@tasselx/pi-web 1.5.0 → 1.6.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 (487) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +18 -15
  3. package/.next/build-manifest.json +4 -4
  4. package/.next/next-server.js.nft.json +1 -1
  5. package/.next/prerender-manifest.json +7 -7
  6. package/.next/react-loadable-manifest.json +1 -1
  7. package/.next/required-server-files.js +7 -7
  8. package/.next/required-server-files.json +7 -7
  9. package/.next/routes-manifest.json +18 -0
  10. package/.next/server/app/_global-error/page.js +2 -2
  11. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  12. package/.next/server/app/_global-error.html +1 -1
  13. package/.next/server/app/_global-error.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  16. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  17. package/.next/server/app/_not-found/page.js +1 -1
  18. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  19. package/.next/server/app/_not-found.html +1 -1
  20. package/.next/server/app/_not-found.rsc +5 -5
  21. package/.next/server/app/_not-found.segments/_full.segment.rsc +5 -5
  22. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +4 -4
  23. package/.next/server/app/_not-found.segments/_tree.segment.rsc +3 -3
  24. package/.next/server/app/api/agent/[id]/bash-output/route.js +1 -1
  25. package/.next/server/app/api/agent/[id]/bash-output/route_client-reference-manifest.js +1 -1
  26. package/.next/server/app/api/agent/[id]/events/route.js +2 -2
  27. package/.next/server/app/api/agent/[id]/events/route_client-reference-manifest.js +1 -1
  28. package/.next/server/app/api/agent/[id]/lease/route.js +1 -1
  29. package/.next/server/app/api/agent/[id]/lease/route_client-reference-manifest.js +1 -1
  30. package/.next/server/app/api/agent/[id]/route.js +1 -1
  31. package/.next/server/app/api/agent/[id]/route_client-reference-manifest.js +1 -1
  32. package/.next/server/app/api/agent/debug/route.js +2 -2
  33. package/.next/server/app/api/agent/debug/route_client-reference-manifest.js +1 -1
  34. package/.next/server/app/api/agent/new/route.js +1 -1
  35. package/.next/server/app/api/agent/new/route_client-reference-manifest.js +1 -1
  36. package/.next/server/app/api/agent/running/route.js +1 -1
  37. package/.next/server/app/api/agent/running/route_client-reference-manifest.js +1 -1
  38. package/.next/server/app/api/app-update/route.js +1 -1
  39. package/.next/server/app/api/app-update/route_client-reference-manifest.js +1 -1
  40. package/.next/server/app/api/auth/api-key/[provider]/route.js +1 -1
  41. package/.next/server/app/api/auth/api-key/[provider]/route_client-reference-manifest.js +1 -1
  42. package/.next/server/app/api/auth/login/[provider]/route.js +1 -1
  43. package/.next/server/app/api/auth/login/[provider]/route_client-reference-manifest.js +1 -1
  44. package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
  45. package/.next/server/app/api/auth/logout/[provider]/route_client-reference-manifest.js +1 -1
  46. package/.next/server/app/api/auth/providers/route.js +1 -1
  47. package/.next/server/app/api/auth/providers/route_client-reference-manifest.js +1 -1
  48. package/.next/server/app/api/cache-miss-notices/route.js +1 -1
  49. package/.next/server/app/api/cache-miss-notices/route_client-reference-manifest.js +1 -1
  50. package/.next/server/app/api/cwd/browse/route.js +1 -1
  51. package/.next/server/app/api/cwd/browse/route_client-reference-manifest.js +1 -1
  52. package/.next/server/app/api/cwd/pick/route.js +1 -1
  53. package/.next/server/app/api/cwd/pick/route_client-reference-manifest.js +1 -1
  54. package/.next/server/app/api/cwd/validate/route.js +1 -1
  55. package/.next/server/app/api/cwd/validate/route_client-reference-manifest.js +1 -1
  56. package/.next/server/app/api/default-cwd/route.js +1 -1
  57. package/.next/server/app/api/default-cwd/route_client-reference-manifest.js +1 -1
  58. package/.next/server/app/api/file-index/route.js +1 -1
  59. package/.next/server/app/api/file-index/route_client-reference-manifest.js +1 -1
  60. package/.next/server/app/api/files/[...path]/route.js +1 -1
  61. package/.next/server/app/api/files/[...path]/route_client-reference-manifest.js +1 -1
  62. package/.next/server/app/api/git/diff/route.js +2 -2
  63. package/.next/server/app/api/git/diff/route_client-reference-manifest.js +1 -1
  64. package/.next/server/app/api/git/status/route.js +2 -2
  65. package/.next/server/app/api/git/status/route_client-reference-manifest.js +1 -1
  66. package/.next/server/app/api/home/route.js +1 -1
  67. package/.next/server/app/api/home/route_client-reference-manifest.js +1 -1
  68. package/.next/server/app/api/mcp/route.js +1 -1
  69. package/.next/server/app/api/mcp/route_client-reference-manifest.js +1 -1
  70. package/.next/server/app/api/mcp/sign-in/[flowId]/route.js +1 -1
  71. package/.next/server/app/api/mcp/sign-in/[flowId]/route_client-reference-manifest.js +1 -1
  72. package/.next/server/app/api/mcp/sign-in/route.js +1 -1
  73. package/.next/server/app/api/mcp/sign-in/route_client-reference-manifest.js +1 -1
  74. package/.next/server/app/api/mcp/test/route.js +1 -1
  75. package/.next/server/app/api/mcp/test/route_client-reference-manifest.js +1 -1
  76. package/.next/server/app/api/models/enabled/route.js +1 -1
  77. package/.next/server/app/api/models/enabled/route_client-reference-manifest.js +1 -1
  78. package/.next/server/app/api/models/refresh/route.js +1 -1
  79. package/.next/server/app/api/models/refresh/route_client-reference-manifest.js +1 -1
  80. package/.next/server/app/api/models/route.js +1 -1
  81. package/.next/server/app/api/models/route_client-reference-manifest.js +1 -1
  82. package/.next/server/app/api/models-config/catalog/route.js +1 -1
  83. package/.next/server/app/api/models-config/catalog/route_client-reference-manifest.js +1 -1
  84. package/.next/server/app/api/models-config/discover/route.js +1 -1
  85. package/.next/server/app/api/models-config/discover/route_client-reference-manifest.js +1 -1
  86. package/.next/server/app/api/models-config/route.js +1 -1
  87. package/.next/server/app/api/models-config/route_client-reference-manifest.js +1 -1
  88. package/.next/server/app/api/models-config/test/route.js +1 -1
  89. package/.next/server/app/api/models-config/test/route_client-reference-manifest.js +1 -1
  90. package/.next/server/app/api/open-in-explorer/route.js +1 -1
  91. package/.next/server/app/api/open-in-explorer/route_client-reference-manifest.js +1 -1
  92. package/.next/server/app/api/plugins/check/route.js +1 -1
  93. package/.next/server/app/api/plugins/check/route_client-reference-manifest.js +1 -1
  94. package/.next/server/app/api/plugins/route.js +1 -1
  95. package/.next/server/app/api/plugins/route_client-reference-manifest.js +1 -1
  96. package/.next/server/app/api/project-trust/route.js +1 -1
  97. package/.next/server/app/api/project-trust/route_client-reference-manifest.js +1 -1
  98. package/.next/server/app/api/provider-usage/query/route.js +1 -1
  99. package/.next/server/app/api/provider-usage/query/route_client-reference-manifest.js +1 -1
  100. package/.next/server/app/api/push/config/route.js +1 -1
  101. package/.next/server/app/api/push/config/route_client-reference-manifest.js +1 -1
  102. package/.next/server/app/api/push/subscribe/route.js +1 -1
  103. package/.next/server/app/api/push/subscribe/route_client-reference-manifest.js +1 -1
  104. package/.next/server/app/api/sessions/[id]/auto-name/route.js +2 -2
  105. package/.next/server/app/api/sessions/[id]/auto-name/route_client-reference-manifest.js +1 -1
  106. package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
  107. package/.next/server/app/api/sessions/[id]/context/route_client-reference-manifest.js +1 -1
  108. package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js +1 -1
  109. package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route_client-reference-manifest.js +1 -1
  110. package/.next/server/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route.js +1 -1
  111. package/.next/server/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route_client-reference-manifest.js +1 -1
  112. package/.next/server/app/api/sessions/[id]/export/route.js +2 -2
  113. package/.next/server/app/api/sessions/[id]/export/route_client-reference-manifest.js +1 -1
  114. package/.next/server/app/api/sessions/[id]/fork/route.js +1 -1
  115. package/.next/server/app/api/sessions/[id]/fork/route_client-reference-manifest.js +1 -1
  116. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  117. package/.next/server/app/api/sessions/[id]/route_client-reference-manifest.js +1 -1
  118. package/.next/server/app/api/sessions/[id]/share/route.js +2 -2
  119. package/.next/server/app/api/sessions/[id]/share/route_client-reference-manifest.js +1 -1
  120. package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
  121. package/.next/server/app/api/sessions/[id]/state/route_client-reference-manifest.js +1 -1
  122. package/.next/server/app/api/sessions/delete/route.js +1 -1
  123. package/.next/server/app/api/sessions/delete/route_client-reference-manifest.js +1 -1
  124. package/.next/server/app/api/sessions/import/pick/route.js +1 -1
  125. package/.next/server/app/api/sessions/import/pick/route_client-reference-manifest.js +1 -1
  126. package/.next/server/app/api/sessions/import/route.js +2 -2
  127. package/.next/server/app/api/sessions/import/route_client-reference-manifest.js +1 -1
  128. package/.next/server/app/api/sessions/route.js +1 -1
  129. package/.next/server/app/api/sessions/route_client-reference-manifest.js +1 -1
  130. package/.next/server/app/api/sessions/search/route.js +1 -1
  131. package/.next/server/app/api/sessions/search/route_client-reference-manifest.js +1 -1
  132. package/.next/server/app/api/sessions/stats/route.js +1 -1
  133. package/.next/server/app/api/sessions/stats/route_client-reference-manifest.js +1 -1
  134. package/.next/server/app/api/sessions/ui-state/route.js +1 -1
  135. package/.next/server/app/api/sessions/ui-state/route_client-reference-manifest.js +1 -1
  136. package/.next/server/app/api/skills/check/route.js +1 -1
  137. package/.next/server/app/api/skills/check/route.js.nft.json +1 -1
  138. package/.next/server/app/api/skills/check/route_client-reference-manifest.js +1 -1
  139. package/.next/server/app/api/skills/content/route.js +1 -1
  140. package/.next/server/app/api/skills/content/route.js.nft.json +1 -1
  141. package/.next/server/app/api/skills/content/route_client-reference-manifest.js +1 -1
  142. package/.next/server/app/api/skills/import/pick/route.js +1 -0
  143. package/.next/server/app/api/skills/import/pick/route.js.nft.json +1 -0
  144. package/.next/server/app/api/skills/import/pick/route_client-reference-manifest.js +1 -0
  145. package/.next/server/app/api/skills/import/route.js +1 -0
  146. package/.next/server/app/api/skills/import/route.js.nft.json +1 -0
  147. package/.next/server/app/api/skills/import/route_client-reference-manifest.js +1 -0
  148. package/.next/server/app/api/skills/install/route.js +1 -1
  149. package/.next/server/app/api/skills/install/route_client-reference-manifest.js +1 -1
  150. package/.next/server/app/api/skills/remove/route.js +1 -0
  151. package/.next/server/app/api/skills/remove/route.js.nft.json +1 -0
  152. package/.next/server/app/api/skills/remove/route_client-reference-manifest.js +1 -0
  153. package/.next/server/app/api/skills/route.js +1 -1
  154. package/.next/server/app/api/skills/route.js.nft.json +1 -1
  155. package/.next/server/app/api/skills/route_client-reference-manifest.js +1 -1
  156. package/.next/server/app/api/skills/search/route.js +1 -1
  157. package/.next/server/app/api/skills/search/route_client-reference-manifest.js +1 -1
  158. package/.next/server/app/api/skills/update/route.js +1 -1
  159. package/.next/server/app/api/skills/update/route.js.nft.json +1 -1
  160. package/.next/server/app/api/skills/update/route_client-reference-manifest.js +1 -1
  161. package/.next/server/app/api/sleep-inhibit/route.js +1 -1
  162. package/.next/server/app/api/sleep-inhibit/route_client-reference-manifest.js +1 -1
  163. package/.next/server/app/api/subagents/[id]/route.js +1 -1
  164. package/.next/server/app/api/subagents/[id]/route_client-reference-manifest.js +1 -1
  165. package/.next/server/app/api/subagents/profiles/route.js +1 -1
  166. package/.next/server/app/api/subagents/profiles/route_client-reference-manifest.js +1 -1
  167. package/.next/server/app/api/subagents/settings/route.js +1 -1
  168. package/.next/server/app/api/subagents/settings/route_client-reference-manifest.js +1 -1
  169. package/.next/server/app/api/terminal/[id]/events/route.js +1 -1
  170. package/.next/server/app/api/terminal/[id]/events/route_client-reference-manifest.js +1 -1
  171. package/.next/server/app/api/terminal/[id]/route.js +1 -1
  172. package/.next/server/app/api/terminal/[id]/route_client-reference-manifest.js +1 -1
  173. package/.next/server/app/api/terminal/route.js +1 -1
  174. package/.next/server/app/api/terminal/route_client-reference-manifest.js +1 -1
  175. package/.next/server/app/api/tools/settings/route.js +1 -1
  176. package/.next/server/app/api/tools/settings/route_client-reference-manifest.js +1 -1
  177. package/.next/server/app/api/web-auth/route.js +1 -1
  178. package/.next/server/app/api/web-auth/route_client-reference-manifest.js +1 -1
  179. package/.next/server/app/api/worktrees/route.js +1 -1
  180. package/.next/server/app/api/worktrees/route_client-reference-manifest.js +1 -1
  181. package/.next/server/app/favicon.ico/route.js +1 -1
  182. package/.next/server/app/index.html +1 -1
  183. package/.next/server/app/index.rsc +8 -8
  184. package/.next/server/app/index.segments/__PAGE__.segment.rsc +7 -7
  185. package/.next/server/app/index.segments/_full.segment.rsc +8 -8
  186. package/.next/server/app/index.segments/_tree.segment.rsc +3 -3
  187. package/.next/server/app/login/page.js +1 -1
  188. package/.next/server/app/login/page.js.nft.json +1 -1
  189. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  190. package/.next/server/app/login.html +1 -1
  191. package/.next/server/app/login.rsc +7 -7
  192. package/.next/server/app/login.segments/_full.segment.rsc +7 -7
  193. package/.next/server/app/login.segments/_tree.segment.rsc +3 -3
  194. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +6 -6
  195. package/.next/server/app/manifest.webmanifest/route.js +1 -17
  196. package/.next/server/app/manifest.webmanifest/route.js.nft.json +1 -1
  197. package/.next/server/app/manifest.webmanifest/route_client-reference-manifest.js +1 -1
  198. package/.next/server/app/page.js +83 -10
  199. package/.next/server/app/page.js.nft.json +1 -1
  200. package/.next/server/app/page_client-reference-manifest.js +1 -1
  201. package/.next/server/app-paths-manifest.json +18 -15
  202. package/.next/server/chunks/1906.js +1 -1
  203. package/.next/server/chunks/1944.js +1 -0
  204. package/.next/server/chunks/2243.js +1 -1
  205. package/.next/server/chunks/2430.js +3 -3
  206. package/.next/server/chunks/2970.js +1 -1
  207. package/.next/server/chunks/3757.js +1 -1
  208. package/.next/server/chunks/3824.js +1 -1
  209. package/.next/server/chunks/4315.js +1 -1
  210. package/.next/server/chunks/5582.js +2 -2
  211. package/.next/server/chunks/5799.js +1 -0
  212. package/.next/server/chunks/6429.js +8 -6
  213. package/.next/server/functions-config-manifest.json +1 -0
  214. package/.next/server/middleware-build-manifest.js +1 -1
  215. package/.next/server/middleware-react-loadable-manifest.js +1 -1
  216. package/.next/server/middleware.js +4 -4
  217. package/.next/server/next-font-manifest.js +1 -1
  218. package/.next/server/next-font-manifest.json +1 -1
  219. package/.next/server/pages/404.html +1 -1
  220. package/.next/server/pages/500.html +1 -1
  221. package/.next/server/preview-props.json +3 -3
  222. package/.next/server/server-reference-manifest.json +1 -1
  223. package/.next/static/chunks/1278-7223b9e9655c6650.js +1 -0
  224. package/.next/static/chunks/{7379.078f0917cc6a0349.js → 7379.dbf01c504140289e.js} +1 -1
  225. package/.next/static/chunks/app/_global-error/page-0136693aa0b2412d.js +1 -0
  226. package/.next/static/chunks/app/_not-found/{page-35dee0d93253f38c.js → page-1e1cf8cba5576cd4.js} +1 -1
  227. package/.next/static/chunks/app/api/agent/[id]/bash-output/route-0136693aa0b2412d.js +1 -0
  228. package/.next/static/chunks/app/api/agent/[id]/events/route-0136693aa0b2412d.js +1 -0
  229. package/.next/static/chunks/app/api/agent/[id]/lease/route-0136693aa0b2412d.js +1 -0
  230. package/.next/static/chunks/app/api/agent/[id]/route-0136693aa0b2412d.js +1 -0
  231. package/.next/static/chunks/app/api/agent/debug/route-0136693aa0b2412d.js +1 -0
  232. package/.next/static/chunks/app/api/agent/new/route-0136693aa0b2412d.js +1 -0
  233. package/.next/static/chunks/app/api/agent/running/route-0136693aa0b2412d.js +1 -0
  234. package/.next/static/chunks/app/api/app-update/route-0136693aa0b2412d.js +1 -0
  235. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-0136693aa0b2412d.js +1 -0
  236. package/.next/static/chunks/app/api/auth/login/[provider]/route-0136693aa0b2412d.js +1 -0
  237. package/.next/static/chunks/app/api/auth/logout/[provider]/route-0136693aa0b2412d.js +1 -0
  238. package/.next/static/chunks/app/api/auth/providers/route-0136693aa0b2412d.js +1 -0
  239. package/.next/static/chunks/app/api/cache-miss-notices/route-0136693aa0b2412d.js +1 -0
  240. package/.next/static/chunks/app/api/cwd/browse/route-0136693aa0b2412d.js +1 -0
  241. package/.next/static/chunks/app/api/cwd/pick/route-0136693aa0b2412d.js +1 -0
  242. package/.next/static/chunks/app/api/cwd/validate/route-0136693aa0b2412d.js +1 -0
  243. package/.next/static/chunks/app/api/default-cwd/route-0136693aa0b2412d.js +1 -0
  244. package/.next/static/chunks/app/api/file-index/route-0136693aa0b2412d.js +1 -0
  245. package/.next/static/chunks/app/api/files/[...path]/route-0136693aa0b2412d.js +1 -0
  246. package/.next/static/chunks/app/api/git/diff/route-0136693aa0b2412d.js +1 -0
  247. package/.next/static/chunks/app/api/git/status/route-0136693aa0b2412d.js +1 -0
  248. package/.next/static/chunks/app/api/home/route-0136693aa0b2412d.js +1 -0
  249. package/.next/static/chunks/app/api/mcp/route-0136693aa0b2412d.js +1 -0
  250. package/.next/static/chunks/app/api/mcp/sign-in/[flowId]/route-0136693aa0b2412d.js +1 -0
  251. package/.next/static/chunks/app/api/mcp/sign-in/route-0136693aa0b2412d.js +1 -0
  252. package/.next/static/chunks/app/api/mcp/test/route-0136693aa0b2412d.js +1 -0
  253. package/.next/static/chunks/app/api/models/enabled/route-0136693aa0b2412d.js +1 -0
  254. package/.next/static/chunks/app/api/models/refresh/route-0136693aa0b2412d.js +1 -0
  255. package/.next/static/chunks/app/api/models/route-0136693aa0b2412d.js +1 -0
  256. package/.next/static/chunks/app/api/models-config/catalog/route-0136693aa0b2412d.js +1 -0
  257. package/.next/static/chunks/app/api/models-config/discover/route-0136693aa0b2412d.js +1 -0
  258. package/.next/static/chunks/app/api/models-config/route-0136693aa0b2412d.js +1 -0
  259. package/.next/static/chunks/app/api/models-config/test/route-0136693aa0b2412d.js +1 -0
  260. package/.next/static/chunks/app/api/open-in-explorer/route-0136693aa0b2412d.js +1 -0
  261. package/.next/static/chunks/app/api/plugins/check/route-0136693aa0b2412d.js +1 -0
  262. package/.next/static/chunks/app/api/plugins/route-0136693aa0b2412d.js +1 -0
  263. package/.next/static/chunks/app/api/project-trust/route-0136693aa0b2412d.js +1 -0
  264. package/.next/static/chunks/app/api/provider-usage/query/route-0136693aa0b2412d.js +1 -0
  265. package/.next/static/chunks/app/api/push/config/route-0136693aa0b2412d.js +1 -0
  266. package/.next/static/chunks/app/api/push/subscribe/route-0136693aa0b2412d.js +1 -0
  267. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-0136693aa0b2412d.js +1 -0
  268. package/.next/static/chunks/app/api/sessions/[id]/context/route-0136693aa0b2412d.js +1 -0
  269. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-0136693aa0b2412d.js +1 -0
  270. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route-0136693aa0b2412d.js +1 -0
  271. package/.next/static/chunks/app/api/sessions/[id]/export/route-0136693aa0b2412d.js +1 -0
  272. package/.next/static/chunks/app/api/sessions/[id]/fork/route-0136693aa0b2412d.js +1 -0
  273. package/.next/static/chunks/app/api/sessions/[id]/route-0136693aa0b2412d.js +1 -0
  274. package/.next/static/chunks/app/api/sessions/[id]/share/route-0136693aa0b2412d.js +1 -0
  275. package/.next/static/chunks/app/api/sessions/[id]/state/route-0136693aa0b2412d.js +1 -0
  276. package/.next/static/chunks/app/api/sessions/delete/route-0136693aa0b2412d.js +1 -0
  277. package/.next/static/chunks/app/api/sessions/import/pick/route-0136693aa0b2412d.js +1 -0
  278. package/.next/static/chunks/app/api/sessions/import/route-0136693aa0b2412d.js +1 -0
  279. package/.next/static/chunks/app/api/sessions/route-0136693aa0b2412d.js +1 -0
  280. package/.next/static/chunks/app/api/sessions/search/route-0136693aa0b2412d.js +1 -0
  281. package/.next/static/chunks/app/api/sessions/stats/route-0136693aa0b2412d.js +1 -0
  282. package/.next/static/chunks/app/api/sessions/ui-state/route-0136693aa0b2412d.js +1 -0
  283. package/.next/static/chunks/app/api/skills/check/route-0136693aa0b2412d.js +1 -0
  284. package/.next/static/chunks/app/api/skills/content/route-0136693aa0b2412d.js +1 -0
  285. package/.next/static/chunks/app/api/skills/import/pick/route-0136693aa0b2412d.js +1 -0
  286. package/.next/static/chunks/app/api/skills/import/route-0136693aa0b2412d.js +1 -0
  287. package/.next/static/chunks/app/api/skills/install/route-0136693aa0b2412d.js +1 -0
  288. package/.next/static/chunks/app/api/skills/remove/route-0136693aa0b2412d.js +1 -0
  289. package/.next/static/chunks/app/api/skills/route-0136693aa0b2412d.js +1 -0
  290. package/.next/static/chunks/app/api/skills/search/route-0136693aa0b2412d.js +1 -0
  291. package/.next/static/chunks/app/api/skills/update/route-0136693aa0b2412d.js +1 -0
  292. package/.next/static/chunks/app/api/sleep-inhibit/route-0136693aa0b2412d.js +1 -0
  293. package/.next/static/chunks/app/api/subagents/[id]/route-0136693aa0b2412d.js +1 -0
  294. package/.next/static/chunks/app/api/subagents/profiles/route-0136693aa0b2412d.js +1 -0
  295. package/.next/static/chunks/app/api/subagents/settings/route-0136693aa0b2412d.js +1 -0
  296. package/.next/static/chunks/app/api/terminal/[id]/events/route-0136693aa0b2412d.js +1 -0
  297. package/.next/static/chunks/app/api/terminal/[id]/route-0136693aa0b2412d.js +1 -0
  298. package/.next/static/chunks/app/api/terminal/route-0136693aa0b2412d.js +1 -0
  299. package/.next/static/chunks/app/api/tools/settings/route-0136693aa0b2412d.js +1 -0
  300. package/.next/static/chunks/app/api/web-auth/route-0136693aa0b2412d.js +1 -0
  301. package/.next/static/chunks/app/api/worktrees/route-0136693aa0b2412d.js +1 -0
  302. package/.next/static/chunks/app/{layout-5f83006eeeda0674.js → layout-a29733531748d73d.js} +1 -1
  303. package/.next/static/chunks/app/login/{page-7d17aa0961f2fcbe.js → page-b414cd944710d72a.js} +1 -1
  304. package/.next/static/chunks/app/manifest.webmanifest/route-0136693aa0b2412d.js +1 -0
  305. package/.next/static/chunks/app/page-9a4f80b84616d8c6.js +1202 -0
  306. package/.next/static/chunks/main-app-a98576891fdd8f60.js +1 -0
  307. package/.next/static/chunks/next/dist/client/components/builtin/app-error-0136693aa0b2412d.js +1 -0
  308. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-0136693aa0b2412d.js +1 -0
  309. package/.next/static/chunks/next/dist/client/components/builtin/global-error-30078bc26a2476fc.js +1 -0
  310. package/.next/static/chunks/next/dist/client/components/builtin/not-found-0136693aa0b2412d.js +1 -0
  311. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-0136693aa0b2412d.js +1 -0
  312. package/.next/static/chunks/{webpack-95292085cd40fbc6.js → webpack-e76cafb8cfa7a24a.js} +1 -1
  313. package/.next/static/css/338a13865b07f69a.css +1 -0
  314. package/.next/static/css/c038d8937e704328.css +1 -0
  315. package/.next/static/kxN9W7vtCWqWWjxrXMwKG/_buildManifest.js +1 -0
  316. package/.next/trace +188 -183
  317. package/.next/trace-build +1 -1
  318. package/.next/types/app/api/agent/[id]/bash-output/route.ts +1 -1
  319. package/.next/types/app/api/agent/[id]/events/route.ts +1 -1
  320. package/.next/types/app/api/agent/[id]/lease/route.ts +1 -1
  321. package/.next/types/app/api/agent/[id]/route.ts +1 -1
  322. package/.next/types/app/api/agent/debug/route.ts +1 -1
  323. package/.next/types/app/api/agent/new/route.ts +1 -1
  324. package/.next/types/app/api/agent/running/route.ts +1 -1
  325. package/.next/types/app/api/app-update/route.ts +1 -1
  326. package/.next/types/app/api/auth/api-key/[provider]/route.ts +1 -1
  327. package/.next/types/app/api/auth/login/[provider]/route.ts +1 -1
  328. package/.next/types/app/api/auth/logout/[provider]/route.ts +1 -1
  329. package/.next/types/app/api/auth/providers/route.ts +1 -1
  330. package/.next/types/app/api/cache-miss-notices/route.ts +1 -1
  331. package/.next/types/app/api/cwd/browse/route.ts +1 -1
  332. package/.next/types/app/api/cwd/pick/route.ts +1 -1
  333. package/.next/types/app/api/cwd/validate/route.ts +1 -1
  334. package/.next/types/app/api/default-cwd/route.ts +1 -1
  335. package/.next/types/app/api/file-index/route.ts +1 -1
  336. package/.next/types/app/api/files/[...path]/route.ts +1 -1
  337. package/.next/types/app/api/git/diff/route.ts +1 -1
  338. package/.next/types/app/api/git/status/route.ts +1 -1
  339. package/.next/types/app/api/home/route.ts +1 -1
  340. package/.next/types/app/api/mcp/route.ts +1 -1
  341. package/.next/types/app/api/mcp/sign-in/[flowId]/route.ts +1 -1
  342. package/.next/types/app/api/mcp/sign-in/route.ts +1 -1
  343. package/.next/types/app/api/mcp/test/route.ts +1 -1
  344. package/.next/types/app/api/models/enabled/route.ts +1 -1
  345. package/.next/types/app/api/models/refresh/route.ts +1 -1
  346. package/.next/types/app/api/models/route.ts +1 -1
  347. package/.next/types/app/api/models-config/catalog/route.ts +1 -1
  348. package/.next/types/app/api/models-config/discover/route.ts +1 -1
  349. package/.next/types/app/api/models-config/route.ts +1 -1
  350. package/.next/types/app/api/models-config/test/route.ts +1 -1
  351. package/.next/types/app/api/open-in-explorer/route.ts +1 -1
  352. package/.next/types/app/api/plugins/check/route.ts +1 -1
  353. package/.next/types/app/api/plugins/route.ts +1 -1
  354. package/.next/types/app/api/project-trust/route.ts +1 -1
  355. package/.next/types/app/api/provider-usage/query/route.ts +1 -1
  356. package/.next/types/app/api/push/config/route.ts +1 -1
  357. package/.next/types/app/api/push/subscribe/route.ts +1 -1
  358. package/.next/types/app/api/sessions/[id]/auto-name/route.ts +1 -1
  359. package/.next/types/app/api/sessions/[id]/context/route.ts +1 -1
  360. package/.next/types/app/api/sessions/[id]/entries/[entryId]/thinking/route.ts +1 -1
  361. package/.next/types/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route.ts +1 -1
  362. package/.next/types/app/api/sessions/[id]/export/route.ts +1 -1
  363. package/.next/types/app/api/sessions/[id]/fork/route.ts +1 -1
  364. package/.next/types/app/api/sessions/[id]/route.ts +1 -1
  365. package/.next/types/app/api/sessions/[id]/share/route.ts +1 -1
  366. package/.next/types/app/api/sessions/[id]/state/route.ts +1 -1
  367. package/.next/types/app/api/sessions/delete/route.ts +1 -1
  368. package/.next/types/app/api/sessions/import/pick/route.ts +1 -1
  369. package/.next/types/app/api/sessions/import/route.ts +1 -1
  370. package/.next/types/app/api/sessions/route.ts +1 -1
  371. package/.next/types/app/api/sessions/search/route.ts +1 -1
  372. package/.next/types/app/api/sessions/stats/route.ts +1 -1
  373. package/.next/types/app/api/sessions/ui-state/route.ts +1 -1
  374. package/.next/types/app/api/skills/check/route.ts +1 -1
  375. package/.next/types/app/api/skills/content/route.ts +1 -1
  376. package/.next/types/app/api/skills/import/pick/route.ts +355 -0
  377. package/.next/types/app/api/skills/import/route.ts +355 -0
  378. package/.next/types/app/api/skills/install/route.ts +1 -1
  379. package/.next/types/app/api/skills/remove/route.ts +355 -0
  380. package/.next/types/app/api/skills/route.ts +1 -1
  381. package/.next/types/app/api/skills/search/route.ts +1 -1
  382. package/.next/types/app/api/skills/update/route.ts +1 -1
  383. package/.next/types/app/api/sleep-inhibit/route.ts +1 -1
  384. package/.next/types/app/api/subagents/[id]/route.ts +1 -1
  385. package/.next/types/app/api/subagents/profiles/route.ts +1 -1
  386. package/.next/types/app/api/subagents/settings/route.ts +1 -1
  387. package/.next/types/app/api/terminal/[id]/events/route.ts +1 -1
  388. package/.next/types/app/api/terminal/[id]/route.ts +1 -1
  389. package/.next/types/app/api/terminal/route.ts +1 -1
  390. package/.next/types/app/api/tools/settings/route.ts +1 -1
  391. package/.next/types/app/api/web-auth/route.ts +1 -1
  392. package/.next/types/app/api/worktrees/route.ts +1 -1
  393. package/.next/types/app/layout.ts +1 -1
  394. package/.next/types/app/login/page.ts +1 -1
  395. package/.next/types/app/manifest.webmanifest/route.ts +355 -0
  396. package/.next/types/app/page.ts +1 -1
  397. package/.next/types/routes.d.ts +5 -1
  398. package/.next/types/validator.ts +40 -0
  399. package/README.md +4 -0
  400. package/package.json +1 -1
  401. package/.next/server/chunks/7979.js +0 -1
  402. package/.next/static/R5PN1Mg8bAb01xwQ2DM9k/_buildManifest.js +0 -1
  403. package/.next/static/chunks/1278-8eaba54dabdd20f4.js +0 -1
  404. package/.next/static/chunks/app/_global-error/page-372b1b76af46907f.js +0 -1
  405. package/.next/static/chunks/app/api/agent/[id]/bash-output/route-372b1b76af46907f.js +0 -1
  406. package/.next/static/chunks/app/api/agent/[id]/events/route-372b1b76af46907f.js +0 -1
  407. package/.next/static/chunks/app/api/agent/[id]/lease/route-372b1b76af46907f.js +0 -1
  408. package/.next/static/chunks/app/api/agent/[id]/route-372b1b76af46907f.js +0 -1
  409. package/.next/static/chunks/app/api/agent/debug/route-372b1b76af46907f.js +0 -1
  410. package/.next/static/chunks/app/api/agent/new/route-372b1b76af46907f.js +0 -1
  411. package/.next/static/chunks/app/api/agent/running/route-372b1b76af46907f.js +0 -1
  412. package/.next/static/chunks/app/api/app-update/route-372b1b76af46907f.js +0 -1
  413. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-372b1b76af46907f.js +0 -1
  414. package/.next/static/chunks/app/api/auth/login/[provider]/route-372b1b76af46907f.js +0 -1
  415. package/.next/static/chunks/app/api/auth/logout/[provider]/route-372b1b76af46907f.js +0 -1
  416. package/.next/static/chunks/app/api/auth/providers/route-372b1b76af46907f.js +0 -1
  417. package/.next/static/chunks/app/api/cache-miss-notices/route-372b1b76af46907f.js +0 -1
  418. package/.next/static/chunks/app/api/cwd/browse/route-372b1b76af46907f.js +0 -1
  419. package/.next/static/chunks/app/api/cwd/pick/route-372b1b76af46907f.js +0 -1
  420. package/.next/static/chunks/app/api/cwd/validate/route-372b1b76af46907f.js +0 -1
  421. package/.next/static/chunks/app/api/default-cwd/route-372b1b76af46907f.js +0 -1
  422. package/.next/static/chunks/app/api/file-index/route-372b1b76af46907f.js +0 -1
  423. package/.next/static/chunks/app/api/files/[...path]/route-372b1b76af46907f.js +0 -1
  424. package/.next/static/chunks/app/api/git/diff/route-372b1b76af46907f.js +0 -1
  425. package/.next/static/chunks/app/api/git/status/route-372b1b76af46907f.js +0 -1
  426. package/.next/static/chunks/app/api/home/route-372b1b76af46907f.js +0 -1
  427. package/.next/static/chunks/app/api/mcp/route-372b1b76af46907f.js +0 -1
  428. package/.next/static/chunks/app/api/mcp/sign-in/[flowId]/route-372b1b76af46907f.js +0 -1
  429. package/.next/static/chunks/app/api/mcp/sign-in/route-372b1b76af46907f.js +0 -1
  430. package/.next/static/chunks/app/api/mcp/test/route-372b1b76af46907f.js +0 -1
  431. package/.next/static/chunks/app/api/models/enabled/route-372b1b76af46907f.js +0 -1
  432. package/.next/static/chunks/app/api/models/refresh/route-372b1b76af46907f.js +0 -1
  433. package/.next/static/chunks/app/api/models/route-372b1b76af46907f.js +0 -1
  434. package/.next/static/chunks/app/api/models-config/catalog/route-372b1b76af46907f.js +0 -1
  435. package/.next/static/chunks/app/api/models-config/discover/route-372b1b76af46907f.js +0 -1
  436. package/.next/static/chunks/app/api/models-config/route-372b1b76af46907f.js +0 -1
  437. package/.next/static/chunks/app/api/models-config/test/route-372b1b76af46907f.js +0 -1
  438. package/.next/static/chunks/app/api/open-in-explorer/route-372b1b76af46907f.js +0 -1
  439. package/.next/static/chunks/app/api/plugins/check/route-372b1b76af46907f.js +0 -1
  440. package/.next/static/chunks/app/api/plugins/route-372b1b76af46907f.js +0 -1
  441. package/.next/static/chunks/app/api/project-trust/route-372b1b76af46907f.js +0 -1
  442. package/.next/static/chunks/app/api/provider-usage/query/route-372b1b76af46907f.js +0 -1
  443. package/.next/static/chunks/app/api/push/config/route-372b1b76af46907f.js +0 -1
  444. package/.next/static/chunks/app/api/push/subscribe/route-372b1b76af46907f.js +0 -1
  445. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-372b1b76af46907f.js +0 -1
  446. package/.next/static/chunks/app/api/sessions/[id]/context/route-372b1b76af46907f.js +0 -1
  447. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-372b1b76af46907f.js +0 -1
  448. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route-372b1b76af46907f.js +0 -1
  449. package/.next/static/chunks/app/api/sessions/[id]/export/route-372b1b76af46907f.js +0 -1
  450. package/.next/static/chunks/app/api/sessions/[id]/fork/route-372b1b76af46907f.js +0 -1
  451. package/.next/static/chunks/app/api/sessions/[id]/route-372b1b76af46907f.js +0 -1
  452. package/.next/static/chunks/app/api/sessions/[id]/share/route-372b1b76af46907f.js +0 -1
  453. package/.next/static/chunks/app/api/sessions/[id]/state/route-372b1b76af46907f.js +0 -1
  454. package/.next/static/chunks/app/api/sessions/delete/route-372b1b76af46907f.js +0 -1
  455. package/.next/static/chunks/app/api/sessions/import/pick/route-372b1b76af46907f.js +0 -1
  456. package/.next/static/chunks/app/api/sessions/import/route-372b1b76af46907f.js +0 -1
  457. package/.next/static/chunks/app/api/sessions/route-372b1b76af46907f.js +0 -1
  458. package/.next/static/chunks/app/api/sessions/search/route-372b1b76af46907f.js +0 -1
  459. package/.next/static/chunks/app/api/sessions/stats/route-372b1b76af46907f.js +0 -1
  460. package/.next/static/chunks/app/api/sessions/ui-state/route-372b1b76af46907f.js +0 -1
  461. package/.next/static/chunks/app/api/skills/check/route-372b1b76af46907f.js +0 -1
  462. package/.next/static/chunks/app/api/skills/content/route-372b1b76af46907f.js +0 -1
  463. package/.next/static/chunks/app/api/skills/install/route-372b1b76af46907f.js +0 -1
  464. package/.next/static/chunks/app/api/skills/route-372b1b76af46907f.js +0 -1
  465. package/.next/static/chunks/app/api/skills/search/route-372b1b76af46907f.js +0 -1
  466. package/.next/static/chunks/app/api/skills/update/route-372b1b76af46907f.js +0 -1
  467. package/.next/static/chunks/app/api/sleep-inhibit/route-372b1b76af46907f.js +0 -1
  468. package/.next/static/chunks/app/api/subagents/[id]/route-372b1b76af46907f.js +0 -1
  469. package/.next/static/chunks/app/api/subagents/profiles/route-372b1b76af46907f.js +0 -1
  470. package/.next/static/chunks/app/api/subagents/settings/route-372b1b76af46907f.js +0 -1
  471. package/.next/static/chunks/app/api/terminal/[id]/events/route-372b1b76af46907f.js +0 -1
  472. package/.next/static/chunks/app/api/terminal/[id]/route-372b1b76af46907f.js +0 -1
  473. package/.next/static/chunks/app/api/terminal/route-372b1b76af46907f.js +0 -1
  474. package/.next/static/chunks/app/api/tools/settings/route-372b1b76af46907f.js +0 -1
  475. package/.next/static/chunks/app/api/web-auth/route-372b1b76af46907f.js +0 -1
  476. package/.next/static/chunks/app/api/worktrees/route-372b1b76af46907f.js +0 -1
  477. package/.next/static/chunks/app/manifest.webmanifest/route-372b1b76af46907f.js +0 -1
  478. package/.next/static/chunks/app/page-5c9e0f41ea07cfdd.js +0 -1129
  479. package/.next/static/chunks/main-app-4b56fc85be3f7823.js +0 -1
  480. package/.next/static/chunks/next/dist/client/components/builtin/app-error-372b1b76af46907f.js +0 -1
  481. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-372b1b76af46907f.js +0 -1
  482. package/.next/static/chunks/next/dist/client/components/builtin/global-error-064e367d6001dbac.js +0 -1
  483. package/.next/static/chunks/next/dist/client/components/builtin/not-found-372b1b76af46907f.js +0 -1
  484. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-372b1b76af46907f.js +0 -1
  485. package/.next/static/css/600a486e13adbe4a.css +0 -1
  486. package/.next/static/css/f38e4e9c1d25d157.css +0 -1
  487. /package/.next/static/{R5PN1Mg8bAb01xwQ2DM9k → kxN9W7vtCWqWWjxrXMwKG}/_ssgManifest.js +0 -0
@@ -0,0 +1,1202 @@
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{2849:(e,t,n)=>{"use strict";n.d(t,{m:()=>C});var r=n(95155),i=n(12115),s=n(32316),o=n(21278),l=n(7834),a=n(19870),d=n(28999),c=n(35754),u=n(68925);let p=/^ {0,3}(`{3,}|~{3,})/,h=/^(?:[*+-]|\d{1,9}[.)])(?:[ \t]|$)/,m=/<[A-Za-z!/?]/,f=/`[^`]*`/g;var g=n(8436),x=n(22408);let v="http://www.w3.org/2000/svg";function b(e,t){let n=t.parseFromString(e,"image/svg+xml");return n.getElementsByTagName("parsererror").length>0?null:n.documentElement}function y(e){let{code:t,isStreaming:n}=e,{t:s}=(0,o.s)(),[l,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),f=l&&!n,g=(0,i.useMemo)(()=>{var e;let n,r;return f&&"u">typeof DOMParser?(e=new DOMParser,r=b(n=t,e),r?.localName!=="svg"||null!==r.namespaceURI||r.hasAttribute("xmlns")||(r=b(n=t.replace(/<svg(?=[\s/>])/,`<svg xmlns="${v}"`),e)),r?.localName==="svg"&&r.namespaceURI===v?n:null):void 0},[t,f]),y=(0,i.useMemo)(()=>g?`data:image/svg+xml;charset=utf-8,${encodeURIComponent(g)}`:null,[g]),j=(0,i.useMemo)(()=>(0,r.jsx)(x.hB,{isStreaming:n,previewVisible:f,onToggle:()=>a(e=>!e),title:f?s("i18n.showSvgSource"):s("i18n.previewSvg")}),[n,f,s]);if(!f)return(0,r.jsx)(x.NG,{code:t,lang:"svg",headerAction:j,isStreaming:n});let k=null!==y&&u!==y,w=e=>(0,r.jsx)("img",{src:y??void 0,alt:s("i18n.svgImage"),className:[e,h===y?"is-unsized":""].filter(Boolean).join(" "),onLoad:e=>{let{naturalWidth:t,naturalHeight:n}=e.currentTarget;t&&n||m(y)},onError:()=>p(y)});return(0,r.jsx)(x.wL,{lang:"svg",actions:(0,r.jsxs)(r.Fragment,{children:[k&&g&&(0,r.jsx)(x.fP,{onClick:()=>(0,x.Rb)(g,"image.svg")}),j]}),children:void 0===g?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading"}):k?(0,r.jsxs)(r.Fragment,{children:[!d&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:s("i18n.openSvgViewer"),"aria-label":s("i18n.openSvgViewer"),onClick:()=>c(!0),children:w("svg-block-image")}),d&&(0,r.jsx)(x.nT,{title:s("i18n.svgImage"),label:s("i18n.svgViewer"),onClose:()=>c(!1),children:w("svg-zoom-image")})]}):(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidSvg")})})}let j=(0,i.createContext)(!1);function k(e){let{src:t,alt:n,cwd:s,...o}=e,l=(0,i.useContext)(j);delete o.node;let u="string"==typeof t?t:void 0,p=u?(0,a.Vc)(u,s):null,h=p?`/api/files/${(0,d.HG)(p)}?type=read`:u,m=p??u?.split(/[?#]/,1)[0]??"",f=n?.trim()?n:void 0;if((0,c.EC)(m))return(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:h,"aria-label":f});if((0,c.t9)(m))return(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:h,"aria-label":f});let x=(0,r.jsx)("img",{src:h,alt:n??"",loading:"lazy",...o});return!h||l?x:(0,r.jsx)(g.k,{src:h,alt:n??"",className:"markdown-image",children:x})}function w(e){let{source:t,children:n}=e,{t:s}=(0,o.s)(),[a,d]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-math-display",children:[n,(0,r.jsx)("button",{type:"button",onClick:()=>{(0,l.D)(t).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action markdown-math-copy",children:s(a?"i18n.copied":"i18n.copy")})]})}let S=(0,i.memo)(function(e){let{markdown:t,remarkPlugins:n,urlTransform:i,rehypePlugins:o,components:l}=e;return(0,r.jsx)(s.oz,{remarkPlugins:n,rehypePlugins:o,urlTransform:i,components:l,children:t})}),C=(0,i.memo)(function(e){let{children:t,className:n,isStreaming:s,cwd:o,onOpenFile:l,onNavigateLink:d,keepLineBreaks:c,keepTextLayout:g}=e,v=(0,i.useMemo)(()=>(0,u.Ep)(t),[t]),b=(0,i.useMemo)(()=>s?function(e){let t=e.split("\n");if(/^---[ \t]*\r?$/.test(t[0]))return[e];let n=[],r=[],i=null,s=!1,o=!1,l=!1;for(let e of t){let t=""===e.trim();!l||t||i||s||o||!(r.length>0)||/^[ \t]/.test(e)||h.test(e)||(n.push(r.join("\n")+"\n"),r=[]),r.push(e);let a=e.match(p);if(a){let e=a[1][0],t=a[1].length;i?e===i.marker&&t>=i.size&&(i=null):i={marker:e,size:t}}else if(!i){let t=e.replace(f,"");m.test(t)&&(o=!0),(t.match(/\$\$/g)?.length??0)%2==1&&(s=!s)}l=t}return n.push(r.join("\n")),n}(v):[v],[s,v]),C=(0,i.useMemo)(()=>({code(e){let{className:t,children:n,...i}=e,o=t?.replace("language-","").toLowerCase()??"",l=String(n);return t?.includes("language-")||l.includes("\n")?"mermaid"===o?(0,r.jsx)(x.t,{code:l.replace(/\n$/,""),isStreaming:s,defaultPreview:!0}):"svg"===o?(0,r.jsx)(y,{code:l.replace(/\n$/,""),isStreaming:s}):(0,r.jsx)(x.NG,{code:l.replace(/\n$/,""),lang:o,isStreaming:s}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:n})},pre(e){let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},a(e){let{href:t,children:n,...i}=e;if(delete i.node,d&&t&&!(0,u.AA)(t)){let e=()=>d(t);return(0,r.jsx)(j.Provider,{value:!0,children:(0,r.jsx)("a",{...i,role:"link",tabIndex:0,onClick:e,onKeyDown:t=>{"Enter"===t.key&&e()},children:n})})}if(t?.startsWith("#"))return(0,r.jsx)(j.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,onClick:u.xq,children:n})});let s=l?(0,a.Vc)(t,o):null;return s&&l?(0,r.jsx)(j.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,onClick:e=>{if(!(0,a.pz)(e))return;let n=e.currentTarget.getAttribute("target");n&&"_self"!==n||(e.preventDefault(),l(s,(0,a.XJ)(t)??void 0))},children:n})}):(0,r.jsx)(j.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,target:"_blank",rel:"noopener noreferrer",children:n})})},img:e=>(0,r.jsx)(k,{cwd:o,...e}),ol(e){let{node:t,start:n,style:i,...s}=e,o=String(Math.abs((n??1)+Math.max(t?.children.filter(e=>"element"===e.type&&"li"===e.tagName).length??0,1)-1)).length;return(0,r.jsx)("ol",{start:n,style:{...i,"--ol-marker-digits":Math.max(o,2)},...s})},div(e){let{node:t,children:n,...i}=e,s=t?.properties?.dataMathSource;return"string"==typeof s?(0,r.jsx)(w,{source:s,children:n}):(0,r.jsx)("div",{...i,children:n})},table(e){let{children:t}=e;return(0,r.jsx)("div",{className:"markdown-table-frame",children:(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:t})})})}}),[o,s,l,d]);return(0,r.jsx)("div",{className:["markdown-body",n].filter(Boolean).join(" "),children:b.map((e,t)=>(0,r.jsx)(S,{markdown:e,remarkPlugins:g?u.Hm:c?u.$7:u.u_,urlTransform:l?u.t9:u.SG,rehypePlugins:d?u.o9:u.LO,components:C},t))})})},6872:e=>{e.exports={tabs:"ChatViewTabs_tabs__7CVqD",tab:"ChatViewTabs_tab__j1EpE"}},7413:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>bm});var r=n(95155),i=n(12115),s=n(73321);let o=null;function l(e,t){return e.name&&"Side chat"!==e.name?e.name:t}function a(e){return e?.kind==="subagent"||e?.kind==="side"}function d(e){let t=function(e){let t=new Map(e.map(e=>[e.id,e])),n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,s=r.id,o=null;for(;;){if(n.has(s)){o=n.get(s)??null;break}if(i.has(s))break;i.add(s),e.push(s);let r=t.get(s);if(!r)break;if(!a(r.relation)){o=r.id;break}s=r.relation.parentSessionId}for(let t of e)n.set(t,o)}return n}(e),n=new Map;for(let t of e)a(t.relation)||n.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let r of e){if(!a(r.relation))continue;let e=t.get(r.id),i=e?n.get(e):void 0;i&&(i.subagents.push(r),r.modified>i.latestModified&&(i.latestModified=r.modified))}return[...n.values()].sort((e,t)=>t.latestModified.localeCompare(e.latestModified))}function c(e,t){return e.filter(e=>t.has(e.id)).length}function u(e){return`?session=${encodeURIComponent(e)}`}let p="pi-web:last-open-by-workspace";function h(){try{return window.localStorage}catch{return null}}function m(e){let t=e.getItem(p);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function f(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:h();if(t)try{let n=m(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(p):t.setItem(p,JSON.stringify(n))}catch{}}function g(e){return e.projectKey??e.projectRoot??e.cwd}function x(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=g(n),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{root:e,modified:n.modified})}return[...t.entries()].sort((e,t)=>t[1].modified.localeCompare(e[1].modified)).map(e=>{let[t,{root:n}]=e;return{key:t,root:n}})}let v=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,b=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function y(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function j(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function k(e){return"string"==typeof e&&e.length>0&&e.length<=4096&&"__proto__"!==e}let w=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function S(e){if(null===e)return null;if("string"!=typeof e)return;let t=e.trim();return t?w.test(t)||[...t].length>80?void 0:t:null}let C=new TextEncoder;function N(e){return C.encode(JSON.stringify(e)).length+1}function E(e){let t=1;for(let n of e)t+=N(n);return t}function I(e,t){return e<=1e3&&t<=262144}function $(e){let t=[],n=1;for(let r of e){if(t.length>=1e3)break;let e=N(r);n+e>262144||(t.push(r),n+=e)}return t}function T(e,t){return C.encode(JSON.stringify(e)).length+C.encode(JSON.stringify(t)).length+2}function M(e,t){return e<=1e3&&t<=262144}function R(){return{version:1,revision:0,sessions:{},projects:{}}}function A(e,t,n){let r=b(e,t)?e[t]:void 0;return void 0===n.pinnedAt&&void 0===n.archivedAt?!!r&&(delete e[t],!0):(r?.pinnedAt!==n.pinnedAt||r?.archivedAt!==n.archivedAt)&&(e[t]=n,!0)}function L(e,t){var n;return n=e.projectOrder??[],!(n.length===t.length&&n.every((e,n)=>e===t[n]))&&(0===t.length?delete e.projectOrder:e.projectOrder=t,!0)}function z(e,t){let n=new Set(e),r=[];for(let e of t)n.has(e)||(n.add(e),r.push(e));return r}function P(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:500,n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}let W={desktop:{"pinned-header":28,session:28,"pinned-more":26,group:28,"group-more":26,"group-empty":28,spacer:8,"footer-open":28,"footer-archived":28,"archive-group":28},mobile:{"pinned-header":44,session:44,"pinned-more":36,group:44,"group-more":36,"group-empty":44,spacer:8,"footer-open":44,"footer-archived":44,"archive-group":44}},O="pinned";function F(e,t){return Object.hasOwn(e.sessions,t)?e.sessions[t]:void 0}function D(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function B(e,t){return e===t?0:e>t?-1:1}function H(e){return[e.root.id,...e.subagents.map(e=>e.id)]}function _(e,t){return 0!==t.size&&(t.has(e.root.id)||e.subagents.some(e=>t.has(e.id)))}function U(e,t,n){let r=D(F(t,e.root.id)?.archivedAt);if(null===r||_(e,n))return!1;if(e.root.detailsPending)return!0;let i=Date.parse(e.root.modified);return Number.isNaN(i)||r>=i}function K(e,t,n){return null!==D(F(t,e.root.id)?.pinnedAt)&&!U(e,t,n)}function q(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e.charAt(0);let n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return t.slice(n+1)}function V(e,t){if(Object.hasOwn(t,e.key)){let n=t[e.key];if("boolean"==typeof n)return n}return e.current||e.pinned}function Z(e,t){var n;return{running:_(e,t.runningIds),awaiting:!!t.awaitingIds&&_(e,t.awaitingIds),unread:_(e,t.unreadIds),selected:!!(n=t.selectedSessionId)&&(e.root.id===n||e.subagents.some(e=>e.id===n)),transient:!0===e.root.transient}}function J(e,t){let n=0,r=0,i=0;for(let s of e)t.awaitingIds&&_(s,t.awaitingIds)?r++:_(s,t.runningIds)&&n++,_(s,t.unreadIds)&&i++;return{running:n,awaiting:r,unread:i}}function G(e){return g(e.root)}function Y(e,t){let n=new Map,r=new Map;return{noteFamily(e){let t=G(e);n.has(t)||n.set(t,e.root.projectRoot??e.root.cwd)},get(i){let s,o=r.get(i);if(o)return o;let l=Object.hasOwn(e.projects,i)?e.projects[i]:void 0,a=null!==t&&t.key===i,d=n.get(i)??(a?t.root:void 0)??l?.root??i,c=((s=e.projectNames)&&b(s,i)?s[i]:void 0)??null,u={key:i,root:d,name:c??q(d),customName:c,pinned:void 0!==l,current:a};return r.set(i,u),u}}}function X(e,t,n,r){return{kind:"session",key:`session:${t}:${e.root.id}`,family:e,context:t,project:n,status:Z(e,r)}}function Q(e,t,n,r){let i=e.map((e,n)=>{if(n<t)return!1;let i=Z(e,r);return i.running||i.unread||i.selected}),s=t+n,o=0,l=e.filter((e,n)=>n<t||!!i[n]||n<s&&(o++,!0)),a=Math.max(t,Math.min(s,e.length));for(let t=0;a<e.length&&t<20;a++)!i[a]&&t++;return{visible:l,revealed:o,nextShown:a-t}}function ee(e,t){if(!Object.hasOwn(e,t))return 0;let n=e[t];return"number"==typeof n&&Number.isFinite(n)&&n>0?Math.floor(n):0}function et(e,t){if(!Object.hasOwn(e,t))return e;let n={...e};return delete n[t],n}function en(e,t,n){let r=e-t,i=n>0;return r>0||i?{hidden:r,canShowLess:i}:null}function er(e,t,n,r){let i=r-n,s=[];for(let n of d(e.sessions)){if(G(n)!==t||U(n,e.uiState,e.runningIds)||K(n,e.uiState,e.runningIds))continue;let r=Z(n,e);if(r.running||r.unread||r.selected||r.transient)continue;let o=Date.parse(n.latestModified);Number.isNaN(o)||o>=i||s.push(n.root.id)}return s}function ei(e,t){let n=[],r=0;for(let i of d(e.sessions))if(G(i)===t&&!i.root.transient){if(_(i,e.runningIds)||e.awaitingIds&&_(i,e.awaitingIds)){r++;continue}n.push(i.root.id)}return{ids:n,running:r}}function es(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),o=i["up"===n?s-1:s+1];return o?{anchorKey:o.key,position:"up"===n?"before":"after"}:null}function eo(e,t,n,r,i){if(!Number.isInteger(t)||t<0||t>=e.length-1)return null;let s=e[t],o=e[t+1];return"start"===i?s===n?null:s:s>=n&&o<=n+r?null:Math.max(0,s-Math.max(0,(r-(o-s))/2))}let el="pi-web:sidebar-tab",ea="pi-web:sidebar-groups-v2",ed="pi-web:sidebar-groups",ec="pi-web:sidebar-archive-collapsed",eu="pi-web:sidebar-pins-collapsed",ep="pi-web:sidebar-files-show-ignored",eh="pi-web:sidebar-files-collapsed",em="pi-web:sidebar-changes-view-mode",ef="pi-web:sidebar-non-git-cwds",eg=["pi-web:file-explorer:open","pi-web:sidebar-session-pane-height",ed];function ex(){try{return window.localStorage}catch{return null}}function ev(e){let t={};if(null===e||"object"!=typeof e||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))"__proto__"!==n&&"boolean"==typeof r&&(t[n]=r);return t}function eb(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ex();if(t)try{let n=Object.entries(ev(e)),r=n.length>300?n.slice(n.length-300):n;t.setItem(ea,JSON.stringify(Object.fromEntries(r)))}catch{}}function ey(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ex();if(t)try{t.setItem(ec,JSON.stringify([...new Set(e)].slice(-300)))}catch{}}function ej(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ex();if(!e)return[];try{let t=e.getItem(ef),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];return n.filter(e=>"string"==typeof e&&""!==e).slice(-50)}catch{return[]}}async function ek(e,t){try{let n=await t(`/api/sessions/${encodeURIComponent(e)}/auto-name`,{method:"POST"}),r=await n.json().catch(()=>({})),i="string"==typeof r.title?r.title.trim():"";if(!n.ok||!i)return{error:r.error||`HTTP ${n.status}`};return{title:i}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}async function ew(e,t){let n={deletedRoots:[],deleted:[],running:[],error:null};for(let r=0;r<e.length;r+=500){let i=e.slice(r,r+500);try{let e=await t("/api/sessions/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:i})}),r=await e.json().catch(()=>({}));if(!e.ok||!Array.isArray(r.deleted)){n.error=r.error??`HTTP ${e.status}`;break}let s=new Set(r.deleted);n.deleted.push(...r.deleted),n.deletedRoots.push(...i.filter(e=>s.has(e))),n.running.push(...r.running??[])}catch(e){n.error=e instanceof Error?e.message:String(e);break}}return n}function eS(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function eC(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:eS(e)}let eN=/ · [0-9a-f]{4}$/;function eE(e){let t=eN.exec(e);return t&&0!==t.index?{base:e.slice(0,t.index),suffix:t[0]}:null}function eI(e,t){return{cwd:e.current&&t?t:e.root,projectKey:e.key,projectRoot:e.root}}function e$(e){let t=e.project;return!t||e.projects.some(e=>e.key===t.key)?[...e.projects]:[t,...e.projects]}function eT(e,t){let{key:n,root:r}=e,i=t&&Object.hasOwn(t,n)?t[n]:void 0;return void 0===i?{key:n,root:r}:{key:n,root:r,alias:i}}function eM(e){let t=e.map(e=>({choice:e,name:e.alias??q(e.root)})),n=new Map;for(let{name:e}of t)n.set(e,(n.get(e)??0)+1);return t.map(e=>{let t,r,{choice:i,name:s}=e;return{choice:i,name:s,note:void 0===i.alias&&(n.get(s)??0)>1&&(r=Math.max((t=i.root.replace(/[\\/]+$/,"")).lastIndexOf("/"),t.lastIndexOf("\\")))>0?q(t.slice(0,r)):null}})}let eR={awaiting:"#d97706",unread:"#0891b2"};function eA(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}let eL=null,ez=null,eP=new Map;function eW(){return[...document.querySelectorAll('link[rel="icon"]')]}async function eO(e,t){let n=await (!ez&&(ez=new Promise(e=>{let t=new Image;t.onload=()=>e(t),t.onerror=()=>e(null),t.src="/icons/icon-192.png"})),ez);if(!n||eL!==t)return;let r=document.createElement("canvas");r.width=192,r.height=192;let i=r.getContext("2d");if(!i)return;i.clearRect(0,0,192,192),i.drawImage(n,0,0,192,192);let s=e.count>1,o=s?56:42,l=192-o-10,a=o+10;if(i.beginPath(),i.arc(l,a,o,0,2*Math.PI),i.fillStyle=eR[e.kind],i.fill(),i.lineWidth=10,i.strokeStyle="#ffffff",i.stroke(),s&&(i.fillStyle="#ffffff",i.font=`bold ${e.count>9?56:68}px system-ui, sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(e.count),l,a+4)),eL!==t)return;let d=r.toDataURL("image/png");for(let e of eW())e.href=d}function eF(e){return e.isComposing||229===e.keyCode}function eD(e,t,n){let r,i=e.activeElement;t?.focus({preventScroll:!0});let s=(r=e=>{"Escape"!==e.key||(e.stopPropagation(),eF(e)||(e.preventDefault(),n()))},e.addEventListener("keydown",r,!0),()=>e.removeEventListener("keydown",r,!0));return()=>{s(),i&&i.isConnected&&"function"==typeof i.focus&&i.focus({preventScroll:!0})}}function eB(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}let eH=Symbol.for("pi-web:page-id");function e_(){let e=globalThis,t=e[eH];if("string"==typeof t)return t;let n=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return e[eH]=n,n}let eU=new Set,eK=1;function eq(e){let t=e.source.deref();return t&&2!==t.readyState?t:void 0}function eV(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;for(let e of eU)eq(e)||eU.delete(e);let r={id:eK++,kind:e,label:n,source:new WeakRef(t),createdAt:Date.now(),opens:0,errors:0,lastOpenAt:null,lastErrorAt:null};return eU.add(r),"function"==typeof t.addEventListener&&(t.addEventListener("open",()=>{r.opens+=1,r.lastOpenAt=Date.now()}),t.addEventListener("error",()=>{r.errors+=1,r.lastErrorAt=Date.now()})),t}function eZ(){let e=[];for(let t of eU){let n=eq(t);if(!n){eU.delete(t);continue}e.push({id:t.id,kind:t.kind,label:t.label,state:1===n.readyState?"open":"connecting",createdAt:t.createdAt,opens:t.opens,errors:t.errors,lastOpenAt:t.lastOpenAt,lastErrorAt:t.lastErrorAt})}return e}let eJ={trackingSince:null,lastHiddenAt:null,lastVisibleAt:null,hiddenCount:0};function eG(){"u">typeof document&&("hidden"===document.visibilityState?(eJ.lastHiddenAt=Date.now(),eJ.hiddenCount+=1):eJ.lastVisibleAt=Date.now())}function eY(){return{state:"u">typeof document&&"hidden"===document.visibilityState?"hidden":"visible",trackingSince:eJ.trackingSince,lastHiddenAt:eJ.lastHiddenAt,lastVisibleAt:eJ.lastVisibleAt,hiddenCount:eJ.hiddenCount}}let eX={count:0,failures:0,last:null};function eQ(){return{...eX,last:eX.last?{...eX.last}:null}}function e0(){if("u"<typeof performance||"function"!=typeof performance.getEntriesByType)return null;let e=performance.getEntriesByType("navigation")[0],t=e?.nextHopProtocol;return t||("u">typeof location&&"http:"===location.protocol?"http/1.1":null)}let e1="pi-web:sidebar-files-placement",e2="below";function e4(){try{var e;return e=window.localStorage.getItem(e1),"tab"===e?"tab":e2}catch{return e2}}let e8=null,e3=new Set;function e5(){return null===e8&&(e8=e4()),e8}function e6(){e3.forEach(e=>e())}function e9(e){if(null!==e.key&&e.key!==e1)return;let t=e4();t!==e8&&(e8=t,e6())}function e7(e){return 0===e3.size&&(window.addEventListener("storage",e9),e8=e4()),e3.add(e),()=>{e3.delete(e),0===e3.size&&window.removeEventListener("storage",e9)}}function te(e){if(e!==e5()){e8=e;try{window.localStorage.setItem(e1,e)}catch{}e6()}}function tt(){return(0,i.useSyncExternalStore)(e7,e5,()=>e2)}var tn=n(21278);let tr="(max-width: 640px)",ti="(max-width: 480px)";function ts(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)}function to(e){return!!window.matchMedia&&window.matchMedia(e).matches}let tl=e=>ts(tr,e),ta=()=>to(tr),td=e=>ts(ti,e),tc=()=>to(ti);function tu(){return!1}function tp(){return(0,i.useSyncExternalStore)(tl,ta,tu)}function th(e,t,n){let r=Number.isFinite(e)?e:t,i=Math.max(t,n);return Math.round(Math.max(t,Math.min(i,r)))}function tm(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function tf(e){let{ariaLabel:t,axis:n="horizontal",cssVariable:r,defaultWidth:s,getDefaultWidth:o,getMaxWidth:l,growthDirection:a,maxWidth:d,minWidth:c,persistClamp:u=!0,storageKey:p,widthRef:h}=e,m=(0,i.useRef)(null),f=(0,i.useRef)(null),g=(0,i.useRef)(!1),x=(0,i.useRef)(s),[v,b]=(0,i.useState)(s),[y,j]=(0,i.useState)(!1),[k,w]=(0,i.useState)(!1);(0,i.useEffect)(()=>{w(!0)},[]);let S=(0,i.useCallback)(()=>Math.min(d,Math.max(c,l())),[l,d,c]),C=(0,i.useCallback)(e=>th(e,c,S()),[S,c]),N=(0,i.useCallback)(e=>{h.current=e,m.current?.style.setProperty(r,`${e}px`)},[r,h]),E=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{forcePersist:n=!1,persist:r=!0}=t,i=C(e),s=i!==h.current;return N(i),b(i),u?r&&(s||n)&&tm(p,i):n&&(x.current=th(e,c,d),tm(p,x.current)),i},[N,C,d,c,u,p,h]),I=(0,i.useCallback)(()=>{E(u||f.current?h.current:x.current)},[E,u,h]),$=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),T=(0,i.useCallback)(e=>{let t=f.current;if(t&&t.pointerId===e){f.current=null,$(t),j(!1),E(h.current,{forcePersist:u||h.current!==t.startWidth});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[E,u,$,h]),M=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=f.current;t&&T(t.pointerId);let r=e.currentTarget;r.focus({preventScroll:!0}),r.setPointerCapture(e.pointerId),f.current={pointerId:e.pointerId,startPosition:"vertical"===n?e.clientY:e.clientX,startWidth:h.current,target:r,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="vertical"===n?"row-resize":"col-resize",document.body.style.userSelect="none",j(!0)},[n,T,h]),R=(0,i.useCallback)(e=>{let t=f.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void T(e.pointerId);e.preventDefault();let r="right"===a||"down"===a?1:-1,i="vertical"===n?e.clientY:e.clientX,s=C(t.startWidth+(i-t.startPosition)*r);N(s),e.currentTarget.setAttribute("aria-valuenow",String(s)),e.currentTarget.setAttribute("aria-valuetext",`${s} px`)},[N,n,C,T,a]),A=(0,i.useCallback)(e=>{T(e.pointerId)},[T]),L=(0,i.useCallback)(e=>{T(e.pointerId)},[T]),z=(0,i.useCallback)(e=>{T(e.pointerId)},[T]),P=(0,i.useCallback)(()=>{E(o?.()??s,{forcePersist:!0})},[E,s,o]),W=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,r="right"===a||"down"===a,i="vertical"===n?"ArrowDown":"ArrowRight",s="vertical"===n?"ArrowUp":"ArrowLeft",o=u?h.current:Math.max(h.current,x.current);e.key===(r?i:s)?(e.preventDefault(),E(o+t,{forcePersist:!0})):e.key===(r?s:i)?(e.preventDefault(),E(h.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),E(c,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),E(Math.max(o,S()),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),P())},[n,E,S,a,c,u,P,h]);return(0,i.useEffect)(()=>{if(g.current)return;g.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(p),t=e??o?.()??s;if(!u){x.current=th(t,c,d),E(x.current,{persist:!1});return}let n=E(t,{persist:!1});null!==e&&e!==n&&tm(p,n)},[E,s,o,d,c,u,p]),(0,i.useEffect)(()=>{if(!g.current)return;I();let e=()=>{I()};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[I]),(0,i.useEffect)(()=>{if(!y)return;let e=()=>{let e=f.current;e&&T(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[T,y]),(0,i.useEffect)(()=>()=>{let e=f.current;e&&(f.current=null,$(e))},[$]),{isResizing:y,panelRef:m,reclampWidth:I,resetWidth:P,separatorProps:{"aria-label":t,"aria-orientation":"vertical"===n?"horizontal":"vertical","aria-valuemax":k?S():d,"aria-valuemin":c,"aria-valuenow":v,"aria-valuetext":`${v} px`,onDoubleClick:P,onKeyDown:W,onLostPointerCapture:z,onPointerCancel:L,onPointerDown:M,onPointerMove:R,onPointerUp:A,role:"separator",tabIndex:0},width:v}}function tg(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];(0,i.useEffect)(()=>{if(!t)return;let n=null,r=null,i=!1,s=null,o=()=>{null!==s&&(clearTimeout(s),s=null)},l=()=>{n&&(o(),n.classList.add("scrollbar-visible"))},a=()=>{n&&(o(),s=setTimeout(()=>{s=null,n?.classList.remove("scrollbar-visible")},500))},d=()=>{l(),a()},c=()=>{if(!i){if(!(n=e.current)){r=requestAnimationFrame(c);return}n.addEventListener("pointerenter",l),n.addEventListener("pointerleave",a),n.addEventListener("scroll",d)}};return c(),()=>{i=!0,null!==r&&cancelAnimationFrame(r),n?.removeEventListener("pointerenter",l),n?.removeEventListener("pointerleave",a),n?.removeEventListener("scroll",d),o(),n?.classList.remove("scrollbar-visible")}},[t,e])}let tx="/api/sessions/ui-state";async function tv(e){try{let t=await e.json();if(t&&"object"==typeof t&&"string"==typeof t.error)return t.error}catch{}return`HTTP ${e.status}`}function tb(e){return e instanceof Error?e.message:String(e)}async function ty(e){if(!e.ok)throw Error(await tv(e));let t=await e.json(),n=t&&"object"==typeof t?function(e){if(!y(e)||void 0!==e.version&&1!==e.version||void 0!==e.sessions&&!y(e.sessions)||void 0!==e.projects&&!y(e.projects))return null;let t=R(),n=e.revision;for(let[r,i]of("number"==typeof n&&Number.isSafeInteger(n)&&n>=0&&(t.revision=n),Object.entries(e.sessions??{}))){if(!("string"==typeof r&&v.test(r)))continue;let e=function(e){if(!y(e))return null;let t={};return j(e.pinnedAt)&&(t.pinnedAt=e.pinnedAt),j(e.archivedAt)&&(t.archivedAt=e.archivedAt),void 0===t.pinnedAt&&void 0===t.archivedAt?null:t}(i);e&&(t.sessions[r]=e)}for(let[n,r]of Object.entries(e.projects??{})){if(!k(n))continue;let e=y(r)&&j(r.pinnedAt)&&k(r.root)?{pinnedAt:r.pinnedAt,root:r.root}:null;e&&(t.projects[n]=e)}if(Array.isArray(e.projectOrder)){let n=new Set,r=$(e.projectOrder.filter(e=>!(!k(e)||n.has(e))&&(n.add(e),!0)));r.length>0&&(t.projectOrder=r)}if(y(e.projectNames)){let n={},r=0,i=1;for(let[t,s]of Object.entries(e.projectNames)){let e=S(s);if(!k(t)||"string"!=typeof e)continue;let o=T(t,e);M(r+1,i+o)&&(n[t]=e,r++,i+=o)}r>0&&(t.projectNames=n)}return t}(t.state):null;if(!n)throw Error("Invalid session UI state response");return n}function tj(){let[e,t]=(0,i.useState)(null),n=(0,i.useRef)(null),r=(0,i.useCallback)(()=>{null!==n.current&&(clearTimeout(n.current),n.current=null)},[]),s=(0,i.useCallback)(()=>{r(),t(null)},[r]),o=(0,i.useCallback)(e=>{(r(),function(){try{return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}catch{return!1}}())?t(null):(t(e),n.current=setTimeout(()=>{n.current=null,t(null)},300))},[r]);return(0,i.useEffect)(()=>r,[r]),{phase:e,start:o,end:s}}var tk=n(47650);let tw={overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},tS={height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12},tC={padding:"6px 16px",borderRadius:6,fontSize:13},tN={...tC,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},tE={...tC,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)"};async function tI(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}async function t$(e,t){let n=await fetch("/api/cwd/browse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,name:t})}),r=await n.json();if(!n.ok||r.error||!r.path)throw Error(r.error??`HTTP ${n.status}`);return r.path}function tT(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function tM(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function tR(e){let{onCancel:t,onSelect:n,initialPath:s,busy:o=!1,error:l}=e,{t:a}=(0,tn.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(s??""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(!0),[C,N]=(0,i.useState)(!1),[E,I]=(0,i.useState)(""),[$,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(!1),A=(0,i.useRef)(!1),L=(0,i.useRef)(!1),z=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await tI(e),n=t.path??e??"/";p(n),m(t.parentPath??null),g(n),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{c(document.body),z(s||void 0)},[s,z]);let P=()=>{M||(N(!1),I(""),T(null))},W=async()=>{let e=E.trim();if(u&&e&&!M){R(!0),T(null);try{let t=await t$(u,e);N(!1),I(""),await z(t)}catch(e){T(e instanceof Error?e.message:String(e))}finally{R(!1)}}},O=f.trim()!==u,F=!!u&&!O&&!o&&!w,D=!!h||/^[a-zA-Z]:[\\/]?$/.test(u);return d?(0,tk.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.selectDirectory"),onPointerDown:e=>{A.current=e.target===e.currentTarget},onClick:e=>{let n=A.current;A.current=!1,n&&e.target===e.currentTarget&&!o&&t()},onPointerCancel:()=>{A.current=!1},onKeyDown:e=>{"Escape"!==e.key||o||t()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{...tw,position:"relative",width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:a("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:t,disabled:o,title:a("i18n.close"),"aria-label":a("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:o?"default":"pointer",opacity:o?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&z(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void z(h??void 0),disabled:w||!D,title:a("directoryPicker.goToParent"),"aria-label":a("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:D?"pointer":"default",opacity:D?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:a("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:f,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{...tS,minWidth:0,flex:1}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:w||!f.trim(),title:a("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:w||!f.trim()?"default":"pointer",opacity:w||!f.trim()?.6:1},children:a("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[w?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void z(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(tM,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void z(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(tT,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noSubdirectories")}),(j||l)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:j??l})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>{N(!0),T(null)},disabled:!F,style:{...tE,marginRight:"auto",opacity:F?1:.6,cursor:F?"pointer":"default"},children:a("directoryPicker.newDirectory")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:t,disabled:o,style:{...tE,cursor:o?"default":"pointer"},children:a("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>n(u),disabled:!F,title:a(O?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{...tN,opacity:F?1:.6,cursor:F?"pointer":"default"},children:a(o?"i18n.checking":"directoryPicker.selectThisFolder")})]}),C&&(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:12,background:"rgba(0,0,0,0.35)"},onPointerDown:e=>{L.current=e.target===e.currentTarget},onClick:e=>{let t=L.current;L.current=!1,t&&e.target===e.currentTarget&&P()},onPointerCancel:()=>{L.current=!1},onKeyDown:e=>{e.stopPropagation(),"Escape"===e.key&&P()},children:(0,r.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.createDirectory"),onSubmit:e=>{e.preventDefault(),W()},style:{...tw,width:400,maxWidth:"100%"},children:[(0,r.jsx)("div",{style:{padding:"12px 18px",borderBottom:"1px solid var(--border)",color:"var(--text)",fontSize:15,fontWeight:700},children:a("directoryPicker.createDirectory")}),(0,r.jsxs)("div",{style:{padding:"12px 18px"},children:[(0,r.jsx)("label",{htmlFor:"new-directory-name",style:{display:"block",marginBottom:6,color:"var(--text-muted)",fontSize:11},children:a("directoryPicker.directoryName")}),(0,r.jsx)("input",{id:"new-directory-name",value:E,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:a("directoryPicker.directoryNamePlaceholder"),onChange:e=>{I(e.target.value),T(null)},disabled:M,className:"directory-picker-path",style:{...tS,width:"100%",boxSizing:"border-box"}}),$&&(0,r.jsx)("div",{style:{marginTop:7,color:"#dc2626",fontSize:11,lineHeight:1.35},children:$}),(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginTop:10},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:M||!E.trim(),style:{...tN,flex:1,opacity:M?.65:1,cursor:M||!E.trim()?"default":"pointer"},children:a(M?"directoryPicker.creating":"directoryPicker.create")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:P,disabled:M,style:{...tE,flex:1,cursor:M?"default":"pointer"},children:a("i18n.cancel")})]})]})]})})]})}),d):null}function tA(e){let{onClick:t,title:n}=e;return(0,r.jsx)("button",{type:"button",onClick:t,title:n,"aria-label":n,style:{width:24,height:24,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m6 6 12 12"}),(0,r.jsx)("path",{d:"m18 6-12 12"})]})})}let tL=["jsonl","html","md"];function tz(e){let{sessionId:t,leafId:n,onExported:s,onClose:o}=e,{t:l}=(0,tn.s)(),[a,d]=(0,i.useState)("jsonl"),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),m=(0,i.useRef)(null),f=(0,i.useRef)(c),g=(0,i.useRef)(o);(0,i.useEffect)(()=>{f.current=c,g.current=o},[c,o]),(0,i.useEffect)(()=>{if("u">typeof document)return eD(document,m.current,()=>{f.current||g.current()})},[]);let x=function(e){let r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=new URLSearchParams;return i.set("format",e),n&&i.set("leafId",n),r&&i.set("inline","1"),`/api/sessions/${encodeURIComponent(t)}/export?${i.toString()}`},v=e=>{let n=document.createElement("a");n.href=x(e,!1),n.download=`pi-session-${t}.${e}`,document.body.appendChild(n),n.click(),n.remove()},b=async()=>{if(!c){u(!0),h(null);try{let e=await fetch(`/api/sessions/${encodeURIComponent(t)}/export`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({format:a,...n?{leafId:n}:{},prompt:l("export.dialogTitle")})}),r=await e.json().catch(()=>({}));if(e.ok){r.savedPath&&(s?.(r.savedPath),o());return}if(409===e.status&&"busy"===r.error)return;if(403===e.status||405===e.status||503===e.status||"dialog"===r.stage||!r.stage){v(a),o();return}h(r.error||`HTTP ${e.status}`)}catch{v(a),o()}finally{u(!1)}}},y=(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{c||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{ref:m,role:"dialog","aria-modal":"true","aria-labelledby":"export-session-title","aria-describedby":"export-session-description",tabIndex:-1,className:"project-trust-dialog",children:[(0,r.jsx)("div",{className:"project-trust-body",children:(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"export-session-title",className:"project-trust-title",children:l("export.dialogTitle")}),(0,r.jsx)("div",{id:"export-session-description",className:"project-trust-text",children:l("export.dialogBody")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":l("export.dialogTitle"),style:{display:"flex",flexDirection:"column",gap:8,marginTop:12},children:tL.map(e=>{let t=a===e;return(0,r.jsxs)("label",{onClick:()=>{c||d(e)},style:{display:"flex",alignItems:"flex-start",gap:10,padding:"8px 10px",borderRadius:6,border:t?"1px solid var(--accent)":"1px solid var(--border)",background:t?"color-mix(in srgb, var(--accent) 8%, var(--bg))":"var(--bg)",cursor:c?"default":"pointer"},children:[(0,r.jsx)("input",{type:"radio",name:"export-session-format",checked:t,disabled:c,onChange:()=>{d(e)},style:{marginTop:2}}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:l(`export.format.${e}.title`)}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:l(`export.format.${e}.desc`)})]})]},e)})})]})}),p&&(0,r.jsxs)("div",{role:"alert",className:"project-trust-error",children:[l("export.failed"),(0,r.jsx)("code",{className:"project-trust-error-detail",children:p})]}),(0,r.jsxs)("div",{className:"project-trust-footer",children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:o,disabled:c,children:l("export.close")}),"html"===a&&(0,r.jsx)("a",{href:x("html",!0),target:"_blank",rel:"noopener noreferrer",className:"project-trust-button",style:{textDecoration:"none",display:"inline-flex",alignItems:"center"},children:l("export.previewHtml")}),(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:()=>void b(),disabled:c,"aria-busy":c||void 0,children:c?l("export.exporting"):l("export.confirm")})]})]})});return"u">typeof document&&document.body?(0,tk.createPortal)(y,document.body):y}let tP="/icons/catppuccin";function tW(e){let{name:t,size:n=14}=e,i={width:n,height:n,"--catppuccin-icon-light":`url(${tP}/latte/${t}.svg)`,"--catppuccin-icon-dark":`url(${tP}/mocha/${t}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:i})}function tO(e){let{size:t=14,open:n=!1}=e;return(0,r.jsx)(tW,{name:n?"_folder_open":"_folder",size:t})}function tF(e){let{size:t=14}=e;return(0,r.jsx)(tW,{name:"_file",size:t})}let tD={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function tB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:14,n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)(tW,{name:i,size:t});let s=tD[n.split(".").pop()??""];return s?(0,r.jsx)(tW,{name:s,size:t}):(0,r.jsx)(tF,{size:t})}var tH=n(28999);function t_(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function tU(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function tK(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function tq(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function tV(e,t,n,r){return new Promise((i,s)=>{let o=new FormData;t.forEach(e=>o.append("files",e,e.name));let l=new XMLHttpRequest;l.open("POST",`/api/files/${(0,tH.HG)(e)}?type=upload&conflict=${n}`),l.upload.onprogress=e=>{r&&e.lengthComputable&&e.total>0&&r(Math.round(e.loaded/e.total*100))},l.onerror=()=>s(Error("Network error while uploading files")),l.onabort=()=>s(Error("Upload cancelled")),l.onload=()=>{let e={};try{e=JSON.parse(l.responseText)}catch{l.responseText&&(e.error=l.responseText)}i({status:l.status,data:e})},l.send(o)})}function tZ(e){let t=[],n=new Map;for(let r of e){let e=r.split("/"),i=t,s="";for(let t=0;t<e.length;t++){s=s?`${s}/${e[t]}`:e[t];let r=n.get(s);r||(r={name:e[t],path:s,isDir:t<e.length-1,children:[]},n.set(s,r),i.push(r)),i=r.children}}let r=e=>{e.sort((e,t)=>e.isDir!==t.isDir?e.isDir?-1:1:e.name.localeCompare(t.name)),e.forEach(e=>r(e.children))};return r(t),t}function tJ(e){return Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)}function tG(e){let t=[];for(let n of Array.from(e.items)){if("file"!==n.kind)continue;let e=n.webkitGetAsEntry?.();if(e?.isDirectory){t.push({kind:"folder",name:e.name});continue}let r=n.getAsFile();r&&t.push({kind:"file",file:r})}return t.length>0?t:Array.from(e.files).map(e=>({kind:"file",file:e}))}let tY=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:20,t=new Map;return{save(n,r){if(t.delete(n),0!==r.size)for(let i of(t.set(n,new Set(r)),t.keys())){if(t.size<=e)break;t.delete(i)}},restore:e=>new Set(t.get(e))}}();async function tX(e,t){let n=`${t} (HTTP ${e.status})`;try{let t=await e.json();t.error&&(n=t.error)}catch{}return Error(n)}async function tQ(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=(0,tH.HG)(e),r=await fetch(`/api/files/${n}?type=list${t?"&hidden=1":""}`);if(!r.ok)throw await tX(r,"Failed to load files");return((await r.json()).entries??[]).map(t=>({name:t.name,fullPath:(0,tH.e_)(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir,outsideLinkTarget:t.outsideLinkTarget,outsideLinkEncloses:t.outsideLinkEncloses,hidden:t.hidden}))}async function t0(e,t){let n=await fetch(`/api/files/${(0,tH.HG)(e)}?type=allow-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t})});if(!n.ok)throw await tX(n,"Failed to allow the linked folder")}async function t1(e){let t=new URLSearchParams({cwd:e}),n=await fetch(`/api/git/status?${t.toString()}`);if(!n.ok)throw Error(`Failed to load Git status (HTTP ${n.status})`);return n.json()}let t2={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},t4={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function t8(e){let{status:t,t:n}=e;return(0,r.jsx)("span",{title:n(t2[t.status]),"aria-label":n(t2[t.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:t4[t.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:t.code})}function t3(e){let{size:t=11}=e;return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function t5(e){let{size:t=11}=e;return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M15 3h6v6"}),(0,r.jsx)("path",{d:"M10 14 21 3"}),(0,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]})}let t6={ignored:"files.hiddenIgnored",excluded:"files.hiddenExcluded"};function t9(e){let{node:t,depth:n,cwd:s,onOpenFile:o,onAtMention:l,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:m=!1,parentHidden:f,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b}=e,y=a.has(t.fullPath),j=t.hidden??f,k=t.isDir&&g===t.fullPath,w=u.has(t.fullPath),S=(0,tH.A0)(t.fullPath),C=p.get(S),N=t.isDir&&(void 0!==C||h.has(S)),[E,I]=(0,i.useState)(t.children??[]),[$,T]=(0,i.useState)(t.loaded??!1),[M,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(null),[z,P]=(0,i.useState)(!1),[W,O]=(0,i.useState)(null),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(null),_=t.outsideLinkTarget&&t.outsideLinkTarget!==W?t.outsideLinkTarget:null;(0,i.useEffect)(()=>{O(null),H(null)},[t.outsideLinkTarget]);let U=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!$||e){R(!0),L(null);try{let e=await tQ(t.fullPath,m);I(e),T(!0)}catch(e){L(e instanceof Error?e.message:String(e))}finally{R(!1)}}},[$,t.fullPath,m]),K=(0,i.useRef)(m);(0,i.useEffect)(()=>{K.current===m||(K.current=m,$&&(y&&!_?U(!0):T(!1)))},[m]),(0,i.useEffect)(()=>{t.isDir&&y&&!$&&!_&&U()},[]),(0,i.useEffect)(()=>{void 0!==c&&$&&!_&&(y?U(!0):T(!1))},[c]);let q=(0,i.useCallback)(()=>{if(t.isDir){let e=!y;d(t.fullPath,e),!e||$||_||U()}else o(t.fullPath,t.name)},[t.isDir,t.fullPath,t.name,$,y,_,U,o,d]),V=(0,i.useCallback)(async e=>{if((e.stopPropagation(),_)&&(!t.outsideLinkEncloses||window.confirm(b("files.allowEnclosingLinkConfirm",{target:_})))){D(!0),H(null);try{await t0(t.fullPath,_),O(_),await U(!0)}catch(e){H(e instanceof Error?e.message:String(e))}finally{D(!1)}}},[t.fullPath,t.outsideLinkEncloses,_,U,b]);return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:q,onMouseEnter:()=>P(!0),onMouseLeave:()=>P(!1),onDragOver:t.isDir?e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="copy",v?.(t.fullPath))}:void 0,onDrop:t.isDir?e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),v?.(null),x?.(t.fullPath,tG(e.dataTransfer)))}:void 0,style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:24,cursor:"pointer",background:k?"color-mix(in srgb, var(--accent) 16%, transparent)":z?"var(--bg-hover)":"transparent",outline:k?"1px dashed var(--accent)":"none",outlineOffset:-1,borderRadius:4,userSelect:"none"},children:[t.isDir&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:y?"rotate(90deg)":"none",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),!t.isDir&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:j?.55:1},children:t.isDir?(0,r.jsx)(tO,{size:14,open:y}):tB(t.name,14)}),(0,r.jsx)("span",{"data-hidden-reason":j,style:{fontSize:12,color:j?"var(--text-muted)":"var(--text)",opacity:j?.55:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:j?`${t.fullPath}
2
+ ${b(t6[j])}`:t.fullPath,children:t.name}),!z&&_&&(0,r.jsx)("span",{title:b("files.outsideLink",{target:_}),"aria-label":b("files.outsideLink",{target:_}),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)"},children:(0,r.jsx)(t5,{})}),w&&(0,r.jsx)("span",{title:b("files.newlyUploaded"),"aria-label":b("files.newlyUploaded"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#3b82f6"}})}),!z&&!t.isDir&&C&&(0,r.jsx)(t8,{status:C,t:b}),!z&&N&&(0,r.jsx)("span",{title:b("files.containsChangedFiles"),"aria-label":b("files.containsChangedFiles"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#d6a84b"}})}),M&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),l&&z&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),l((0,tH.qP)(t.fullPath,s),t.isDir)},title:b("files.insertPath"),style:{position:"absolute",right:t.isDir?4:28,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(t3,{}),b("files.mention")]}),z&&!t.isDir&&(0,r.jsx)("a",{href:`/api/files/${(0,tH.HG)(t.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:b("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap",textDecoration:"none"},children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),t.isDir&&y&&_&&(0,r.jsxs)("div",{style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:5,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{wordBreak:"break-all"},children:b("files.outsideLink",{target:_})}),t.outsideLinkEncloses&&(0,r.jsx)("span",{style:{color:"#f59e0b"},children:b("files.outsideLinkEncloses")}),(0,r.jsx)("button",{type:"button",onClick:V,disabled:F,title:b("files.allowOutsideLinkTitle",{target:_}),style:{height:20,padding:"0 8px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:F?"default":"pointer",opacity:F?.6:1,fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:b("files.allowOutsideLink")}),B&&(0,r.jsx)("span",{role:"alert",style:{color:"#f87171",wordBreak:"break-word"},children:B})]}),t.isDir&&y&&!_&&(0,r.jsxs)("div",{children:[E.map(e=>(0,r.jsx)(t9,{node:e,depth:n+1,cwd:s,onOpenFile:o,onAtMention:l,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:m,parentHidden:j,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b},e.fullPath)),0===E.length&&$&&!A&&(0,r.jsx)("div",{style:{paddingLeft:8+(n+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),A&&(0,r.jsx)("div",{role:"alert",style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:3,fontSize:11,color:"#f87171",wordBreak:"break-word"},children:A})]})]})}function t7(e){let{status:t,cwd:n,onOpenFile:s,onAtMention:o,t:l,depth:a=0,treeMode:d=!1}=e,[c,u]=(0,i.useState)(!1),p=(0,tH.WP)(t.filePath),h=(0,tH.qP)(t.filePath,n),m=h.lastIndexOf("/"),f=!d&&m>=0?h.slice(0,m+1):"",g=d?p:m>=0?h.slice(m+1):h;return(0,r.jsxs)("div",{onClick:()=>s(t.filePath,p,{modeHint:"diff"}),onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),title:t.filePath,style:{display:"flex",alignItems:"center",gap:d?4:6,paddingLeft:d?8+14*a:10,paddingRight:8,height:24,cursor:"pointer",background:c?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none",position:"relative"},children:[(0,r.jsx)(t8,{status:t,t:l}),d&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:.85},children:tB(p,13)}),(0,r.jsxs)("span",{title:t.filePath,style:{fontSize:12,color:"var(--text)",display:"flex",alignItems:"center",minWidth:0,flex:1},children:[f&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:"0 1 auto",minWidth:0,color:"var(--text-dim)"},children:f}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:+!!d,maxWidth:"100%"},children:g})]}),o&&c&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),o(h,!1)},title:l("files.insertPath"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(t3,{}),l("files.mention")]})]})}function ne(e){let{node:t,depth:n,open:s,onToggle:o}=e,[l,a]=(0,i.useState)(!1);return(0,r.jsxs)("div",{onClick:()=>o(t.path,!s),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),title:t.path,style:{display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:24,cursor:"pointer",background:l?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:s?"rotate(90deg)":"none",transition:"transform 0.1s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:(0,r.jsx)(tO,{size:14,open:s})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:t.name})]})}function nt(e){let{nodes:t,depth:n,cwd:i,statusByPath:s,collapsedPaths:o,onToggleExpanded:l,onOpenFile:a,onAtMention:d,t:c}=e;return(0,r.jsx)(r.Fragment,{children:t.map(e=>{if(e.isDir){let t=!o.has(e.path);return(0,r.jsxs)("div",{children:[(0,r.jsx)(ne,{node:e,depth:n,open:t,onToggle:l}),t&&(0,r.jsx)(nt,{nodes:e.children,depth:n+1,cwd:i,statusByPath:s,collapsedPaths:o,onToggleExpanded:l,onOpenFile:a,onAtMention:d,t:c})]},`dir:${e.path}`)}let t=s.get(e.path);return t?(0,r.jsx)(t7,{status:t,cwd:i,onOpenFile:a,onAtMention:d,t:c,depth:n,treeMode:!0},t.filePath):null})})}function nn(e){let{mode:t}=e;return"tree"===t?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8 6h13"}),(0,r.jsx)("path",{d:"M8 12h13"}),(0,r.jsx)("path",{d:"M8 18h13"}),(0,r.jsx)("path",{d:"M3 6h.01"}),(0,r.jsx)("path",{d:"M3 12h.01"}),(0,r.jsx)("path",{d:"M3 18h.01"})]}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M6 3v12"}),(0,r.jsx)("path",{d:"M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M6 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M18 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M9 12h6"}),(0,r.jsx)("path",{d:"M12 12v3"})]})}let nr=(0,i.forwardRef)(function(e,t){let{cwd:n,onOpenFile:s,refreshKey:o,onAtMention:l,onAtMentions:a,onUploadBusyChange:d,changesCollapsed:c,onChangesCountChange:u,fileSearchOpen:p=!1,onFileSearchOpenChange:h,showHidden:m=!1}=e,{t:f}=(0,tn.s)(),[g,x]=(0,i.useState)([]),[v,b]=(0,i.useState)(!0),[y,j]=(0,i.useState)(null),[k,w]=(0,i.useState)(new Set),[S,C]=(0,i.useState)(0),[N,E]=(0,i.useState)(new Set),[I,$]=(0,i.useState)([]),[T,M]=(0,i.useState)({additions:0,deletions:0}),[R,A]=(0,i.useState)("list"),[L,z]=(0,i.useState)(()=>new Set),[P,W]=(0,i.useState)("idle"),[O,F]=(0,i.useState)(0),[D,B]=(0,i.useState)(null),[H,_]=(0,i.useState)(null),[U,K]=(0,i.useState)(null),[q,V]=(0,i.useState)(""),[Z,J]=(0,i.useState)([]),[G,Y]=(0,i.useState)(!1),[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(new Set),en=(0,i.useRef)(null),[er,ei]=(0,i.useState)(!1),[es,eo]=(0,i.useState)(null),el=(0,i.useRef)(0),ea=(0,i.useRef)(null),ed=(0,i.useRef)(k),ec=(0,i.useRef)(null),eu=`${o??0}:${S}`,ep="idle"!==P,eh=q.trim().length>0;(0,i.useEffect)(()=>{if(!p)return;let e=q.trim();if(!e){J([]),Y(!1),Q(!1);return}let t=new AbortController;Y(!0),Q(!1);let r=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(n)}&q=${encodeURIComponent(e)}`,{signal:t.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>J((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{t.signal.aborted||(J([]),Q(!0))}).finally(()=>{t.signal.aborted||Y(!1)})},150);return()=>{clearTimeout(r),t.abort()}},[n,p,q]),(0,i.useEffect)(()=>{p&&en.current?.focus()},[p]),(0,i.useEffect)(()=>{if(0===Z.length)return;let e=new Set;for(let t of Z){let r=t.split("/"),i="";for(let t=0;t<r.length-1;t++)i=i?`${i}/${r[t]}`:r[t],e.add((0,tH.e_)(n,i))}et(t=>{let n=!1,r=new Set(t);for(let t of e)r.has(t)||(r.add(t),n=!0);return n?r:t})},[n,Z]);let ef=(0,i.useMemo)(()=>{let e=t=>({name:t.name,fullPath:(0,tH.e_)(n,t.path),isDir:t.isDir,size:0,children:t.children.map(e),loaded:!0});return tZ(Z).map(e)},[n,Z]),eg=(0,i.useMemo)(()=>new Map(I.map(e=>[(0,tH.A0)(e.filePath),e])),[I]),ev=(0,i.useMemo)(()=>{let e=new Set,t=(0,tH.A0)(n).replace(/\/$/,"");for(let n of I){let r=(0,tH.gX)((0,tH.A0)(n.filePath));for(;(r===t||r.startsWith(`${t}/`))&&(e.add(r),r!==t);){let e=(0,tH.gX)(r);if(e===r)break;r=e}}return e},[n,I]),eb=(0,i.useMemo)(()=>new Map(I.map(e=>[(0,tH.A0)((0,tH.qP)(e.filePath,n)).replace(/^\/+/,""),e])),[n,I]),ey=(0,i.useMemo)(()=>tZ([...eb.keys()]),[eb]),ej=(0,i.useCallback)((e,t)=>{w(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),ek=(0,i.useCallback)((e,t)=>{let n=e.uploaded??[];_({directory:t,uploaded:n,skipped:e.skipped??[],errors:e.errors??[]}),n.length>0&&(E(new Set(n.map(e=>(0,tH.e_)(t,e)))),C(e=>e+1))},[]),ew=(0,i.useCallback)(async(e,t,n)=>{K(null),B(null),F(0),W("uploading");try{let{status:r,data:i}=await tV(n,e,t,F);if(409===r&&i.conflicts?.length)return void K({directory:n,files:e,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);F(100),ek(i,n)}catch(e){B(e instanceof Error?e.message:String(e))}finally{W("idle")}},[ek]),eS=(0,i.useCallback)(async(e,t)=>{if(0!==e.length&&!ep){_(null),E(new Set),K(null),B(null),F(0),W("checking");try{let n=await fetch(`/api/files/${(0,tH.HG)(t)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:e.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`Upload check failed (HTTP ${n.status})`);if(r.conflicts?.length)return void K({directory:t,files:e,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await ew(e,"error",t)}catch(e){B(e instanceof Error?e.message:String(e))}finally{W("idle")}}},[ew,ep]),eC=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eS(t,n)},[n,eS]);(0,i.useImperativeHandle)(t,()=>({openUploadPicker(){ep||ec.current?.click()}}),[ep]);let eN=(0,i.useCallback)(()=>{el.current=0,ei(!1),eo(null)},[]),eE=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),el.current+=1,ei(!0))},[]),eI=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy",eo(e=>null===e?e:null))},[]),e$=(0,i.useCallback)(()=>{el.current<=0||(el.current-=1,0===el.current&&(el.current=0,ei(!1),eo(null)))},[]),eT=(0,i.useCallback)((e,t)=>{eN();let n=t.flatMap(e=>"file"===e.kind?[e.file]:[]),r=t.flatMap(e=>"folder"===e.kind?[e.name]:[]);eS(n,e).then(()=>{if(0===r.length)return;let e=f("chat.dropFoldersUnsupported",{names:r.join(", ")});B(t=>t&&n.length>0?t:e)})},[eS,eN,f]),eM=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),eT(es??n,tG(e.dataTransfer)))},[n,es,eT]),eR=(0,i.useCallback)(e=>{eo(t=>t===e?t:e)},[]);(0,i.useEffect)(()=>{d?.(ep)},[d,ep]),(0,i.useEffect)(()=>()=>d?.(!1),[d]),(0,i.useEffect)(()=>{ed.current=k},[k]),(0,i.useEffect)(()=>()=>{null!==ea.current&&tY.save(ea.current,ed.current)},[]),(0,i.useEffect)(()=>{let e=ea.current,t=e!==n;if(ea.current=n,t){null!==e&&tY.save(e,ed.current);let t=tY.restore(n);ed.current=t,w(t),E(new Set),_(null),K(null),B(null)}b(t),j(null);let r=!1;return tQ(n,m).then(e=>{r||x(e)}).catch(e=>{r||j(e instanceof Error?e.message:String(e))}).finally(()=>{r||b(!1)}),()=>{r=!0}},[n,o,S,m]),(0,i.useEffect)(()=>{let e=()=>C(e=>e+1);return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[]),(0,i.useEffect)(()=>{let e=!1;return t1(n).then(t=>{e||($(t.isGitRepository?t.files:[]),M(t.isGitRepository?{additions:t.additions,deletions:t.deletions}:{additions:0,deletions:0}))}).catch(()=>{e||($([]),M({additions:0,deletions:0}))}),()=>{e=!0}},[n,o,S]),(0,i.useEffect)(()=>{u?.(I.length)},[I,u]),(0,i.useEffect)(()=>{A(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ex();if(!e)return"list";try{return"tree"===e.getItem(em)?"tree":"list"}catch{return"list"}}())},[]);let eA=(0,i.useCallback)((e,t)=>{z(n=>{let r=new Set(n);return t?r.delete(e):r.add(e),r})},[]),eL=(0,i.useCallback)(()=>{A(e=>{let t="list"===e?"tree":"list";return!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ex();if(t)try{t.setItem(em,e)}catch{}}(t),t})},[]),ez=ep||null!==U||null!==D||null!==H,eP=(0,i.useCallback)(()=>{H&&0!==H.uploaded.length&&a?.(H.uploaded.map(e=>(0,tH.qP)((0,tH.e_)(H.directory,e),n)))},[n,a,H]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},onDragEnter:eE,onDragOver:eI,onDragLeave:e$,onDrop:eM,children:[(0,r.jsx)("input",{ref:ec,type:"file",multiple:!0,hidden:!0,onChange:eC}),ez&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ep&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===P?f("files.checking"):f("files.uploading",{progress:O}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===P?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===P&&(0,r.jsxs)("span",{style:{fontSize:10},children:[O,"%"]})]}),"uploading"===P&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${O}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),U&&(0,r.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, #f59e0b 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, #f59e0b 9%, var(--bg-panel))"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:f("files.conflictSummary",{count:U.conflicts.length,countSuffix:1===U.conflicts.length?"":"s",files:U.conflicts.join(", ")})}),U.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:f("files.cannotReplace",{files:U.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void ew(U.files,"overwrite",U.directory),style:{height:22,padding:"0 7px",border:"1px solid #ef4444",borderRadius:4,background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:10},children:f("files.replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void ew(U.files,"skip",U.directory),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:10},children:f("files.skipExisting")}),(0,r.jsx)("button",{type:"button",onClick:()=>K(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:f("files.cancel")})]})]}),D&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"#f87171"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:D}),(0,r.jsx)(tA,{onClick:()=>B(null),title:f("files.dismissError")})]}),H&&(0,r.jsxs)("div",{"aria-live":"polite",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[H.uploaded.length>0&&(0,r.jsxs)("span",{title:f("files.uploadedCount",{count:H.uploaded.length}),"aria-label":f("files.uploadedCount",{count:H.uploaded.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:H.uploaded.length})]}),H.skipped.length>0&&(0,r.jsxs)("span",{title:f("files.skippedCount",{count:H.skipped.length}),"aria-label":f("files.skippedCount",{count:H.skipped.length}),style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:H.skipped.length})]}),H.errors.length>0&&(0,r.jsxs)("span",{title:f("files.failedCount",{count:H.errors.length}),"aria-label":f("files.failedCount",{count:H.errors.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:H.errors.length})]})]}),H.uploaded.length>0&&a&&(0,r.jsxs)("button",{type:"button",onClick:eP,title:1===H.uploaded.length?f("files.addUploadedFile"):f("files.addAllUploadedFiles"),"aria-label":1===H.uploaded.length?f("files.addUploadedFile"):f("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(t3,{}),f("files.mention")]}),(0,r.jsx)(tA,{onClick:()=>_(null),title:f("files.dismissUploadResults")})]}),H.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:10,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 8v5"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),p&&(0,r.jsxs)("div",{style:{padding:"2px 8px 6px"},children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{ref:en,id:"file-search-input",value:q,onChange:e=>V(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),h?.(!1))},placeholder:f("sidebar.searchFilesPlaceholder"),"aria-label":f("sidebar.searchFiles"),style:{width:"100%",boxSizing:"border-box",padding:"6px 24px",border:"1px solid var(--border)",borderRadius:8,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}}),q&&(0,r.jsx)("button",{type:"button",onClick:()=>V(""),title:f("sidebar.clearSearch"),"aria-label":f("sidebar.clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,padding:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),eh&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[G&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:f("sidebar.searchingFiles")}),!G&&X&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:f("i18n.networkError")}),!G&&!X&&0===Z.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:f("sidebar.noMatchingFiles")}),!G&&!X&&Z.length>0&&(0,r.jsx)("div",{children:ef.map(e=>(0,r.jsx)(t9,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:l,expandedPaths:ee,onToggleExpanded:(e,t)=>{et(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:N,gitStatusByPath:eg,changedDirectoryPaths:ev,dropTargetPath:es,onDropFiles:eT,onDropTargetChange:eR,t:f},`${q}:${e.fullPath}`))})]})]}),!c&&I.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":f("files.changeStats",{count:I.length,additions:T.additions,deletions:T.deletions}),style:{display:"flex",alignItems:"center",gap:6,height:24,padding:"0 6px 0 10px",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:f("files.changedCount",{count:I.length})}),(0,r.jsxs)("span",{style:{color:t4.added,fontFamily:"var(--font-mono)"},children:["+",T.additions]}),(0,r.jsxs)("span",{style:{color:t4.deleted,fontFamily:"var(--font-mono)"},children:["-",T.deletions]}),(0,r.jsx)("span",{style:{flex:1}}),(0,r.jsx)("button",{type:"button",onClick:eL,title:"list"===R?f("files.viewAsTree"):f("files.viewAsList"),"aria-label":"list"===R?f("files.viewAsTree"):f("files.viewAsList"),"aria-pressed":"tree"===R,style:{display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,border:"none",borderRadius:4,background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsx)(nn,{mode:R})})]}),"tree"===R?(0,r.jsx)(nt,{nodes:ey,depth:0,cwd:n,statusByPath:eb,collapsedPaths:L,onToggleExpanded:eA,onOpenFile:s,onAtMention:l,t:f}):I.map(e=>(0,r.jsx)(t7,{status:e,cwd:n,onOpenFile:s,onAtMention:l,t:f},e.filePath))]}),(c||0===I.length)&&(!p||!eh)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[v?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:f("files.loading")}):y?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:y}):g.map(e=>(0,r.jsx)(t9,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:l,expandedPaths:k,onToggleExpanded:ej,refreshToken:eu,highlightedPaths:N,gitStatusByPath:eg,changedDirectoryPaths:ev,showHidden:m,dropTargetPath:es,onDropFiles:eT,onDropTargetChange:eR,t:f},e.fullPath)),!v&&!y&&0===g.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:f("files.noFiles")})]}),er&&(0,r.jsxs)("div",{role:"status","aria-live":"polite",style:{position:"sticky",bottom:0,zIndex:1,display:"flex",alignItems:"center",gap:6,padding:"6px 8px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)",fontSize:11,color:"var(--accent)",userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),f("files.dropToUpload",{directory:es?(0,tH.qP)(es,n)||es:(0,tH.WP)(n)||n})]})]})});async function ni(e){try{let t=await fetch("/api/sessions/import/pick",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:e})}),n=await t.json().catch(()=>({}));if(t.ok)return n.path?{path:n.path}:"cancelled";return"busy"===n.error?"busy":"unavailable"}catch{return"unavailable"}}function ns(e){let{initialPath:t,cwd:n,onClose:s,onImported:o}=e,{t:l}=(0,tn.s)(),[a,d]=(0,i.useState)(t??""),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(!1);(0,i.useEffect)(()=>{d(t??""),u(null),f(null)},[t]);let v=async e=>{let t=e.target.files?.[0];if(t){f(null);try{let e=await t.text();u({name:t.name,content:e})}catch(e){f(e instanceof Error?e.message:String(e))}}},b=async()=>{if(f(null),!x.current){let e=await ni(l("import.chooseFile"));if("busy"===e||"cancelled"===e)return;if("unavailable"!==e){d(e.path),u(null);return}x.current=!0}g.current?.click()},y=async()=>{if(p)return;let e=a.trim();if(c||e){h(!0),f(null);try{let t=c?{content:c.content,fileName:c.name,...n?{cwd:n}:{}}:{path:e,...n?{cwd:n}:{}},r=await fetch("/api/sessions/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok||!i.sessionId)return void f(i.error||`HTTP ${r.status}`);o(i.sessionId)}catch(e){f(e instanceof Error?e.message:String(e))}finally{h(!1)}}};return(0,r.jsx)(no,{pathValue:a,selectedFileName:c?.name??null,busy:p,error:m,fileInputRef:g,onFileInputChange:e=>void v(e),onPathChange:e=>{d(e),e.trim()&&u(null)},onChooseFile:()=>void b(),onCancel:s,onConfirm:()=>void y()})}function no(e){let{pathValue:t,selectedFileName:n,busy:s,error:o,fileInputRef:l,onFileInputChange:a,onPathChange:d,onChooseFile:c,onCancel:u,onConfirm:p}=e,{t:h}=(0,tn.s)(),m=(0,i.useRef)(null),f=(0,i.useRef)(s),g=(0,i.useRef)(u);(0,i.useEffect)(()=>{f.current=s,g.current=u},[s,u]),(0,i.useEffect)(()=>{if("u">typeof document)return eD(document,m.current,()=>{f.current||g.current()})},[]);let x=!s&&(!!n||t.trim().length>0),v=(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{s||e.target!==e.currentTarget||u()},children:(0,r.jsxs)("div",{ref:m,role:"dialog","aria-modal":"true","aria-labelledby":"import-session-title","aria-describedby":"import-session-description",tabIndex:-1,className:"project-trust-dialog",children:[(0,r.jsx)("input",{ref:l,type:"file",accept:".jsonl,.json,text/plain",style:{display:"none"},onChange:a}),(0,r.jsx)("div",{className:"project-trust-body",children:(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"import-session-title",className:"project-trust-title",children:h("import.dialogTitle")}),(0,r.jsx)("div",{id:"import-session-description",className:"project-trust-text",children:h("import.dialogBody")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10,marginTop:12},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:c,disabled:s,children:h("import.chooseFile")}),n&&(0,r.jsx)("code",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text)",padding:"4px 8px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg)"},children:n})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:"import-session-path-input",style:{display:"block",fontSize:11,color:"var(--text-muted)",marginBottom:4},children:h("import.serverPathLabel")}),(0,r.jsx)("input",{id:"import-session-path-input",type:"text",value:t,disabled:s,placeholder:h("import.serverPathPlaceholder"),onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&!e.nativeEvent.isComposing&&x&&(e.preventDefault(),p())},style:{width:"100%",boxSizing:"border-box",padding:"7px 10px",borderRadius:5,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}})]})]})]})}),o&&(0,r.jsxs)("div",{role:"alert",className:"project-trust-error",children:[h("import.importFailed"),(0,r.jsx)("code",{className:"project-trust-error-detail",children:o})]}),(0,r.jsxs)("div",{className:"project-trust-footer",children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:u,disabled:s,children:h("import.cancel")}),(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:p,disabled:!x,"aria-busy":s||void 0,children:h(s?"import.importing":"import.confirm")})]})]})});return"u">typeof document&&document.body?(0,tk.createPortal)(v,document.body):v}let nl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function na(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Math.random,r=4*e.length;if(t>=r)return e;let i=Math.floor(t/r*e.length),s="";for(let t=0;t<e.length;t++){let r=e[t];s+=" "===r||t<i?r:nl[Math.floor(n()*nl.length)]}return s}function nd(e){let{onWidthChange:t}=e,{t:n}=(0,tn.s)(),[s,o]=(0,i.useState)(!1),l=(0,i.useRef)(null),a="1.6.1",d="1.4.0",c=function(e){let[t,n]=(0,i.useState)(e),r=(0,i.useRef)(e);return(0,i.useEffect)(()=>{if(r.current===e)return;if(r.current=e,window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return void n(e);let t=4*e.length,i=0,s=0,o=()=>{n(na(e,i+=1)),i<t&&(s=requestAnimationFrame(o))};return n(na(e,0)),s=requestAnimationFrame(o),()=>cancelAnimationFrame(s)},[e]),t}(s?`${a??"0.0.0"}p${d??"0.0.0"}`:"Pi Web");return(0,i.useLayoutEffect)(()=>{t?.()},[c.length,t]),(0,i.useEffect)(()=>()=>{l.current&&clearTimeout(l.current)},[]),(0,r.jsx)("button",{type:"button",className:`sidebar-brand${s?" is-version":""}`,"aria-label":n("sidebar.brandLabel",{app:a??"0.0.0",pi:d??"0.0.0"}),onClick:()=>{(l.current&&clearTimeout(l.current),l.current=null,s)?o(!1):(o(!0),l.current=setTimeout(()=>{l.current=null,o(!1)},3e3))},children:c})}var nc=n(2730);let nu=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function np(e){let t=e.match(nu);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}let nh={desktop:32,mobile:48};function nm(e,t,n,r){return Math.hypot(n-e,r-t)}function nf(e){return e.getClientRects().length>0}function ng(e){let{size:t=13,className:n,label:i,strokeWidth:s=2,children:o}=e;return(0,r.jsx)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",className:n,...i?{role:"img","aria-label":i}:{"aria-hidden":!0},children:o})}function nx(e){return(0,r.jsx)(ng,{...e,children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})}function nv(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"})]})}function nb(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"5",rx:"1"}),(0,r.jsx)("path",{d:"M5 9v9a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9"}),(0,r.jsx)("path",{d:"M10 13h4"})]})}function ny(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function nj(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M9 10.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.8a2 2 0 0 0-1.1-1.8l-1.8-.9a2 2 0 0 1-1.1-1.8V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"})]})}function nk(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M15 9.3V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8.5"}),(0,r.jsx)("path",{d:"m2 2 20 20"}),(0,r.jsx)("path",{d:"M9 9v1.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h11"})]})}function nw(e){let{strokeWidth:t,...n}=e;return(0,r.jsx)(ng,{...n,strokeWidth:t,children:(0,r.jsx)("path",{d:"m9 6 6 6-6 6"})})}function nS(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function nC(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("circle",{cx:"6",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"18",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"2.5"}),(0,r.jsx)("path",{d:"M6 7.5v1.5a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V7.5"}),(0,r.jsx)("path",{d:"M12 12v4.5"})]})}function nN(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("circle",{cx:"18",cy:"5",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"12",r:"3"}),(0,r.jsx)("circle",{cx:"18",cy:"19",r:"3"}),(0,r.jsx)("path",{d:"m8.6 13.5 6.8 4M15.4 6.5l-6.8 4"})]})}function nE(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})}function nI(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("path",{d:"M14 4h6v6"}),(0,r.jsx)("path",{d:"M20 4 11 13"}),(0,r.jsx)("path",{d:"M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4"})]})}function n$(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}function nT(e){return(0,r.jsx)(ng,{...e,children:(0,r.jsx)("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})})}function nM(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("path",{d:"m15 4 5 5L7 22l-5-5Z"}),(0,r.jsx)("path",{d:"m14 5 5 5"}),(0,r.jsx)("path",{d:"M6 4V2M5 3H3M19 19v3M17.5 20.5h3"})]})}function nR(e){return(0,r.jsx)(ng,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5",fill:"currentColor",stroke:"none"})})}function nA(e){return(0,r.jsx)(ng,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5"})})}function nL(e){return(0,r.jsx)(ng,{...e,children:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"})})}function nz(e){return(0,r.jsx)(ng,{...e,children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})}function nP(e){return(0,r.jsx)(ng,{...e,children:(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})})}function nW(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"}),(0,r.jsx)("path",{d:"M12 11v5M9.5 13.5h5"})]})}function nO(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function nF(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})}function nD(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,r.jsx)("path",{d:"M12 3v12"})]})}function nB(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function nH(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M3 12h6M15 12h6"})]})}function n_(e){return(0,r.jsxs)(ng,{...e,children:[(0,r.jsx)("path",{d:"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function nU(e){return(0,r.jsx)(ng,{...e,children:(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function nK(e){let{className:t,...n}=e;return(0,r.jsx)(ng,{...n,strokeWidth:2.8,className:t?`sidebar-spin ${t}`:"sidebar-spin",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4"})})}function nq(e){let t=np(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function nV(e){return e.nativeEvent.isComposing||229===e.keyCode}function nZ(e){let{rows:t,layout:n,emptyLabel:s,loading:o,error:l,renamingRootId:a,renamingProjectKey:d,confirmDeleteRootId:c,activeMenuRowKey:u,reveal:p}=e,{t:h}=(0,tn.s)(),m=(0,i.useRef)(e);m.current=e;let f=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null);tg(g);let[b,y]=(0,i.useState)(0),[j,k]=(0,i.useState)(0),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(()=>Date.now()),E=(0,i.useRef)(null),I=(0,i.useCallback)(()=>{null===E.current&&(E.current=requestAnimationFrame(()=>{E.current=null;let e=g.current;e&&y(e.scrollTop)}))},[]);(0,i.useLayoutEffect)(()=>{let e=g.current;if(!e)return;let t=()=>{let t=`${Math.max(0,e.offsetWidth-e.clientWidth)}px`;e.style.setProperty("--session-tree-scrollbar",t),e.offsetWidth>0&&e.closest(".session-sidebar")?.style.setProperty("--session-tree-scrollbar",t)};if(t(),k(e.clientHeight),y(e.scrollTop),"u"<typeof ResizeObserver)return;let n=new ResizeObserver(()=>{t(),k(e.clientHeight),y(e.scrollTop)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>()=>{null!==E.current&&cancelAnimationFrame(E.current)},[]),(0,i.useEffect)(()=>{let e=window.setInterval(()=>N(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let $=(0,i.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;S(t?.getAttribute("data-row-key")??null)},[]),T=(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||S(null)},[]),M=(0,i.useMemo)(()=>(function(e,t){let n=W[t],r=Array(e.length+1);r[0]=0;for(let t=0;t<e.length;t++)r[t+1]=r[t]+n[e[t].kind];return r})(t,n),[t,n]),R=!!e.onMoveGroup,A=(0,i.useMemo)(()=>{let e={pinned:0,other:0};for(let n of t)"group"===n.kind&&e[n.project.pinned?"pinned":"other"]++;return e},[t]),L=function(e){let{rows:t,offsets:n,enabled:r}=e,s=(0,i.useRef)(e);s.current=e;let o=(0,i.useMemo)(()=>(function(e,t){let n=[],r=0;for(;r<e.length;){var i;let s=e[r];if("group"!==s.kind){r++;continue}let o=r;for(;o>0&&"spacer"===e[o-1].kind;)o--;let l=r+1;for(;l<e.length&&("group-more"===(i=e[l]).kind||"group-empty"===i.kind||"session"===i.kind&&"group"===i.context);)l++;let a=l;for(;a<e.length&&"spacer"===e[a].kind;)a++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[l],gapAbove:t[r]-t[o],gapBelow:t[a]-t[l]}),r=l}return n})(t,n),[t,n]),l=(0,i.useRef)(o);l.current=o;let a=(0,i.useRef)(null),d=(0,i.useRef)(0),[c,u]=(0,i.useState)(null),p=(0,i.useMemo)(()=>{let e=e=>{u("armed"===e.phase||"dragging"===e.phase?{projectKey:e.projectKey,phase:e.phase,drop:e.drop}:null)},t=e=>{let t=s.current.innerRef.current;return t?function(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),o=i.filter(e=>e!==r);if(0===o.length)return null;let l=o.filter(e=>(e.top+e.bottom)/2<n).length;if(l===s)return null;let a=o[o.length-1],d=Math.max(3,l<o.length?o[l].top-o[l].gapAbove/2:a.bottom+a.gapBelow/2);return l>0?{anchorKey:o[l-1].key,position:"after",lineY:d}:{anchorKey:o[0].key,position:"before",lineY:d}}(l.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=a.current,t=s.current.ghostRef.current,n=s.current.treeRef.current,r=s.current.innerRef.current,i=s.current.scrollRef.current;if(!e?.ghost||!t||!n||!i)return;let o=n.getBoundingClientRect().top,l=i.getBoundingClientRect(),d=t.offsetHeight,c=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:o,maxTop:l}=e,a=Math.max(o,l),d=t-i-r,c=null!==n&&n>=o&&n<=a+r?n:null,u=e=>e>=o&&e<=a,p=e=>null!==c&&e>c-s-r&&e<c+s,h=null===c?[d,o,t+i,a]:[d,c-s-r,o,t+i,c+s,a],m=e=>{let t=null;for(let n of h)e(n)&&(null===t||Math.abs(n-d)<Math.abs(t-d))&&(t=n);return t};return m(e=>u(e)&&!(e>d&&e<t+i)&&!p(e))??m(e=>u(e)&&!p(e))??Math.min(a,Math.max(o,d))}({pointerY:e.clientY,lineY:e.drop&&r?r.getBoundingClientRect().top+e.drop.lineY:null,ghostHeight:d,pointerGap:"mouse"===e.pointerType?8:28,lineGap:8,minTop:l.top,maxTop:l.bottom-d});t.style.top=`${c-o}px`,t.style.left=`${e.ghost.left}px`},r=e=>{null!==e.timer&&window.clearTimeout(e.timer),null!==e.frame&&cancelAnimationFrame(e.frame),e.timer=null,e.frame=null,s.current.scrollRef.current?.removeEventListener("scroll",p);try{e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId)}catch{}},i=()=>{let e=a.current;e&&(a.current=null,r(e),window.removeEventListener("pointermove",g,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",v,!0),window.removeEventListener("pointerdown",b,!0),window.removeEventListener("keydown",y,!0),window.removeEventListener("contextmenu",j,!0),window.removeEventListener("blur",k),document.removeEventListener("visibilitychange",w),u(null))},o=()=>{let e=a.current;if(e){if("armed"!==e.phase&&"dragging"!==e.phase){"pending"===e.phase&&i();return}e.phase="cancelled",e.drop=null,r(e),u(null)}},c=function(){var r;let i=arguments.length>0&&void 0!==arguments[0]&&arguments[0],l=a.current;if(!l||"dragging"!==l.phase)return;let d=s.current.scrollRef.current;if(!d||!nf(d))return void o();let c=t(l),u=i||c!==(r=l.drop)&&(null===c||null===r||c.anchorKey!==r.anchorKey||c.position!==r.position||c.lineY!==r.lineY);l.drop=c,n(),u&&e(l)};function p(){c()}let h=()=>{let e=a.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=s.current.scrollRef.current;if(!t||!nf(t))return void o();let n=t.getBoundingClientRect(),r=function(e,t,n,r){let i=Math.min(r,(n-t)/2);if(!(i>0)||!Number.isFinite(e))return 0;let s=e=>Math.ceil(14*Math.min(1,e/i));return e<t+i?-s(t+i-e):e>n-i?s(e-(n-i)):0}(e.clientY,n.top,n.bottom,nh[s.current.layout]);if(0!==r){let n=Math.min(Math.max(0,(s.current.offsets[s.current.offsets.length-1]??0)-t.clientHeight),Math.max(0,t.scrollTop+r));n!==t.scrollTop&&(t.scrollTop=n,e.expectedScrollTop=t.scrollTop,c())}a.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},m=e=>{let t=s.current.scrollRef.current,n=s.current.treeRef.current;if(!t||!n||!nf(t)||!e.element.isConnected)return void o();if(e.phase="dragging","touch"!==e.pointerType)try{e.element.setPointerCapture(e.pointerId)}catch{}e.ghost={left:e.element.getBoundingClientRect().left-n.getBoundingClientRect().left+4},e.expectedScrollTop=t.scrollTop,t.addEventListener("scroll",p,{passive:!0}),e.frame=requestAnimationFrame(h),c(!0)},f=()=>{let t=a.current;t&&"pending"===t.phase&&(t.timer=null,t.phase="armed",t.armX=t.clientX,t.armY=t.clientY,t.expectedScrollTop=s.current.scrollRef.current?.scrollTop??0,e(t))};function g(e){let t=a.current;if(!t||e.pointerId!==t.pointerId)return;if("mouse"===t.pointerType&&0===e.buttons)return void i();t.clientX=e.clientX,t.clientY=e.clientY;let n=nm(t.startX,t.startY,e.clientX,e.clientY);switch(t.phase){case"pending":"mouse"===t.pointerType?n>=4&&m(t):n>8&&i();break;case"armed":nm(t.armX,t.armY,e.clientX,e.clientY)>=4&&m(t);break;case"dragging":c()}}function x(e){let n=a.current;if(n&&e.pointerId===n.pointerId){if("dragging"===n.phase){n.clientX=e.clientX,n.clientY=e.clientY;let r=t(n);r&&s.current.onMove(n.projectKey,r.anchorKey,r.position)}"pending"!==n.phase&&(d.current=e.timeStamp+600),i()}}function v(e){a.current&&e.pointerId===a.current.pointerId&&i()}function b(e){a.current&&e.pointerId!==a.current.pointerId&&o()}function y(e){let t=a.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),o())}function j(e){let t=a.current;if(t){if("pending"===t.phase)return void i();e.preventDefault(),e.stopPropagation()}}function k(){i()}function w(){"hidden"===document.visibilityState&&i()}return{handlers:{onPointerDown(e,t){if(!s.current.enabled||a.current||!e.isPrimary||0!==e.button||e.ctrlKey||e.target instanceof Element&&e.target.closest(".session-tree-group-actions"))return;let n=e.currentTarget,r={pointerId:e.pointerId,pointerType:e.pointerType,projectKey:t,element:n,startX:e.clientX,startY:e.clientY,armX:e.clientX,armY:e.clientY,clientX:e.clientX,clientY:e.clientY,phase:"pending",timer:null,frame:null,expectedScrollTop:0,drop:null,ghost:null};a.current=r,window.addEventListener("pointermove",g,!0),window.addEventListener("pointerup",x,!0),window.addEventListener("pointercancel",v,!0),window.addEventListener("pointerdown",b,!0),window.addEventListener("keydown",y,!0),window.addEventListener("contextmenu",j,!0),window.addEventListener("blur",k),document.addEventListener("visibilitychange",w),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(f,350))},onTouchMove(e){let t=a.current;if(!t||"armed"!==t.phase&&"dragging"!==t.phase)return;if(e.cancelable)return void e.preventDefault();let n=s.current.scrollRef.current;n&&n.scrollTop!==t.expectedScrollTop&&i()}},cancel:o,teardown:i,updateDrag:c,placeGhost:n}},[]);(0,i.useLayoutEffect)(()=>{let e=a.current;e&&("armed"===e.phase||"dragging"===e.phase)&&(t.some(t=>"group"===t.kind&&t.project.key===e.projectKey)?p.updateDrag():p.cancel())},[t,n,p]),(0,i.useEffect)(()=>{r||p.cancel()},[r,p]);let h=c?.phase==="dragging";(0,i.useLayoutEffect)(()=>{h&&p.placeGhost()},[h,p]),(0,i.useEffect)(()=>()=>p.teardown(),[p]);let m=(0,i.useCallback)(e=>{let t=d.current;0===t||(d.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),f=(0,i.useCallback)(()=>{d.current=0},[]);return{view:(0,i.useMemo)(()=>{if(!c)return null;let e="dragging"===c.phase?o.find(e=>e.key===c.projectKey)??null:null;return{...c,source:e}},[c,o]),handlers:p.handlers,onClickCapture:m,onPointerDownCapture:f}}({rows:t,offsets:M,layout:n,enabled:R&&!o,scrollRef:g,innerRef:x,treeRef:f,ghostRef:v,onMove:(e,t,n)=>m.current.onMoveGroup?.(e,t,n)}),z=L.view,P=z?`group:${z.projectKey}`:null,[F,D]=(0,i.useState)(null),B=p&&p.id!==F?p:null,H=B?.rowKey??null,_=(0,i.useMemo)(()=>{let e=[];return t.forEach((t,n)=>{t.key===w||t.key===u||t.key===H||t.key===P||"session"===t.kind&&(t.family.root.id===a||t.family.root.id===c)?e.push(n):"group"===t.kind&&t.project.key===d&&e.push(n)}),e},[t,w,u,H,P,a,d,c]),U=(0,i.useMemo)(()=>o?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),o=Number.isFinite(t)?Math.max(0,t):0,l=Number.isFinite(n)&&n>0?n:600,a=Number.isFinite(r)&&r>0?r:0,d=o-a,c=o+l+a,u=0,p=s;for(;u<p;){let t=u+p>>>1;e[t+1]>d?p=t:u=t+1}let h=u;for(u=h,p=s;u<p;){let t=u+p>>>1;e[t]>=c?p=t:u=t+1}let m=u,f=[];for(let e=h;e<m;e++)f.push(e);if(0===i.length)return f;let g=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=m));return 0===g.length?f:[...new Set([...f,...g])].sort((e,t)=>e-t)}(M,b,j,240,_),[o,M,b,j,_]),K=(0,i.useRef)(null),q=(0,i.useRef)(null),V=(0,i.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");K.current={rowKey:e,fallbackKey:t===O?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?m.current.onShowMore(t):m.current.onShowLess(t)},[]);(0,i.useLayoutEffect)(()=>{let e=K.current;if(!e)return;K.current=null;let n=g.current,r=t.findIndex(t=>t.key===e.rowKey);if(r<0&&(r=t.findIndex(t=>t.key===e.fallbackKey)),e.scroll&&n&&r>=0){let e=eo(M,r,n.scrollTop,n.clientHeight);null!==e&&(n.scrollTop=e),y(n.scrollTop)}e.focus&&(q.current={rowKey:e.rowKey,fallbackKey:e.fallbackKey,tries:0})},[t,M]);let Z=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{if(!B)return;let e=t.findIndex(e=>e.key===B.rowKey),n=function(e,t,n,r){let i=e?.id===t.id?e:{id:t.id,misses:0};if(!(r-t.at<=3e3))return{misses:i,action:"drop"};if(n)return{misses:i,action:"reveal"};let s={id:t.id,misses:i.misses+1};return{misses:s,action:s.misses>=3?"drop":"wait"}}(Z.current,B,e>=0,Date.now());if(Z.current=n.misses,"wait"!==n.action){if("reveal"===n.action){let t=g.current;if(t&&t.getClientRects().length>0){let n=eo(M,e,t.scrollTop,t.clientHeight,B.block);null!==n&&(t.scrollTop=n),y(t.scrollTop)}B.takeFocusFrom&&(q.current={rowKey:B.rowKey,fallbackKey:B.rowKey,tries:0,takeFocusFrom:B.takeFocusFrom})}D(B.id),m.current.onRevealHandled?.(B.id)}},[B,t,M]),(0,i.useLayoutEffect)(()=>{let e=q.current;if(!e)return;let t=document.activeElement;if(t&&t!==document.body&&document.contains(t)&&!e.takeFocusFrom?.(t)){q.current=null;return}let n=g.current,r=e=>n?.querySelector(`[data-row-key="${CSS.escape(e)}"]`)??null,i=r(e.rowKey),s=i?.querySelector('[data-more-action="more"]')??i?.querySelector("a[href], button")??r(e.fallbackKey)?.querySelector("a[href], button");s?(s.focus({preventScroll:!0}),q.current=null):++e.tries>2&&(q.current=null)},[U]);let J=t.some(e=>"session"===e.kind||"group"===e.kind),G=!o&&!l&&null!==s&&!J,Y=z?.source??null,X=z?.drop?.lineY??null,Q=z?.phase==="dragging"?t.find(e=>"group"===e.kind&&e.project.key===z.projectKey)?.project??null:null;return(0,r.jsxs)("div",{ref:f,className:`session-tree${"mobile"===n?" is-mobile":""}${Q?" is-group-dragging":""}`,children:[o&&(0,r.jsx)("div",{className:"session-tree-message",children:h("sidebar.loading")}),l&&(0,r.jsx)("div",{className:"session-tree-message is-error",children:l}),G&&(0,r.jsx)("div",{className:"session-tree-message",children:s}),(0,r.jsx)("div",{ref:g,className:"session-tree-scroll scrollbar-subtle",onScroll:I,onFocus:$,onBlur:T,onPointerDownCapture:L.onPointerDownCapture,onClickCapture:L.onClickCapture,children:!o&&(0,r.jsxs)("div",{ref:x,className:"session-tree-inner",style:{height:M[t.length]},children:[U.map(e=>{let i=t[e];if("spacer"===i.kind)return null;let s=M[e],o=M[e+1]-s,l=i.key===u;if("session"===i.kind)return(0,r.jsx)(nG,{row:i,layout:n,top:s,height:o,now:C,renaming:i.family.root.id===a,confirming:i.family.root.id===c,menuOpen:l,handlers:m},i.key);if("archive-group"===i.kind)return(0,r.jsx)(n2,{row:i,top:s,height:o,menuOpen:l,handlers:m},i.key);if("group"===i.kind){let e=i.project.key===d;return(0,r.jsx)(n0,{row:i,top:s,height:o,menuOpen:l,renaming:e,canDrag:R&&!e&&A[i.project.pinned?"pinned":"other"]>1,dragPhase:z?.projectKey===i.project.key?z.phase:null,drag:L.handlers,handlers:m},i.key)}return(0,r.jsx)(n1,{row:i,top:s,height:o,handlers:m,onMoreAction:V},i.key)}),Y&&(0,r.jsx)("div",{className:"session-tree-drag-source","aria-hidden":"true",style:{top:Y.top,height:Y.bottom-Y.top}}),null!==X&&(0,r.jsx)("div",{className:"session-tree-drop-line","aria-hidden":"true",style:{top:X}})]})}),Q&&(0,r.jsx)("div",{ref:v,className:"session-tree-drag-ghost","aria-hidden":"true",children:(0,r.jsx)("span",{className:"session-tree-group-name",children:Q.name})})]})}function nJ(e,t){return{top:e,height:t}}let nG=(0,i.memo)(function(e){let t,n,{row:i,layout:s,top:o,height:l,now:a,renaming:d,confirming:c,menuOpen:p,handlers:h}=e,{locale:m,t:f}=(0,tn.s)(),{family:g,context:x,status:v}=i,b=g.root,y=nq(b),j=new Date(a),k=["session-tree-row session-tree-session",v.selected?"is-selected":"",v.running?"is-running":"","archive"===x?"is-archived":"",p?"is-menu-open":"",c?"is-confirming":"",d?"is-renaming":""].filter(Boolean).join(" ");if(c){let e=y.slice(0,22)+(y.length>22?"…":"");return(0,r.jsx)("div",{className:k,style:nJ(o,l),"data-row-key":i.key,onKeyDown:e=>{"Escape"!==e.key||nV(e)||(e.preventDefault(),e.stopPropagation(),h.current.onDeleteCancel())},children:(0,r.jsx)(nX,{label:f("sidebar.deleteSession",{title:e}),deleteLabel:f("sidebar.delete"),cancelLabel:f("sidebar.cancel"),onConfirm:e=>{e.stopPropagation(),h.current.onDeleteConfirm(g,e)},onCancel:e=>{e.stopPropagation(),h.current.onDeleteCancel()}})})}if(d)return(0,r.jsx)("div",{className:k,style:nJ(o,l),"data-row-key":i.key,children:(0,r.jsx)(nY,{initialValue:y,label:f("sidebar.rename"),onCommit:e=>h.current.onRenameCommit(g,e),onCancel:()=>h.current.onRenameCancel()})});let w=b.isWorktree&&b.branch?b.branch:null,S=b.name&&b.relation?.kind==="fork"?eE(b.name):null,C=b.detailsPending?"…":f("sidebar.messagesCount",{count:b.messageCount}),N=`${y}
3
+ ${C} \xb7 ${(0,nc.fw)(b.modified,m,j)}${w?` \xb7 ⑂ ${w}`:""}`,E="";v.awaiting?(t=(0,r.jsx)("span",{className:"session-tree-awaiting",role:"img","aria-label":f("sidebar.agentAwaitingInput")}),E=" is-awaiting",n=f("sidebar.agentAwaitingInput")):v.running?(t=(0,r.jsx)(nK,{size:12,label:f("sidebar.agentRunning")}),E=" is-running",n=f("sidebar.agentRunning")):v.unread?(t=(0,r.jsx)("span",{className:"session-tree-unread",role:"img","aria-label":f("sidebar.newSessionActivity")}),E=" is-unread",n=f("sidebar.newActivity")):t="pinned"===x?(0,r.jsx)("span",{className:"session-tree-project",children:i.project.name}):(0,nc.Rg)(g.latestModified,m,j);let I="desktop"===s&&("archive"===x||!v.running),$=(0,r.jsxs)(r.Fragment,{children:[S?(0,r.jsxs)("span",{className:"session-tree-title has-fork-suffix",children:[(0,r.jsx)("span",{className:"session-tree-title-base",children:S.base}),(0,r.jsx)("span",{className:"session-tree-title-suffix",children:S.suffix})]}):(0,r.jsx)("span",{className:"session-tree-title",children:y}),w&&(0,r.jsxs)("span",{className:"session-tree-branch",children:[(0,r.jsx)(nS,{size:10,className:"session-tree-branch-icon"}),w]}),(0,r.jsx)("span",{className:`session-tree-meta${E}`,title:n,children:t})]});return(0,r.jsxs)("div",{className:k,style:nJ(o,l),"data-row-key":i.key,onClick:()=>h.current.onSelectFamily(g),onContextMenu:e=>h.current.onRowContextMenu(i,e),children:[v.transient?(0,r.jsx)("button",{type:"button",className:"session-tree-main",title:N,"aria-current":v.selected?"true":void 0,children:$}):(0,r.jsx)("a",{className:"session-tree-main",href:u(b.id),title:N,"aria-current":v.selected?"true":void 0,onClick:e=>{e.stopPropagation(),e.defaultPrevented||0!==e.button||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||(e.preventDefault(),h.current.onSelectFamily(g))},children:$}),!v.transient&&(0,r.jsxs)("span",{className:"session-tree-actions",children:[I&&("archive"===x?(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":f("sidebar.restore"),title:f("sidebar.restore"),onClick:e=>{e.stopPropagation(),h.current.onRestoreFamily(g)},children:(0,r.jsx)(ny,{size:13})}):(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":f("sidebar.archive"),title:f("sidebar.archive"),onClick:e=>{e.stopPropagation(),h.current.onArchiveFamily(g)},children:(0,r.jsx)(nb,{size:13})})),(0,r.jsx)("button",{type:"button",className:`session-tree-action session-tree-more-action${p?" is-active":""}`,"aria-label":f("sidebar.moreActions"),title:f("sidebar.moreActions"),"aria-haspopup":"menu","aria-expanded":p,onClick:e=>{let t;e.stopPropagation();let n=e.currentTarget;h.current.onOpenRowMenu(i,{kind:"rect",rect:{left:(t=n.getBoundingClientRect()).left,top:t.top,right:t.right,bottom:t.bottom},align:"end"},n)},children:(0,r.jsx)(nv,{size:14})})]})]})});function nY(e){let{initialValue:t,label:n,maxLength:s,onCommit:o,onCancel:l}=e,[a,d]=(0,i.useState)(t),c=(0,i.useRef)(null),u=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=c.current;e&&(e.focus(),e.select())},[]);let p=e=>{u.current||(u.current=!0,o(e))};return(0,r.jsx)("input",{ref:c,className:"session-tree-rename",value:a,"aria-label":n,maxLength:s,onChange:e=>d(e.target.value),onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{if(!nV(e)){if("Enter"===e.key)e.preventDefault(),p(e.currentTarget.value);else if("Escape"===e.key){if(e.preventDefault(),e.stopPropagation(),u.current)return;u.current=!0,l()}}}})}function nX(e){let{label:t,deleteLabel:n,cancelLabel:s,onConfirm:o,onCancel:l}=e,a=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||a.current?.focus()},[]),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"session-tree-confirm-text",children:t}),(0,r.jsxs)("button",{type:"button",className:"session-tree-confirm-delete",onClick:o,children:[(0,r.jsx)(n$,{size:12}),n]}),(0,r.jsx)("button",{ref:a,type:"button",className:"session-tree-confirm-cancel",onClick:l,children:s})]})}function nQ(e){let{running:t,awaiting:n=0,unread:i,t:s}=e;return 0===t&&0===n&&0===i?null:(0,r.jsxs)("span",{className:"session-tree-summary",children:[t>0&&(0,r.jsxs)("span",{className:"session-tree-summary-running",role:"img",title:s("sidebar.agentRunning"),"aria-label":`${s("sidebar.agentRunning")} (${t})`,children:[(0,r.jsx)(nK,{size:10}),t]}),n>0&&(0,r.jsxs)("span",{className:"session-tree-summary-awaiting",role:"img",title:s("sidebar.agentAwaitingInput"),"aria-label":`${s("sidebar.agentAwaitingInput")} (${n})`,children:[(0,r.jsx)("span",{className:"session-tree-summary-dot is-awaiting"}),n]}),i>0&&(0,r.jsxs)("span",{className:"session-tree-summary-unread",role:"img",title:s("sidebar.newSessionActivity"),"aria-label":`${s("sidebar.newSessionActivity")} (${i})`,children:[(0,r.jsx)("span",{className:"session-tree-summary-dot"}),i]})]})}let n0=(0,i.memo)(function(e){let{row:t,top:n,height:s,menuOpen:o,renaming:l,canDrag:a,dragPhase:d,drag:c,handlers:u}=e,{t:p}=(0,tn.s)(),{project:h,expanded:m}=t,f=(0,i.useRef)(null),g=["session-tree-row session-tree-group",h.current?"is-current":"",o?"is-active":"","armed"===d?"is-drag-armed":""].filter(Boolean).join(" ");return((0,i.useEffect)(()=>{let e=f.current;if(!a||!e)return;let t=e=>c.onTouchMove(e);return e.addEventListener("touchmove",t,{passive:!1}),()=>e.removeEventListener("touchmove",t)},[a,c]),l)?(0,r.jsx)("div",{ref:f,className:`${g} is-renaming`,style:nJ(n,s),"data-row-key":t.key,children:(0,r.jsx)(nY,{initialValue:h.name,label:p("sidebar.projectName"),maxLength:80,onCommit:e=>u.current.onRenameProjectCommit(h,e),onCancel:()=>u.current.onRenameProjectCancel()})}):(0,r.jsxs)("div",{ref:f,className:g,style:nJ(n,s),"data-row-key":t.key,onPointerDown:a?e=>c.onPointerDown(e,h.key):void 0,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":m,title:h.root,onClick:e=>u.current.onToggleGroup(h.key,e.altKey),children:[(0,r.jsx)(nw,{size:12,strokeWidth:3,className:`session-tree-chevron${m?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:h.name}),h.pinned&&(0,r.jsx)(nj,{size:10,className:"session-tree-group-pin",label:p("sidebar.pinnedProject")}),!m&&(0,r.jsx)(nQ,{running:t.running,awaiting:t.awaiting,unread:t.unread,t:p})]}),(0,r.jsxs)("span",{className:"session-tree-group-actions",children:[(0,r.jsx)("button",{type:"button",className:"session-tree-group-action","aria-label":p("sidebar.newSessionInProject",{name:h.name}),title:p("sidebar.newSessionInProject",{name:h.name}),onClick:e=>{e.stopPropagation(),u.current.onGroupNew(h)},children:(0,r.jsx)(nx,{size:13})}),(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${o?" is-active":""}`,"aria-label":p("sidebar.projectActions",{name:h.name}),title:p("sidebar.projectActions",{name:h.name}),"aria-haspopup":"menu","aria-expanded":o,onClick:e=>{e.stopPropagation(),u.current.onGroupMenu(h,e.currentTarget)},children:(0,r.jsx)(nv,{size:13})})]})]})}),n1=(0,i.memo)(function(e){let{row:t,top:n,height:i,handlers:s,onMoreAction:o}=e,{t:l}=(0,tn.s)(),a=nJ(n,i);switch(t.kind){case"pinned-header":return(0,r.jsx)("div",{className:"session-tree-row session-tree-pinned-header",style:a,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-pinned-toggle","aria-expanded":!t.collapsed,onClick:()=>s.current.onTogglePinned(),children:[(0,r.jsx)(nw,{size:12,strokeWidth:3,className:`session-tree-chevron${t.collapsed?"":" is-open"}`}),(0,r.jsx)("span",{className:"session-tree-pinned-label",children:l("sidebar.pinned")}),(0,r.jsxs)("span",{className:"session-tree-pinned-count",children:["\xb7 ",t.count]}),t.collapsed&&t.running>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-running",role:"img",title:l("sidebar.agentRunning"),"aria-label":`${l("sidebar.agentRunning")} (${t.running})`}),t.collapsed&&t.awaiting>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-awaiting",role:"img",title:l("sidebar.agentAwaitingInput"),"aria-label":`${l("sidebar.agentAwaitingInput")} (${t.awaiting})`}),t.collapsed&&t.unread>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-unread",role:"img",title:l("sidebar.newSessionActivity"),"aria-label":`${l("sidebar.newSessionActivity")} (${t.unread})`})]})});case"pinned-more":case"group-more":{let e="pinned-more"===t.kind?O:t.projectKey;return(0,r.jsxs)("div",{className:"session-tree-row session-tree-more",style:a,"data-row-key":t.key,children:[t.hidden>0&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"more",onClick:n=>o(t.key,e,"more",n.currentTarget),children:l("sidebar.showMore",{count:t.hidden})}),t.canShowLess&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"less",onClick:n=>o(t.key,e,"less",n.currentTarget),children:l("sidebar.showLess")})]})}case"group-empty":return(0,r.jsxs)("div",{className:"session-tree-row session-tree-group-empty",style:a,"data-row-key":t.key,children:[(0,r.jsx)("span",{className:"session-tree-group-empty-label",children:l("sidebar.noLiveSessions")}),!t.project.pinned&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle",onClick:()=>s.current.onPinEmptyGroup(t.project),children:l("sidebar.pinToKeep")})]});case"footer-open":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:a,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:e=>s.current.onOpenOtherProject(e.currentTarget),children:[(0,r.jsx)(nW,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:l("sidebar.openOtherProject")})]})});case"footer-archived":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:a,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:()=>s.current.onOpenArchive(),children:[(0,r.jsx)(nb,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:l("sidebar.archivedCount",{count:t.count})}),(0,r.jsx)(nw,{size:10,className:"session-tree-footer-chevron"})]})})}}),n2=(0,i.memo)(function(e){let{row:t,top:n,height:i,menuOpen:s,handlers:o}=e,{t:l}=(0,tn.s)(),{project:a,expanded:d}=t,c=["session-tree-row session-tree-group session-tree-archive-group",a.current?"is-current":"",s?"is-active":""].filter(Boolean).join(" ");return(0,r.jsxs)("div",{className:c,style:nJ(n,i),"data-row-key":t.key,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":d,title:a.root,onClick:e=>o.current.onToggleArchiveGroup?.(a.key,e.altKey),children:[(0,r.jsx)(nw,{size:12,strokeWidth:3,className:`session-tree-chevron${d?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:a.name}),(0,r.jsxs)("span",{className:"session-tree-archive-group-count",children:["\xb7 ",t.count]})]}),(0,r.jsx)("span",{className:"session-tree-group-actions",children:(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${s?" is-active":""}`,"aria-label":l("sidebar.archivedProjectActions",{name:a.name}),title:l("sidebar.archivedProjectActions",{name:a.name}),"aria-haspopup":"menu","aria-expanded":s,onClick:e=>{e.stopPropagation(),o.current.onArchiveGroupMenu?.(a,e.currentTarget)},children:(0,r.jsx)(nv,{size:13})})})]})}),n4="[data-sidebar-menu-filter]",n8="[data-sidebar-menu-autofocus]",n3="button, input, textarea, select, a[href], [tabindex]";function n5(e){return i.Children.toArray(e).length>0}function n6(e){return"item"===e.type&&void 0!==e.checked}function n9(e){return e.getClientRects().length>0}function n7(e){return!e.disabled&&"true"!==e.getAttribute("aria-disabled")&&n9(e)}function re(e){return Array.from(e.querySelectorAll("[data-sidebar-menu-item]")).filter(n7)}function rt(e){let t=Array.from(e.querySelectorAll(n8)).find(n7);if(t)return t;let n=re(e);return n.length>0?n[0]:Array.from(e.querySelectorAll(n3)).filter(e=>e.tabIndex>=0&&n7(e))[0]??null}function rn(e){e.stopPropagation()}let rr={onClick:rn,onDoubleClick:rn,onMouseDown:rn,onMouseUp:rn,onPointerDown:rn,onPointerUp:rn,onKeyDown:rn,onKeyUp:rn,onFocus:rn,onBlur:rn,onContextMenu:function(e){e.preventDefault(),e.stopPropagation()}};function ri(e,t){return n=>{"Enter"!==n.key||n.nativeEvent.isComposing||229===n.keyCode||(n.preventDefault(),t(e,n.shiftKey))}}function rs(e){let{item:t,onActivate:n}=e,i=void 0!==t.checked,s=["sidebar-menu-item",i?"is-choice":"",t.danger?"is-danger":"",t.checked?"is-checked":""].filter(Boolean).join(" "),o=["sidebar-menu-label",t.mono?"is-mono":"",t.path?"is-path":""].filter(Boolean).join(" "),l=null;t.disabled&&t.disabledReason?l=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.disabledReason}):t.note?l=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.note}):t.shortcut&&(l=(0,r.jsx)("kbd",{className:"sidebar-menu-shortcut",children:t.shortcut}));let a=(0,r.jsxs)("button",{type:"button",role:i?"menuitemradio":"menuitem","aria-checked":i?t.checked:void 0,"aria-disabled":!!t.disabled||void 0,"aria-keyshortcuts":t.shortcut&&!t.disabled?t.shortcut.toUpperCase():void 0,tabIndex:-1,title:t.title,"data-sidebar-menu-item":"",className:s,onClick:e=>n(t,e.shiftKey),onKeyDown:ri(t,n),children:[(0,r.jsx)("span",{className:"sidebar-menu-icon",children:i?t.checked?(0,r.jsx)(nL,{size:13}):null:t.icon}),(0,r.jsx)("span",{className:o,children:t.path?(0,r.jsx)("span",{children:t.label}):t.label}),t.badge,l]}),d=t.secondary;return d?(0,r.jsxs)("div",{className:i?"sidebar-menu-row is-choice":"sidebar-menu-row",role:"none",children:[a,(0,r.jsx)("button",{type:"button",role:"menuitem","aria-label":d.label,"aria-disabled":!!d.disabled||void 0,tabIndex:-1,title:d.label,"data-sidebar-menu-item":"",className:d.danger?"sidebar-menu-secondary is-danger":"sidebar-menu-secondary",onClick:e=>n(d,e.shiftKey),onKeyDown:ri(d,n),children:d.icon})]}):a}function ro(e){var t;let n,{sheet:i,ariaLabel:s,title:o,items:l,filter:a,filterQuery:d="",onFilterQueryChange:c,children:u,cancelLabel:p,focusCancel:h=!1,width:m=208,classic:f=!1,footer:g,surfaceRef:x,onActivate:v,onClose:b}=e,y=n5(u),j=!y&&n5(g),k=void 0!==a&&!y&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return(e??[]).filter(n6).length>=t}(l,a.minChoices),w=k?(t=l??[],(n=d.trim().toLowerCase())?t.filter(e=>"item"!==e.type||void 0===e.checked||[e.label,e.note,e.title].some(e=>e?.toLowerCase().includes(n))):[...t]):l??[],S=w.map(e=>"separator"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-separator",role:"separator"},e.id):"header"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-header",role:"presentation",children:e.label},e.id):"custom"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-custom",role:"none",children:e.content},e.id):(0,r.jsx)(rs,{item:e,onActivate:v},e.id)),C=y?u:k||j?(0,r.jsxs)(r.Fragment,{children:[k&&(0,r.jsx)("div",{className:"sidebar-menu-filter",children:(0,r.jsx)("input",{className:"sidebar-menu-filter-input",value:d,placeholder:a.placeholder,"aria-label":a.placeholder,autoComplete:"off",spellCheck:!1,"data-sidebar-menu-filter":"","data-sidebar-menu-autofocus":i?void 0:"",onChange:e=>c?.(e.target.value)})}),k&&(0,r.jsx)("div",{role:"status",children:d.trim()&&!w.some(n6)&&(0,r.jsx)("div",{className:"sidebar-menu-empty",children:a.emptyLabel})}),(0,r.jsx)("div",{role:"menu","aria-label":s,children:S}),j&&g]}):S,N=y||k||j?void 0:"menu";return i?(0,r.jsxs)("div",{className:"sidebar-sheet-layer",...rr,children:[(0,r.jsx)("div",{className:"sidebar-sheet-backdrop","aria-hidden":"true",onClick:()=>b("outside")}),(0,r.jsxs)("div",{ref:x,className:"sidebar-sheet",role:"dialog","aria-modal":"true","aria-label":s,children:[o?(0,r.jsx)("div",{className:"sidebar-sheet-title",children:o}):null,(0,r.jsx)("div",{className:"sidebar-sheet-body",role:N,"aria-label":N?s:void 0,children:C}),(0,r.jsx)("button",{type:"button",className:"sidebar-sheet-cancel","data-sidebar-menu-autofocus":h?"":void 0,onClick:()=>b("cancel"),children:p})]})]}):(0,r.jsx)("div",{ref:x,className:f?"sidebar-menu is-classic":"sidebar-menu",role:N??"dialog","aria-label":s,style:{width:m},...rr,children:C})}function rl(e){let{open:t,anchor:n,sheet:s,ariaLabel:o,title:l,items:a,filter:d,children:c,cancelLabel:u,focusCancel:p,onClose:h,returnFocusTo:m,width:f,classic:g=!1,footer:x,focusKey:v=""}=e,[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(""),w=(0,i.useRef)(j);w.current=j;let S=(0,i.useRef)(null),C=(0,i.useRef)(h);C.current=h;let N=(0,i.useRef)(a);N.current=a;let E=(0,i.useRef)(m??null);E.current=m??null;let I=(0,i.useRef)(n);I.current=n,(0,i.useEffect)(()=>{y(document.body)},[]);let $=t&&null!==b&&(s||null!==n),T=n5(c),M=n?JSON.stringify(n):"",R=(e,t)=>{if(e.disabled)return;let n=!1;e.onSelect({shiftKey:t,keepOpen:()=>{n=!0}}),n||C.current("select")},A=(0,i.useRef)(R);A.current=R,(0,i.useLayoutEffect)(()=>{let e=S.current;if(!$||s||!e)return;let t=window.visualViewport,n=()=>{let n=I.current;if(!n)return;let r=e.getBoundingClientRect(),{left:i,top:s}=function(e,t,n){let r,i,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8,o=n.left+s,l=n.top+s,a=n.left+n.width-s,d=n.top+n.height-s;if("point"===e.kind)r=e.x+t.width>a&&e.x-t.width>=o?e.x-t.width:e.x,i=e.y+t.height>d&&e.y-t.height>=l?e.y-t.height:e.y;else{let{rect:n}=e;r="end"===e.align?n.right-t.width:n.left;let s=n.bottom+4,o=n.top-4-t.height;i=s+t.height>d&&o>=l?o:s}return{left:Math.max(o,Math.min(r,a-t.width)),top:Math.max(l,Math.min(i,d-t.height))}}(n,{width:r.width,height:r.height},{left:t?.offsetLeft??0,top:t?.offsetTop??0,width:t?.width??window.innerWidth,height:t?.height??window.innerHeight});e.style.left=`${i}px`,e.style.top=`${s}px`};n();let r="u"<typeof ResizeObserver?null:new ResizeObserver(n);return r?.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r?.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[$,s,M,T]),(0,i.useEffect)(()=>{k("")},[$,T]);let L=(0,i.useRef)(!1);return((0,i.useLayoutEffect)(()=>{let e=S.current;if(!$||!e){L.current=!1;return}let t=!L.current;L.current=!0,(t?rt(e):Array.from(e.querySelectorAll(n8)).filter(e=>!e.matches(n4)&&n7(e))[0]??rt(e))?.focus({preventScroll:!0})},[$,s,T,v]),(0,i.useLayoutEffect)(()=>{let e=S.current;if(!$||!e)return;let t=E.current;return()=>{let n=document.activeElement;if(n&&n!==document.body&&!e.contains(n))return;let r=function(e){if(!e||!e.isConnected)return null;if(n9(e))return e;let t=e.closest("[data-row-key]");if(!t)return null;for(let e of Array.from(t.querySelectorAll(n3)))if(e.tabIndex>=0&&n7(e))return e;return null}(t);r&&(r.focus({preventScroll:!0}),t&&r!==t&&n9(t)&&t.focus({preventScroll:!0}))}},[$,s]),(0,i.useEffect)(()=>{if(!$)return;let e=e=>{let t=S.current;if(!t||e.isComposing||229===e.keyCode)return;if("Escape"===e.key){e.preventDefault(),e.stopPropagation();let n=t.querySelector(n4);if(n&&w.current){k(""),n.focus({preventScroll:!0});return}C.current("escape");return}let n=e.target instanceof Element?e.target:null,r=null!==n&&t.contains(n),i=null===n||n===document.body||n===document.documentElement;if(!r&&!i)return;if("Tab"===e.key){var s;let i,o;r&&(s=e.shiftKey,i=Array.from(t.querySelectorAll(n3)).filter(e=>e!==n&&e.tabIndex>=0&&n7(e)),o=s?Node.DOCUMENT_POSITION_PRECEDING:Node.DOCUMENT_POSITION_FOLLOWING,i.some(e=>(n.compareDocumentPosition(e)&o)!=0))||C.current("outside");return}let o=("ArrowDown"===e.key||"ArrowUp"===e.key)&&n?.matches(n4);if(r&&function(e){if(!e)return!1;if(e.isContentEditable)return!0;let t=e.tagName;return"TEXTAREA"===t||"SELECT"===t||"INPUT"===t&&!["button","checkbox","radio","range","reset","submit","image","color","file"].includes((e.type||"text").toLowerCase())}(n)&&!o)return;if("ArrowDown"===e.key||"ArrowUp"===e.key||"Home"===e.key||"End"===e.key){let r,i=re(t);if(0===i.length)return;e.preventDefault(),e.stopPropagation();let s=n?i.indexOf(n):-1;r="Home"===e.key?0:"End"===e.key?i.length-1:"ArrowDown"===e.key?s<0?0:(s+1)%i.length:s<0?i.length-1:(s-1+i.length)%i.length,i[r].focus({preventScroll:!1});return}if(1!==e.key.length||e.ctrlKey||e.metaKey||e.altKey)return;let l=function(e,t){if(!e||1!==t.length)return null;let n=t.toLowerCase();for(let t of e)if("item"===t.type&&!t.disabled&&t.shortcut&&t.shortcut.toLowerCase()===n)return t;return null}(N.current,e.key);l&&!T&&(e.preventDefault(),e.stopPropagation(),A.current(l,e.shiftKey))};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[$,T]),(0,i.useEffect)(()=>{if(!$||s)return;let e=e=>{let t=S.current,n=e.target instanceof Node?e.target:null;if(!t||n&&t.contains(n))return;let r=E.current;r&&n&&0===e.button&&r.contains(n)&&function(e){let t=e.ownerDocument,n=t.defaultView;if(!n)return;let r=0,i=()=>{t.removeEventListener("click",s,!0),n.clearTimeout(r)};function s(t){i(),t.target instanceof Node&&e.contains(t.target)&&(t.preventDefault(),t.stopPropagation())}t.addEventListener("click",s,!0),r=n.setTimeout(i,1e3)}(r),C.current("outside")};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)},[$,s]),$&&b)?(0,tk.createPortal)((0,r.jsx)(ro,{sheet:s,ariaLabel:o,title:l,items:a,filter:d,filterQuery:j,onFilterQueryChange:k,cancelLabel:u,focusCancel:p,width:f,classic:g,footer:x,surfaceRef:S,onActivate:(e,t)=>A.current(e,t),onClose:e=>C.current(e),children:c}),b):null}function ra(e){let{heading:t,busy:n,error:s,showCancel:o,onCreate:l,onCancel:a}=e,{t:d}=(0,tn.s)(),[c,u]=(0,i.useState)(""),p=c.trim(),h=()=>{p&&!n&&l(p)};return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),(0,r.jsx)("input",{className:"sidebar-worktree-input","data-sidebar-menu-autofocus":"",value:c,readOnly:n,placeholder:d("sidebar.branchName"),"aria-label":d("sidebar.branchName"),onChange:e=>u(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),h())}}),(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-create",disabled:n||!p,onClick:h,children:d(n?"sidebar.creating":"sidebar.create")}),o&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel",onClick:a,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function rd(e,t){return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function rc(e){return e.branch??q(e.path)}function ru(e){let{heading:t,dirty:n,busy:i,error:s,showCancel:o,onForce:l,onCancel:a}=e,{t:d}=(0,tn.s)();return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),n&&(0,r.jsx)("div",{className:"sidebar-worktree-message",children:d("sidebar.forceRemoveCheckout")}),(n||o)&&(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[n&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-force",disabled:i,onClick:l,children:d("sidebar.force")}),o&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel","data-sidebar-menu-autofocus":"",onClick:a,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function rp(e){let{busy:t,onForce:n,onCancel:s}=e,{t:o}=(0,tn.s)(),l=(0,i.useId)();return(0,r.jsxs)("div",{className:"sidebar-worktree-confirm",children:[(0,r.jsx)("span",{id:l,className:"sidebar-worktree-confirm-text",title:o("sidebar.forceRemoveCheckout"),children:o("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","aria-describedby":l,"aria-disabled":!!t||void 0,className:"sidebar-worktree-force",onClick:()=>{t||n()},children:o("sidebar.force")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","data-sidebar-menu-autofocus":"",className:"sidebar-worktree-cancel",onClick:s,children:o("sidebar.cancel")})]})}function rh(e){let t,n,{layout:s,context:o,mobile:l,label:a,placeholder:d="",homeDir:c,projectActivity:u,worktreeHint:p=null,newWorktreeTitle:h,handleRef:m,onPick:f,onUseDefaultDirectory:g,onOpenFolder:x,onRefreshWorktrees:v,onCreateWorktree:b,onRemoveWorktree:y}=e,{t:j}=(0,tn.s)(),[k,w]=(0,i.useState)(null),S=(0,i.useRef)(k);S.current=k;let C=(0,i.useRef)(0),N=(0,i.useRef)(null),E=(0,i.useRef)(null),I=(0,i.useRef)(!1),$=(0,i.useRef)(f);$.current=f;let T="inline"!==s,M=!T,R=!l,{project:A,worktrees:L}=o,z=(t=o.worktrees??[]).find(e=>e.path===o.currentWorktreePath)??t.find(e=>e.isMain)??null,P=M&&A?eM(e$(o)).find(e=>{let{choice:t}=e;return t.key===A.key}):void 0;(0,i.useEffect)(()=>(I.current=!0,()=>{I.current=!1}),[]);let W=()=>(C.current+=1,C.current),O=()=>w(null),F=(e,t)=>{let n=t.getBoundingClientRect(),r=Math.max(T?220:"project"===e?260:240,Math.round(n.width));w({id:W(),kind:e,anchor:{kind:"rect",rect:{left:n.left,top:n.top,right:n.right,bottom:n.bottom},align:"row"===s&&"worktree"===e?"end":"start"},opener:t,width:r,body:null,removing:!1}),"worktree"===e&&v()},D=(0,i.useRef)(F);D.current=F,(0,i.useImperativeHandle)(m,()=>({button:e=>("worktree"===e?E:N).current,openMenu:e=>{let t=("worktree"===e?E:N).current;t&&D.current(e,t)}}),[]);let B=(e,t)=>{w(n=>n?.id===e?t(n):n)},H=e=>{let t=W();w(n=>n?.kind==="worktree"?{...n,id:t,body:e,removing:!1}:n)},_=async e=>{let t,n=S.current;if(!n||n.body?.kind!=="create"||!A)return;let{id:r}=n,i=(e,t)=>{B(r,n=>({...n,body:{kind:"create",busy:e,error:t}}))};i(!0,null);try{t=await b(A,e)}catch(e){t={error:e instanceof Error?e.message:String(e)}}I.current&&("error"in t?i(!1,t.error):S.current?.id===r&&(w(null),$.current({cwd:t.path,projectKey:A.key,projectRoot:A.root},"worktree")))},U=async(e,t)=>{let n,r=S.current;if(!r||!A||!y)return;let{id:i}=r;B(i,e=>({...e,removing:!0,body:e.body?.kind==="remove"?{...e.body,busy:!0,error:null}:e.body}));try{n=await y(A,e.path,t)}catch(e){n={error:e instanceof Error?e.message:String(e)}}I.current&&B(i,t=>{if("removed"===n)return{...t,removing:!1,body:null};let r="dirty"===n||t.body?.kind==="remove"&&t.body.dirty;return{...t,removing:!1,body:{kind:"remove",worktree:e,dirty:r,busy:!1,error:"dirty"===n?null:n.error}}})},K=()=>[...(L??[]).map(e=>R&&V?.kind==="remove"&&V.dirty&&V.worktree.path===e.path?{type:"custom",id:`worktree:${e.path}`,content:(0,r.jsx)(rp,{busy:V.busy,onForce:()=>{U(e,!0)},onCancel:()=>H(null)})}:{type:"item",id:`worktree:${e.path}`,label:R?e.branch??rd(e.path,c):rc(e),mono:R,path:R,note:e.isMain?j("sidebar.main"):void 0,title:e.path,checked:e.path===z?.path,secondary:y&&!e.isMain?{label:j("sidebar.removeWorktreeTitle",{path:e.path}),icon:(0,r.jsx)(n$,{size:12}),danger:!0,disabled:k?.removing,onSelect:t=>{let{keepOpen:n}=t;n(),U(e,!1)}}:void 0,onSelect:()=>{A&&e.path!==z?.path&&f({cwd:e.path,projectKey:A.key,projectRoot:A.root},"worktree")}}),...R?[]:[{type:"separator",id:"separator"}],...R&&V?.kind==="create"?[]:[{type:"item",id:"new-worktree",label:j("sidebar.newWorktree"),icon:(0,r.jsx)(nx,{size:13}),onSelect:e=>{let{keepOpen:t}=e;t(),H({kind:"create",busy:!1,error:null})}}]],V=k?.kind==="worktree"?k.body:null,Z="",J=null,G=null;if(R&&k?.kind==="worktree")Z=j("sidebar.switchWorktree"),n=K(),V?.kind==="create"?G=(0,r.jsx)(ra,{heading:null,busy:V.busy,error:V.error,showCancel:!0,onCreate:e=>{_(e)},onCancel:()=>H(null)}):V?.kind==="remove"&&V.error&&(G=(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:V.error}));else if(V?.kind==="create")Z=h,J=(0,r.jsx)(ra,{heading:l?null:Z,busy:V.busy,error:V.error,showCancel:!l,onCreate:e=>{_(e)},onCancel:O});else if(V?.kind==="remove")Z=j("sidebar.removeWorktreeHeading",{name:rc(V.worktree)}),J=(0,r.jsx)(ru,{heading:l?null:Z,dirty:V.dirty,busy:V.busy,error:V.error,showCancel:!l,onForce:()=>{U(V.worktree,!0)},onCancel:O});else if(k?.kind==="project"){let e,t;Z=j("workspace.project"),t=(e=eM(e$(o)).map(e=>{let{choice:t,name:n,note:i}=e,s=u?.get(t.key),o=R&&void 0===t.alias;return{type:"item",id:`project:${t.key}`,label:o?rd(t.root,c):n,note:o?void 0:i??void 0,mono:R,path:o,title:t.root,checked:t.key===A?.key,badge:s?(0,r.jsx)(nQ,{running:s.running,unread:s.unread,t:j}):void 0,onSelect:()=>{t.key===A?.key&&L||f({cwd:t.root,projectKey:t.key,projectRoot:t.root},"project")}}})).length>0?[{type:"separator",id:"separator"}]:[],n=[...e,...t,{type:"item",id:"default-directory",label:j("sidebar.useDefaultDirectory"),icon:(0,r.jsx)(nP,{size:13}),onSelect:()=>g()},{type:"item",id:"open-folder",label:j("sidebar.chooseFolder"),icon:R?(0,r.jsx)(nx,{size:13}):(0,r.jsx)(nW,{size:13}),onSelect:()=>x(k?.opener??null)}]}else k?.kind==="worktree"&&(Z=j("sidebar.switchWorktree"),n=K());let Y=k?.kind==="project"?{placeholder:j("sidebar.filterProjects"),emptyLabel:j("sidebar.noMatchingProjects"),minChoices:R?9:void 0}:{placeholder:j("sidebar.filterWorktrees"),emptyLabel:j("sidebar.noMatchingWorktrees")},X=T&&void 0!==u&&[...u].some(e=>{let[t,{running:n,unread:r}]=e;return t!==A?.key&&(n>0||r>0)});return(0,r.jsxs)("div",{className:`project-picker is-${s}`,role:"group","aria-label":a,children:[(0,r.jsxs)("button",{ref:N,type:"button",className:A?"project-picker-button is-project":"project-picker-button is-project is-empty",title:A?.root??"","aria-haspopup":"menu","aria-expanded":k?.kind==="project",onClick:e=>F("project",e.currentTarget),children:[M&&(0,r.jsx)(nP,{size:12,className:"project-picker-icon"}),M&&A?(0,r.jsxs)("span",{className:"project-picker-name",children:[void 0===A.alias&&P?.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"project-picker-parent",children:P.note}),"/"]}),(0,r.jsx)("span",{className:"project-picker-leaf",children:A.alias??P?.name??q(A.root)})]}):A?.alias!==void 0?(0,r.jsx)("span",{className:"project-picker-label is-alias",children:A.alias}):A?(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:rd(A.root,c)})}):(0,r.jsx)("span",{className:"project-picker-label",children:d}),X&&(0,r.jsx)("span",{className:"project-picker-activity",role:"img",title:j("sidebar.newActivity"),"aria-label":j("sidebar.newActivity")}),M&&(0,r.jsx)(nw,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),L&&(0,r.jsxs)("button",{ref:E,type:"button",className:"project-picker-button",title:z?j("sidebar.worktreePath",{path:z.path}):j("sidebar.switchWorktree"),"aria-haspopup":"menu","aria-expanded":k?.kind==="worktree",onClick:e=>F("worktree",e.currentTarget),children:[(0,r.jsx)(nS,{size:11,className:z&&!z.isMain?"project-picker-icon is-linked":"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:z?z.branch??rd(z.path,c):"…"})}),z?.isMain&&"stacked"===s&&(0,r.jsx)("span",{className:"project-picker-note",children:j("sidebar.main")}),T&&L.length>1&&(0,r.jsx)("span",{className:"project-picker-note",children:L.length}),(0,r.jsx)(nw,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),!L&&T&&p&&(0,r.jsxs)("button",{type:"button","aria-disabled":"true",tabIndex:-1,title:p.title,className:"project-picker-button is-inactive",children:[(0,r.jsx)(nS,{size:11,className:"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-label",children:p.label})]}),(0,r.jsx)(rl,{open:null!==k,anchor:k?.anchor??null,sheet:l,ariaLabel:Z,title:Z,items:n,filter:Y,cancelLabel:j("sidebar.cancel"),focusCancel:V?.kind==="remove",onClose:O,returnFocusTo:k?.opener??null,width:k?.width,classic:R,footer:G,focusKey:V?`${V.kind}:${"remove"===V.kind&&V.dirty}`:"list",children:J})]})}function rm(e){let{open:t,query:n,children:s,selectedSessionId:o,onSelectSession:l,archivedSessionIds:a}=e,{t:d,locale:c}=(0,tn.s)(),[u,p]=(0,i.useState)({query:""}),h=n.trim(),m=u.query===h?u.response:void 0,f=u.query===h&&u.failed;return(0,i.useEffect)(()=>{if(!t||!h)return;let e=new AbortController;p({query:h});let n=setTimeout(async()=>{try{let t=await fetch(`/api/sessions/search?${new URLSearchParams({q:h})}`,{signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e.signal.aborted||p({query:h,response:n})}catch{e.signal.aborted||p({query:h,failed:!0})}},300);return()=>{clearTimeout(n),e.abort()}},[t,h]),t&&h?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!m&&!f,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:f?d("sidebar.sessionSearchFailed"):m?0===m.results.length?d("sidebar.sessionSearchEmpty"):d("sidebar.sessionSearchCount",{count:m.results.length}):d("sidebar.sessionSearching")}),m?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:d("sidebar.sessionSearchPartial")}),m?.results.map(e=>{let{session:t,entryId:n,blockIndex:i,titleMatch:s,before:u,match:p,after:h}=e;return(0,r.jsxs)("button",{type:"button",onClick:()=>l(t,n,i),"aria-current":t.id===o?"true":void 0,className:`block w-full cursor-pointer border-b border-border px-3 py-2 text-left hover:bg-bg-hover focus-visible:outline-2 focus-visible:outline-accent ${t.id===o?"bg-bg-selected":""}`,children:[(0,r.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5",children:[(0,r.jsx)("span",{className:"min-w-0 truncate text-xs font-medium text-text",children:s?(0,r.jsxs)(r.Fragment,{children:[u,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:p}),h]}):t.name||t.firstMessage}),a?.has(t.id)&&(0,r.jsx)("span",{className:"shrink-0 rounded-[4px] border border-border px-1 text-[10px] leading-[14px] text-text-dim",children:d("sidebar.archived")})]}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate",title:t.cwd,children:t.cwd}),(0,r.jsx)("span",{className:"shrink-0",children:(0,nc.fw)(t.modified,c)})]}),!s&&(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[u,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:p}),h]})]},t.id)})]}):s}function rf(e){let{sessionId:t,leafId:n,onClose:s}=e,[o,l]=(0,i.useState)(!1),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),m=async()=>{if(!o){l(!0),d(null);try{let e=await fetch(`/api/sessions/${encodeURIComponent(t)}/share`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({leafId:n??void 0})}),r=await e.json().catch(()=>({}));if(!e.ok||!r.shareUrl||!r.destination)return void d(r.error||`HTTP ${e.status}`);let i={destination:r.destination,shareUrl:r.shareUrl,...r.gistUrl?{gistUrl:r.gistUrl}:{}};u(i),"u">typeof navigator&&navigator.clipboard?.writeText&&navigator.clipboard.writeText(i.shareUrl).then(()=>h(!0),()=>void 0)}catch(e){d(e instanceof Error?e.message:String(e))}finally{l(!1)}}};return(0,r.jsx)(rg,{busy:o,error:a,result:c,copied:p,onCancel:s,onConfirm:()=>void m(),onCopy:()=>{c?.shareUrl&&"u">typeof navigator&&navigator.clipboard?.writeText&&navigator.clipboard.writeText(c.shareUrl).then(()=>h(!0),()=>void 0)}})}function rg(e){let{busy:t,error:n,result:s,copied:o=!1,onCancel:l,onConfirm:a,onCopy:d}=e,{t:c}=(0,tn.s)(),u=(0,i.useRef)(null),p=(0,i.useRef)(t),h=(0,i.useRef)(l);(0,i.useEffect)(()=>{p.current=t,h.current=l},[t,l]),(0,i.useEffect)(()=>{if("u">typeof document)return eD(document,u.current,()=>{p.current||h.current()})},[]);let m=(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{t||e.target!==e.currentTarget||l()},children:(0,r.jsxs)("div",{ref:u,role:"dialog","aria-modal":"true","aria-labelledby":"share-session-title","aria-describedby":"share-session-description",tabIndex:-1,className:"project-trust-dialog",children:[(0,r.jsx)("div",{className:"project-trust-body",children:(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"share-session-title",className:"project-trust-title",children:c("share.dialogTitle")}),(0,r.jsx)("div",{id:"share-session-description",className:"project-trust-text",children:c(s?"share.sharedBody":"share.confirmBody")}),s&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginTop:10},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginBottom:4},children:c("share.shareUrlLabel")}),(0,r.jsx)("a",{href:s.shareUrl,target:"_blank",rel:"noopener noreferrer",className:"project-trust-path",style:{marginTop:0,color:"var(--accent)",textDecoration:"underline"},children:s.shareUrl})]}),s.gistUrl&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginBottom:4},children:c("share.gistUrlLabel")}),(0,r.jsx)("a",{href:s.gistUrl,target:"_blank",rel:"noopener noreferrer",className:"project-trust-path",style:{marginTop:0,color:"var(--accent)",textDecoration:"underline"},children:s.gistUrl})]})]})]})}),n&&(0,r.jsxs)("div",{role:"alert",className:"project-trust-error",children:[c("share.shareFailed"),(0,r.jsx)("code",{className:"project-trust-error-detail",children:n})]}),(0,r.jsx)("div",{className:"project-trust-footer",children:s?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:d,children:c(o?"share.copied":"share.copyLink")}),(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:l,children:c("share.close")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:l,disabled:t,children:c("share.cancel")}),(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:a,disabled:t,"aria-busy":t||void 0,children:c(t?"share.sharing":"share.confirm")})]})})]})});return"u">typeof document&&document.body?(0,tk.createPortal)(m,document.body):m}function rx(e){let{toast:t,dismissLabel:n,durationMs:s,onDismissRef:o}=e,l=(0,i.useRef)(null),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),p=a||c;return(0,i.useLayoutEffect)(()=>{let e=l.current;e&&window.matchMedia?.("(hover: hover)").matches&&e.matches(":hover")&&d(!0)},[]),(0,i.useEffect)(()=>{if(p)return;let e=window.setTimeout(()=>o.current(),s);return()=>window.clearTimeout(e)},[p,s,o]),(0,r.jsxs)("div",{ref:l,className:"sidebar-toast",onPointerEnter:e=>{"mouse"===e.pointerType&&d(!0)},onPointerLeave:()=>d(!1),onFocus:()=>u(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||u(!1)},children:[t.tail?(0,r.jsxs)("span",{className:"sidebar-toast-message has-tail",title:t.message+t.tail,children:[(0,r.jsx)("span",{className:"sidebar-toast-message-head",children:t.message}),(0,r.jsx)("span",{className:"sidebar-toast-message-tail",children:t.tail})]}):(0,r.jsx)("span",{className:"sidebar-toast-message",title:t.message,children:t.message}),t.actions.map(e=>(0,r.jsx)("button",{type:"button",className:"sidebar-toast-action",onClick:()=>{o.current(),e.onClick()},children:e.label},e.id)),(0,r.jsx)("button",{type:"button",className:"sidebar-toast-dismiss","aria-label":n,title:n,onClick:()=>o.current(),children:(0,r.jsx)(nz,{size:12})})]})}function rv(e){let{toast:t,onDismiss:n,dismissLabel:s,durationMs:o=1e4}=e,l=(0,i.useRef)(n);return l.current=n,(0,r.jsx)("div",{className:"sidebar-toast-region",role:"status","aria-live":"polite",children:t?(0,r.jsx)(rx,{toast:t,dismissLabel:s,durationMs:o,onDismissRef:l},t.id):null})}let rb={remote:"sidebar.openInExplorerRemoteOnly","unsupported-platform":"sidebar.openInExplorerUnsupported"};function ry(e){let{ref:t,onClick:n,title:i,disabled:s,pressed:o,expanded:l,controls:a,done:d,className:c,children:u}=e;return(0,r.jsx)("button",{ref:t,type:"button",onClick:n,disabled:s,title:i,"aria-label":i,"aria-pressed":o,"aria-expanded":l,"aria-controls":a,className:`sidebar-tool-button${o||l?" is-active":""}${d?" is-done":""}${c?` ${c}`:""}`,children:u})}let rj="pi-web:unread-session-ids",rk="pi-web:last-custom-cwd",rw={"open-new-tab":"sidebar.openInNewTab",pin:"sidebar.pin",unpin:"sidebar.unpin",rename:"sidebar.rename","generate-title":"title.generate",fork:"sidebar.fork",share:"sidebar.share",export:"sidebar.export","mark-read":"sidebar.markRead","mark-unread":"sidebar.markUnread",archive:"sidebar.archive",unarchive:"sidebar.unarchive",delete:"sidebar.delete"};function rS(){try{return window.localStorage.getItem(rk)??""}catch{return""}}async function rC(e){try{let t=await fetch("/api/cwd/pick",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:e})}),n=await t.json().catch(()=>({}));if(t.ok)return n.path?{path:n.path}:"cancelled";return"busy"===n.error?"busy":"unavailable"}catch{return"unavailable"}}function rN(e){if(!e)return new Set;try{let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e))}catch{}return new Set}function rE(e,t){let n=new Set(t);if(n.size!==e.size)return n;for(let t of n)if(!e.has(t))return n;return e}function rI(e,t){return e.length>t?`${e.slice(0,t)}…`:e}function r$(e){let t=document.activeElement;e&&t instanceof HTMLElement&&t!==document.body&&(0===t.getClientRects().length||null!==t.closest("[inert]"))?e.focus({preventScroll:!0}):eB(document,e)}function rT(e,t){let n=e.getBoundingClientRect();return{kind:"rect",rect:{left:n.left,top:n.top,right:n.right,bottom:n.bottom},align:t}}function rM(e){var t,n,s;let o,l,c,p,h,m,f,v,{selectedSessionId:y,onSelectSession:j,onNewSession:k,controlRef:w,onNewSessionContextChange:C,initialSessionId:W,initialSessionLinked:Z,skipInitialProjectSelection:eo,onInitialRestoreDone:em,refreshKey:eC,onSessionDeleted:eN,selectedCwd:e$,onCwdChange:eM,onOpenFile:eR,onOpenTerminal:ez,explorerRefreshKey:eF,onExplorerRefresh:eD,onAtMention:eH,onAtMentions:e_,onBackgroundTaskDone:eU,hiddenFinishedSessionIds:eK,onRunningSessionIdsChange:eq,onSessionsChange:eV,onSessionImported:eZ}=e,{t:eJ}=(0,tn.s)(),eG=tp(),[eY,eQ]=(0,i.useState)([]),e0=(0,i.useRef)(null),e1=(0,i.useRef)(0),[e2,e4]=(0,i.useState)(!0),[e8,e3]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(null),[e9,e7]=(0,i.useState)(null),[te,tr]=(0,i.useState)(""),[ti,ts]=(0,i.useState)(!1),[to,tl]=(0,i.useState)(rS),[ta,td]=(0,i.useState)(null),[tc,tu]=(0,i.useState)(!1),[th,tm]=(0,i.useState)(null),tv=(0,i.useRef)(null),[tk,tw]=(0,i.useState)(null),[tS,tC]=(0,i.useState)(null),tN=(0,i.useRef)(null);tN.current??=new Set(ej());let[tE,tI]=(0,i.useState)(0),[t$,tT]=(0,i.useState)(!1),[tM,tL]=(0,i.useState)(!1),[tP,tW]=(0,i.useState)(!1),[tO,tF]=(0,i.useState)(""),[tD,tB]=(0,i.useState)(null),[tH,t_]=(0,i.useState)(null),[tU,tK]=(0,i.useState)(null),[tq,tV]=(0,i.useState)(0),[tZ,tJ]=(0,i.useState)(!0),[tG,tY]=(0,i.useState)(!1),[tX,tQ]=(0,i.useState)(!1),[t0,t1]=(0,i.useState)(null),[t2,t4]=(0,i.useState)(null),[t8,t3]=(0,i.useState)(()=>new Set),[t5,t6]=(0,i.useState)(()=>new Set),[t9,t7]=(0,i.useState)(()=>new Set),[ne,nt]=(0,i.useState)(()=>(function(){try{return rN(window.localStorage.getItem(rj))}catch{return new Set}})()),nn=(0,i.useRef)(new Set),ni=(0,i.useRef)(new Set),no=(0,i.useRef)(new Set),nl=(0,i.useRef)(new Set),na=(0,i.useRef)(!1),nc=(0,i.useRef)(null),nu=(0,i.useRef)(null),np=(0,i.useRef)(null),nh=tt(),nm=!eG&&"below"===nh,[nf,ng]=(0,i.useState)("sessions"),[nS,nz]=(0,i.useState)(!1),nW=(0,i.useRef)(null),nV=(0,i.useRef)(null),nJ=(0,i.useRef)(null),nG=(0,i.useRef)(null),nY=(0,i.useRef)(new WeakMap),[nX,nQ]=(0,i.useState)({}),[n0,n1]=(0,i.useState)(()=>new Set),[n2,n4]=(0,i.useState)({}),[n8,n3]=(0,i.useState)(!1),[n5,n6]=(0,i.useState)([]),[n9,n7]=(0,i.useState)(!1),{phase:re,start:rt,end:rn}=tj(),{phase:rr,start:ri,end:rs}=tj(),ro=(0,i.useRef)(nS);ro.current=nS;let ra=(0,i.useRef)(n9);ra.current=n9;let rd=(0,i.useCallback)(e=>{e!==ra.current&&ri(e?"in":"out"),n7(e)},[ri]),rc=(o=nS&&"out"===re,l=!nS&&"in"===re,{bodyHidden:nS&&!o,bodyInert:o,moving:o||l,open:!nS&&!l}),ru=(c=n9&&"in"===rr,p=!n9&&"out"===rr,{mainHidden:n9&&!c,mainInert:c,archiveMounted:n9||p,archiveInert:p,archiveClass:c?"is-entering":p?"is-leaving":null}),[rp,rg]=(0,i.useState)(null),[rx,rM]=(0,i.useState)(null),[rR,rA]=(0,i.useState)(null),[rL,rz]=(0,i.useState)(null),[rP,rW]=(0,i.useState)(null),rO=(0,i.useRef)(0),rF=(0,i.useCallback)(e=>{rW(t=>t?.id===e?null:t)},[]),[rD,rB]=(0,i.useState)(null),rH=(0,i.useCallback)(e=>{rB(t=>t?.id===e?null:t)},[]),r_=(0,i.useRef)(y);r_.current=y;let[rU,rK]=(0,i.useState)(null),rq=(0,i.useRef)(0),rV=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2?arguments[2]:void 0;rq.current+=1,rK({id:rq.current,message:e,...n?{tail:n}:{},actions:t})},[]),[rZ,rJ]=(0,i.useState)(0),rG=(0,i.useRef)(0),rY=(0,i.useRef)(null),[rX,rQ]=(0,i.useState)(0),r0=(0,i.useRef)(null),r1=(0,i.useRef)(null),r2=(0,i.useRef)(null),r4=(0,i.useRef)(null),[r8,r3]=(0,i.useState)(0),r5=(0,i.useCallback)(e=>{r4.current=e,r3(e=>e+1)},[]);(0,i.useEffect)(()=>{let e=r4.current;r4.current=null,e&&eB(document,e())},[r8]);let{state:r6,loaded:r9,synced:r7,error:ie,apply:it,snapshot:ir,noteRevision:ii}=function(){let[e,t]=(0,i.useState)(R),[n,r]=(0,i.useState)(!1),[s,o]=(0,i.useState)(!1),[l,a]=(0,i.useState)(null),d=(0,i.useRef)(e),c=(0,i.useRef)(e),u=(0,i.useRef)([]),p=(0,i.useRef)(Promise.resolve()),h=(0,i.useRef)(0),m=(0,i.useRef)(null),f=(0,i.useCallback)(()=>{let e=d.current;for(let{request:t,now:n}of u.current)e=function(e,t,n){var r,i,s,o;let l=function(e){let t={};for(let[n,r]of Object.entries(e.sessions))t[n]={...r};let n={};for(let[t,r]of Object.entries(e.projects))n[t]={...r};let r={...e,sessions:t,projects:n};return e.projectOrder&&(r.projectOrder=[...e.projectOrder]),e.projectNames&&(r.projectNames={...e.projectNames}),r}(e),a=!1;switch(t.action){case"set":for(let e of t.ids){let r=b(l.sessions,e)?l.sessions[e]:void 0;A(l.sessions,e,function(e,t,n){let r={...e};return"pinned"in t?t.pinned?(void 0===r.pinnedAt||void 0!==r.archivedAt)&&(r.pinnedAt=n,delete r.archivedAt):delete r.pinnedAt:t.archived?(r.archivedAt=n,delete r.pinnedAt):delete r.archivedAt,r}(r,t,n))&&(a=!0)}break;case"restore":for(let e of t.entries){let t={};null!==e.pinnedAt&&(t.pinnedAt=e.pinnedAt),null!==e.archivedAt&&(t.archivedAt=e.archivedAt),A(l.sessions,e.id,t)&&(a=!0)}break;case"pin-project":{let{projectKey:e,root:o}=t,d=b(l.projects,e)?l.projects[e]:void 0;if(t.pinned?d?.root!==o&&(l.projects[e]={pinnedAt:n,root:o},a=!0):d&&(delete l.projects[e],a=!0),(t.pinned?void 0===d:void 0!==d)&&l.projectOrder){let n,o,d=(r=l.projectOrder,i=l.projects,s=t.pinned,o=r.filter(t=>t!==e),s?(n=0,o.forEach((e,t)=>{b(i,e)&&(n=t+1)})):(n=o.findIndex(e=>!b(i,e)))<0&&(n=o.length),o.splice(n,0,e),o);I(d.length,E(d))&&L(l,d)&&(a=!0)}break}case"add-projects":L(l,function(e,t){let n=z(e,t),r=e.length,i=E(e),s=n.length;for(;s>0;){let e=N(n[s-1]);if(!I(r+1,i+e))break;r++,i+=e,s--}return[...n.slice(s),...e]}(l.projectOrder??[],t.keys))&&(a=!0);break;case"move-project":{let e,n,{projectKey:r,anchorKey:i,position:s,add:d}=t,c=l.projectOrder??[];L(l,function(e,t){let n=e.length,r=E(e);if(I(n,r))return e;let i=new Set;for(let s=e.length-1;s>=0&&!I(n,r);s--)t.has(e[s])||(i.add(s),n--,r-=N(e[s]));let s=e.filter((e,t)=>!i.has(t));return I(n,r)?s:$(s)}((o=[...z(c,d),...c],(e=o.filter(e=>e!==r)).includes(i)||e.unshift(i),n=e.indexOf(i),e.splice("before"===s?n:n+1,0,r),e),new Set([r,i,...d])))&&(a=!0);break}case"rename-project":{let e=S(t.name);void 0!==e&&function(e,t,n){let r={...e.projectNames};if((b(r,t)?r[t]:void 0)===(n??void 0))return!1;if(null===n)delete r[t];else if(r[t]=n,!M(Object.keys(r).length,function(e){let t=1;for(let[n,r]of Object.entries(e))t+=T(n,r);return t}(r)))return!1;return 0===Object.keys(r).length?delete e.projectNames:e.projectNames=r,!0}(l,t.projectKey,e)&&(a=!0)}}return{state:l,changed:a}}(e,t,n).state;c.current=e,t(e)},[]),g=(0,i.useCallback)(async e=>{let t=++h.current;m.current=t;try{let n=await fetch(tx,{cache:"no-store"}),i=await ty(n);if(t!==h.current)return;d.current=i,f(),e||a(null),r(!0),o(!0)}catch(e){if(t!==h.current)return;a(tb(e)),r(!0)}finally{m.current===t&&(m.current=null)}},[f]),x=(0,i.useCallback)(()=>g(!1),[g]),v=(0,i.useCallback)(e=>{"number"!=typeof e||!Number.isFinite(e)||u.current.length>0||e===d.current.revision||(null===m.current||m.current!==h.current)&&x()},[x]),y=(0,i.useCallback)(e=>{let t={request:e,now:Date.now()};u.current=[...u.current,t],f();let n=async()=>{let n=!1;try{let t=await fetch(tx,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"}),i=await ty(t);h.current++,d.current=i,a(null),r(!0),o(!0),n=!0}catch(e){a(tb(e))}return u.current=u.current.filter(e=>e!==t),f(),n||await g(!0),n},i=p.current.then(n,n);return p.current=i,i},[g,f]),j=(0,i.useCallback)(e=>(function(e,t){let n=new Set,r=[];for(let i of t){if(n.has(i))continue;n.add(i);let t=b(e.sessions,i)?e.sessions[i]:void 0;r.push({id:i,pinnedAt:t?.pinnedAt??null,archivedAt:t?.archivedAt??null})}return r})(c.current,e),[]);return(0,i.useEffect)(()=>{x()},[x]),(0,i.useMemo)(()=>({state:e,loaded:n,synced:s,error:l,refresh:x,noteRevision:v,apply:y,snapshot:j}),[e,n,s,l,x,v,y,j])}(),is=(0,i.useRef)(null),io=(0,i.useRef)(null);tg(io);let il=(0,i.useRef)(null),ia=(0,i.useRef)(null),id=(0,i.useRef)(320),ic=(0,i.useCallback)(()=>{let e=ia.current,t=is.current;return e&&t&&0!==e.clientHeight?e.clientHeight-t.offsetHeight:window.innerHeight-36},[]),iu=(0,i.useCallback)(()=>Math.round(.45*ic()),[ic]),ip=(0,i.useCallback)(()=>ic()-120,[ic]),ih=tf({ariaLabel:eJ("sidebar.resizeFiles"),axis:"vertical",cssVariable:"--sidebar-files-height",defaultWidth:320,getDefaultWidth:iu,getMaxWidth:ip,growthDirection:"up",maxWidth:2e3,minWidth:220,persistClamp:!1,storageKey:"pi-web:sidebar-files-height",widthRef:id}),im=ih.panelRef,ig=(0,i.useCallback)(e=>{ia.current=e,im.current=e},[im]),ix=ih.reclampWidth;(0,i.useEffect)(()=>{let e=ia.current;if(!nm||!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>ix());return t.observe(e),()=>t.disconnect()},[ix,nm]),(0,i.useEffect)(()=>{let e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ex();if(!e)return"sessions";try{return"files"===e.getItem(el)?"files":"sessions"}catch{return"sessions"}}();"sessions"!==e&&ng(e);let t=function(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ex();if(!t)return{};try{let e=t.getItem(ea);if(null!==e)return ev(JSON.parse(e))}catch{return{}}try{let n=t.getItem(ed);if(null===n)return{};e=ev(JSON.parse(n))}catch{e={}}let n=Object.fromEntries(Object.entries(e).filter(e=>{let[,t]=e;return!t}));return eb(n,t),n}();Object.keys(t).length>0&&nQ(t),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ex();if(!e)return!1;try{return"true"===e.getItem(eu)}catch{return!1}}()&&n3(!0);let n=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ex();if(!e)return[];try{let t=e.getItem(ec),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e&&""!==e);return[...new Set(r)].slice(-300)}catch{return[]}}();n.length>0&&n6(n),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ex();if(!e)return!1;try{return"true"===e.getItem(eh)}catch{return!1}}()&&nz(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ex();if(!e)return!1;try{return"true"===e.getItem(ep)}catch{return!1}}()&&tY(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ex();if(e)for(let t of eg)try{e.removeItem?.(t)}catch{}}()},[]);let iv=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=++e1.current;try{e&&e4(!0);let i=await fetch(n?"/api/sessions?summary=1":t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(r!==e1.current)return;e0.current=s.sessionListVersion,eQ(s.sessions),n||e3(!0),na.current||(no.current=new Set(s.completionNotificationSuppressedSessionIds??[]),t3(e=>rE(e,s.runningSessionIds??[])),t6(e=>rE(e,s.awaitingInputSessionIds??[])));let o=new Set(s.sessions.filter(e=>!a(e.relation)).map(e=>e.id));nt(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>o.has(e)));return t.size===e.size?e:t}),e6(null)}catch(e){r===e1.current&&e6(String(e))}finally{r===e1.current&&e4(!1)}},[]),ib=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!ib.current;ib.current=!0;let t=!0;return e?iv(!0,!1,!0).then(()=>{t&&(nc.current=setTimeout(()=>{nc.current=null,t&&iv(!1,!0)},750))}):iv(),()=>{t=!1,nc.current&&(clearTimeout(nc.current),nc.current=null)}},[iv,eC]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/open-in-explorer").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&t1(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{t4(null)},[e9,e$]);let iy=(0,i.useCallback)(async()=>{let e=e9??e$;if(!e)return!1;try{let t=await fetch("/api/open-in-explorer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e})});if(t.ok)return t4(null),!1;let n=await t.json().catch(()=>({}));t4(n.error??`HTTP ${t.status}`)}catch(e){t4(e instanceof Error?e.message:String(e))}return!0},[e9,e$]),ij=eJ(t0?.platform==="darwin"?"sidebar.openInFinder":t0?.platform==="win32"?"sidebar.openInExplorer":"sidebar.openInFileManager"),ik=t0?.supported===!1,iw=t2?eJ(rb[t2]??t2):null;(0,i.useEffect)(()=>{try{0===ne.size?window.localStorage.removeItem(rj):window.localStorage.setItem(rj,JSON.stringify([...ne]))}catch{}},[ne]),(0,i.useEffect)(()=>{let e=e=>{(null===e.key||e.key===rj)&&nt(t=>rE(t,[...rN(e.newValue)]))};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;let o=Date.now(),l=null,a="error",d=null;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(d=t.status,!t.ok)return;a="ok";let r=await t.json();if(l=Date.now(),e||n!==s)return;na.current=!0,no.current=new Set(r.completionNotificationSuppressedSessionIds??[]),t3(e=>rE(e,r.runningSessionIds??[])),t6(e=>rE(e,r.awaitingInputSessionIds??[])),t7(e=>rE(e,r.subagentsActiveSessionIds??[])),ii(r.sessionUiStateRevision),r.sessionListVersion!==e0.current&&await iv()}catch{a=s.signal.aborted?"aborted":"error"}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500)),function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=Date.now();eX.count+=1,"error"===t&&(eX.failures+=1),eX.last={at:i,durationMs:Math.max(0,(r??i)-e),outcome:t,httpStatus:n}}(o,a,d,l)}},s=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",s),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",s)}},[iv,ii]),(0,i.useEffect)(()=>{eq?.(t8)},[eq,t8]),(0,i.useEffect)(()=>{eV?.(eY)},[eY,eV]),(0,i.useEffect)(()=>{!function(e){let t,n;if("u"<typeof document)return;let r=(n=(t=eA(e.awaiting))+eA(e.unread))<=0?null:{kind:t>0?"awaiting":"unread",count:Math.min(n,99)},i=r?`${r.kind}:${r.count}`:"none";if(i!==eL){if(eL=i,!r){for(let[e,t]of eP)e.href=t;return}for(let e of eW())eP.has(e)||eP.set(e,e.href);eO(r,i)}}({awaiting:t5.size,unread:function(e,t){if(!t||0===t.size)return e.size;let n=0;for(let r of t)e.has(r)||(n+=1);return e.size+n}(ne,eK)})},[t5,ne,eK]),(0,i.useEffect)(()=>{let e=nn.current,t=[...e].filter(e=>!t8.has(e)&&e!==y),n=new Set([...t8,...t9]),r=[...ni.current].filter(e=>!n.has(e)&&e!==y),i=new Set(eY.filter(e=>a(e.relation)).map(e=>e.id)),s=r.filter(e=>!nl.current.has(e)&&!i.has(e)),o=[...t8].filter(t=>!e.has(t));(s.length>0||o.length>0)&&nt(e=>{let t=new Set(e);return t8.forEach(e=>t.delete(e)),s.forEach(e=>t.add(e)),t});let l=o.some(e=>!eY.some(t=>t.id===e));(t.length>0||l)&&iv(),s.length>0&&eU?.(),nn.current=t8,ni.current=n;let d=nl.current;nl.current=new Set([...n].filter(e=>no.current.has(e)||i.has(e)||d.has(e)&&!t8.has(e)))},[t8,t9,y,eY,iv,eU]),(0,i.useEffect)(()=>{y&&nt(e=>{if(!e.has(y))return e;let t=new Set(e);return t.delete(y),t})},[y]),(0,i.useEffect)(()=>{void 0!==eF&&tI(e=>e+1)},[eF]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&tr(e.home)}).catch(()=>{})},[]);let iS=(0,i.useRef)(!1),iC=(0,i.useRef)(!1);(0,i.useEffect)(()=>{e9&&(iC.current=!1)},[e9]);let iN=(0,i.useCallback)(e=>e?function(e,t){let{validated:n,listing:r,sessions:i}=t;if(n?.cwd===e)return{root:n.root,key:n.key};if(r?.forCwd===e||r?.isTopLevel&&r.worktrees.some(t=>t.path===e))return{root:r.projectRoot,key:r.projectKey};let s=i.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return s?{root:s.projectRoot??s.cwd,key:g(s)}:{root:e,key:e}}(e,{validated:th,listing:tk,sessions:eY}):null,[th,tk,eY]),iE=(0,i.useMemo)(()=>iN(e9),[iN,e9]),iI=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=iN(e9),t=iI.current;(t?.cwd!==e9||t.key!==(e?.key??null))&&(iI.current={cwd:e9,key:e?.key??null},eM?.(e9,e?.root??null,e?.key??null))},[e9,eM,iN]);let i$=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!e$){i$.current=null;return}e$!==i$.current&&(i$.current=e$,e7(e$))},[e$]);let[iT,iM]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!e9){tw(null),tC(null);return}let e=!1;return tC(e9),fetch(`/api/worktrees?cwd=${encodeURIComponent(e9)}`).then(e=>e.json()).then(t=>{if(!e){if(tC(null),t.error||!t.projectRoot)return void tw(null);t.isGit?tN.current?.delete(e9):tN.current?.add(e9),function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ex();if(!n||!e)return;let r=ej(n),i=r.indexOf(e);if(t?-1===i:-1!==i&&i===r.length-1)return;let s=r.filter(t=>t!==e);t||s.push(e);try{n.setItem(ef,JSON.stringify(s.slice(-50)))}catch{}}(e9,!!t.isGit),tw({forCwd:e9,projectRoot:t.projectRoot,projectKey:t.projectKey??t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,currentWorktreePath:t.currentWorktreePath??null,worktrees:t.worktrees??[]})}}).catch(()=>{e||(tC(null),tw(null))}),()=>{e=!0}},[e9,iT,eC]),(0,i.useEffect)(()=>{if(0!==eY.length&&!eo&&!iC.current&&null===e9){if(W&&!iS.current){iS.current=!0;let e=eY.find(e=>e.id===W);if(e){e7(e.cwd),j(e,!0);return}em?.(),Z&&rV(eJ("sidebar.sessionNotFound"))}let e=x(eY);e.length>0&&e7(e[0].root)}},[eY,e9,W,Z,eo,j,em,rV,eJ]);let iR=tk?tk.worktrees.find(e=>e.path===e9)??(tk.forCwd===e9&&tk.currentWorktreePath?tk.worktrees.find(e=>e.path===tk.currentWorktreePath):void 0)??tk.worktrees.find(e=>e.isMain):void 0,iA=iR?.path??null,iL=(0,i.useCallback)(async function(e){let{remember:t=!0,purpose:n=ti}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=(e??to).trim();if(!r||tc)return!1;tu(!0),td(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r})}),s=await e.json().catch(()=>({}));if(!e.ok||s.error||!s.cwd||!s.projectRoot||!s.projectKey)return td(s.error??`HTTP ${e.status}`),!1;if(t){var i=s.cwd;try{window.localStorage.setItem(rk,i)}catch{}tl(s.cwd)}if(ts(!1),"new-session"===n){let e=r1.current,t=r2.current;return r1.current=null,r2.current=null,e?.({cwd:s.cwd,projectKey:s.projectKey,projectRoot:s.projectRoot}),r5(()=>t?.isConnected?t:null),!0}return tm({cwd:s.cwd,root:s.projectRoot,key:s.projectKey}),e7(s.cwd),!0}catch(e){return td(e instanceof Error?e.message:String(e)),!1}finally{tu(!1)}},[ti,to,tc,r5]),iz=(0,i.useCallback)(e=>{let t="new-session"===e?r2.current:null;r1.current=null,r2.current=null,ts(!1),td(null),t&&r5(()=>t.isConnected?t:null)},[r5]),iP=(0,i.useRef)(!1),iW=(0,i.useCallback)(async e=>{if(td(null),!iP.current){let t=await rC(eJ("directoryPicker.selectDirectory"));if("busy"===t)return;if("cancelled"===t)return void iz(e);if("unavailable"!==t){if(await iL(t.path,{purpose:e}))return;tl(t.path),ts(e);return}iP.current=!0}ts(e)},[iz,iL,eJ]),iO=(0,i.useRef)(iW);iO.current=iW;let iF=(0,i.useCallback)(()=>{iW("files")},[iW]),iD=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"files";try{let t=await fetch("/api/default-cwd",{method:"POST"}),n=await t.json();n.cwd&&await iL(n.cwd,{remember:!1,purpose:e})}catch{}},[iL]),iB=(0,i.useRef)(iD);iB.current=iD;let iH=(0,i.useCallback)(async(e,t)=>{try{let r=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.root,branch:t})}),i=await r.json().catch(()=>({}));if(!r.ok||i.error||!i.path){var n;let e,t=(n=r.status,(e="branch_in_use"===i.code?"sidebar.worktreeBranchInUse":"branch_worktree_missing"===i.code?"sidebar.worktreeBranchMissing":null)&&i.branch&&i.worktreePath?{key:e,params:{branch:i.branch,path:i.worktreePath}}:{error:i.error??`HTTP ${n}`});return"key"in t?{error:eJ(t.key,{...t.params,path:eS(t.params.path)})}:t}let s=i.path;return tw(n=>n&&n.projectKey===e.key&&!n.worktrees.some(e=>e.path===s)?{...n,worktrees:[...n.worktrees,{path:s,branch:t,isMain:!1}]}:n),iM(e=>e+1),{path:s}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[eJ]),i_=(0,i.useCallback)(async(e,t,n)=>{try{let r=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.root,path:t,force:n})}),i=await r.json().catch(()=>({}));if(!r.ok){if(i.dirty&&!n)return"dirty";return{error:i.error??`HTTP ${r.status}`}}return iA===t&&e7(e.root),iM(e=>e+1),"removed"}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[iA]),iU=(0,i.useCallback)(()=>iM(e=>e+1),[]),iK=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r}=e;n&&r&&tm({cwd:t,root:r,key:n}),e7(t)},[]),iq=(0,i.useCallback)((e,t,n,r)=>{eQ(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&e7(e.cwd),j(e,!1,t,n,r)},[j]),iV=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r,carryComposer:i}=e;n&&r&&tm({cwd:t,root:r,key:n}),e7(t),k?.("function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`,t,n,i?{carryComposer:!0}:void 0)},[k]),iZ=(0,i.useRef)(iV);iZ.current=iV,(0,i.useImperativeHandle)(w,()=>({startNewSessionIn:e=>iZ.current(e),openFolderForNewSession:(e,t)=>{r1.current=e,r2.current=t,iO.current("new-session")},openDefaultDirectoryForNewSession:e=>{r1.current=e,r2.current=null,iB.current("new-session")},refreshWorktrees:iU,createWorktree:iH}),[iH,iU]);let iJ=(0,i.useCallback)(()=>{e9&&iV({cwd:e9})},[e9,iV]),iG=(0,i.useMemo)(()=>x(eY),[eY]),iY=(0,i.useMemo)(()=>d(eY),[eY]),iX=(0,i.useMemo)(()=>new Map(iY.map(e=>[e.root.id,e])),[iY]),iQ=(0,i.useMemo)(()=>{let e=new Set,t=new Map;for(let n of iY){if(!U(n,r6,t8))continue;for(let t of H(n))e.add(t);let r=g(n.root);t.set(r,(t.get(r)??0)+1)}return{ids:e,countByProject:t}},[iY,r6,t8]),i0=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=g(i);if(!e)continue;let s=r.get(e);s||(s={running:0,unread:0},r.set(e,s)),t.has(i.id)&&s.running++,n.has(i.id)&&s.unread++}return r})(0===iQ.ids.size?eY:eY.filter(e=>!iQ.ids.has(e.id)),t8,ne),[eY,iQ,t8,ne]),i1=!!(tk?.isGit&&tk.isTopLevel&&e9&&iE?.key===tk.projectKey),i2=e9&&tk?.isGit&&iE?.key===tk.projectKey&&!i1?{label:eJ("sidebar.openRepoRoot"),title:eJ("sidebar.openRepoRootTitle")}:null,i4=!!(e9&&tS===e9),i8=i2??(!i4||i1||e9&&tN.current?.has(e9)?null:{label:eJ("sidebar.worktrees"),title:eJ("sidebar.checkingWorktrees")}),i3=iE?.key??null,i5=iE?.root??null,i6=(0,i.useMemo)(()=>i3&&i5?{key:i3,root:i5}:null,[i3,i5]),i9=(0,i.useMemo)(()=>0===n0.size?nX:Object.fromEntries([...[...n0].filter(e=>!Object.hasOwn(nX,e)).map(e=>[e,!0]),...Object.entries(nX)]),[nX,n0]),i7=(0,i.useMemo)(()=>(function(e){let{uiState:t,runningIds:n,currentProject:r}=e,i=d(e.sessions),s=Y(t,r),o=0,l=[],a=new Map,c=new Map,u=new Set;for(let e of i){if(U(e,t,n)){o++;continue}s.noteFamily(e);let r=G(e),i=function(e){let t=Date.parse(e);return Number.isNaN(t)?-1/0:t}(e.latestModified);if(c.set(r,Math.max(c.get(r)??-1/0,i)),e.root.transient||u.add(r),K(e,t,n)){l.push(e);continue}let d=a.get(r);d?d.push(e):a.set(r,[e])}let p=[{kind:"spacer",key:"top-spacer"}];if(l.length>0){let n=e=>D(F(t,e.root.id)?.pinnedAt)??0,r=l.map((e,t)=>({family:e,index:t})).sort((e,t)=>B(n(e.family),n(t.family))||e.index-t.index).map(e=>{let{family:t}=e;return t}),{running:i,awaiting:o,unread:a}=J(r,e);if(p.push({kind:"pinned-header",key:"pinned-header",count:r.length,collapsed:e.pinnedCollapsed,running:i,awaiting:o,unread:a}),!e.pinnedCollapsed){let{visible:t,revealed:n,nextShown:i}=Q(r,8,ee(e.moreShown,O),e);for(let n of t)p.push(X(n,"pinned",s.get(G(n)),e));let o=en(r.length,t.length,n);o&&p.push({kind:"pinned-more",key:"pinned-more",...o,nextShown:i})}p.push({kind:"spacer",key:"pinned-spacer"})}let h=[...a.keys()],m=new Set(h),f=e=>{m.has(e)||(m.add(e),h.push(e))};for(let e of(r&&f(r.key),Object.keys(t.projects)))f(e);let g=h.map(e=>s.get(e)),x=new Map;(t.projectOrder??[]).forEach((e,t)=>{x.has(e)||x.set(e,t)});let v=e=>e.pinned||u.has(e.key),b=(e,t)=>[...e.filter(e=>{let{project:t}=e;return!x.has(t.key)}).sort((e,n)=>Number(v(e.project))-Number(v(n.project))||t(e,n)),...e.filter(e=>{let{project:t}=e;return x.has(t.key)}).sort((e,t)=>(x.get(e.project.key)??0)-(x.get(t.project.key)??0))].map(e=>{let{project:t}=e;return t}),y=e=>c.get(e.key)??(e.current?1/0:-1/0),j=e=>D(t.projects[e.key]?.pinnedAt)??0,k=g.map((e,t)=>({project:e,index:t})),w=b(k.filter(e=>{let{project:t}=e;return t.pinned}),(e,t)=>B(j(t.project),j(e.project))||e.index-t.index),S=b(k.filter(e=>{let{project:t}=e;return!t.pinned}),(e,t)=>B(y(e.project),y(t.project))||e.index-t.index),C=[...w,...S],N=e=>e.filter(e=>!x.has(e.key)).map(e=>e.key),E={pinned:N(w),other:N(S)},I=C.filter(e=>!x.has(e.key)&&v(e)).map(e=>e.key);for(let[t,n]of C.entries()){t>0&&p.push({kind:"spacer",key:`group-spacer:${n.key}`});let r=a.get(n.key)??[],i=V(n,e.groupExpansion),{running:s,awaiting:o,unread:l}=J(r,e);if(p.push({kind:"group",key:`group:${n.key}`,project:n,expanded:i,running:s,awaiting:o,unread:l}),i)if(0===r.length)p.push({kind:"group-empty",key:`empty:${n.key}`,project:n});else{let{visible:t,revealed:i,nextShown:s}=Q(r,6,ee(e.moreShown,n.key),e);for(let r of t)p.push(X(r,"group",n,e));let o=en(r.length,t.length,i);o&&p.push({kind:"group-more",key:`more:${n.key}`,projectKey:n.key,...o,nextShown:s})}}return C.length>0&&p.push({kind:"spacer",key:"footer-spacer"}),p.push({kind:"footer-open",key:"footer-open"}),o>0&&p.push({kind:"footer-archived",key:"footer-archived",count:o}),{rows:p,projects:C,archivedCount:o,unorderedKeysByBand:E,projectKeysToRecord:I}})({sessions:eY,uiState:r6,runningIds:t8,awaitingIds:t5,unreadIds:ne,selectedSessionId:y,currentProject:i6,groupExpansion:i9,moreShown:n2,pinnedCollapsed:n8}),[eY,r6,t8,t5,ne,y,i6,i9,n2,n8]),se=ru.archiveMounted,st=(0,i.useMemo)(()=>new Set(n5),[n5]),sn=(0,i.useMemo)(()=>se?function(e){let{uiState:t,runningIds:n}=e,r=Y(t,e.currentProject),i=new Map;for(let s of d(e.sessions)){if(!U(s,t,n))continue;r.noteFamily(s);let e=D(F(t,s.root.id)?.archivedAt)??0,o=G(s),l=i.get(o);l?(l.families.push({family:s,archivedAt:e}),l.newest=Math.max(l.newest,e)):i.set(o,{newest:e,families:[{family:s,archivedAt:e}]})}let s=[];for(let{key:t,group:n}of[...i.entries()].map((e,t)=>{let[n,r]=e;return{key:n,group:r,index:t}}).sort((e,t)=>B(e.group.newest,t.group.newest)||e.index-t.index)){let i=r.get(t),o=!e.collapsed?.has(t);if(s.push({kind:"archive-group",key:`archive:${t}`,project:i,count:n.families.length,expanded:o}),o)for(let{family:t}of n.families.map((e,t)=>({...e,index:t})).sort((e,t)=>B(e.archivedAt,t.archivedAt)||e.index-t.index))s.push(X(t,"archive",i,e))}return s}({sessions:eY,uiState:r6,runningIds:t8,awaitingIds:t5,unreadIds:ne,selectedSessionId:y,currentProject:i6,collapsed:st}):[],[se,eY,r6,t8,t5,ne,y,i6,st]),sr=(0,i.useMemo)(()=>sn.flatMap(e=>"archive-group"===e.kind?[e]:[]),[sn]),si=(0,i.useMemo)(()=>new Map(i7.projects.map(e=>[e.key,e])),[i7.projects]),ss=(0,i.useRef)(new Set),so=i7.projectKeysToRecord,sl=r6.projectOrder?.length??0;(0,i.useEffect)(()=>{if(e2||!r7||!e8||sl>=1e3)return;let e=ss.current,t=function(e,t){let n=e.length;for(;n>0&&e.length-n<500&&!t.has(e[n-1]);)n--;return e.slice(n)}(so,e);if(0!==t.length){for(let n of t)e.add(n);it({action:"add-projects",keys:t})}},[it,e2,so,e8,sl,r7]);let sa=r6.projectNames,sd=(0,i.useMemo)(()=>(function(e,t,n){let r=new Set,i=[];for(let s of[...e,...t])r.has(s.key)||(r.add(s.key),i.push(eT(s,n)));return i})(i7.projects,iG,sa),[i7.projects,iG,sa]),sc=(0,i.useMemo)(()=>{if(!e9||!iE)return null;let e=i1&&null!==tk;return{cwd:e9,project:eT(iE,sa),worktrees:e?tk.worktrees.map(e=>{let{path:t,branch:n,isMain:r}=e;return{path:t,branch:n,isMain:r}}):null,currentWorktreePath:e?iA:null,projects:sd}},[e9,iE,i1,tk,iA,sd,sa]),su=(0,i.useRef)(sc);su.current=sc;let sp=sc?JSON.stringify([sc.cwd,sc.project.key,sc.project.root,sc.project.alias??null,sc.currentWorktreePath,sc.worktrees?.map(e=>[e.path,e.branch,e.isMain])??null,sc.projects.map(e=>[e.key,e.root,e.alias??null])]):"";(0,i.useEffect)(()=>{C?.(su.current)},[sp,C]);let sh=(0,i.useRef)(i3);(0,i.useLayoutEffect)(()=>{let e=sh.current;if(sh.current=i3,null===e||e===i3)return;let t=si.get(e);n1(e=>!t||t.current||t.pinned||e.has(t.key)||Object.hasOwn(nX,t.key)?e:new Set(e).add(t.key))},[i3,nX,si]);let sm=(0,i.useCallback)((e,t)=>{nQ(e),eb(e),n1(e=>(function(e,t){if(0===e.size)return e;if(null===t)return new Set;if(!t.some(t=>e.has(t)))return e;let n=new Set(e);for(let e of t)n.delete(e);return n})(e,t)),n4(n=>(function(e,t,n){let r=(n??Object.keys(t)).filter(n=>!1===t[n]&&Object.hasOwn(e,n));if(0===r.length)return e;let i={...e};for(let e of r)delete i[e];return i})(n,e,t))},[]),sf=(0,i.useCallback)(()=>(nJ.current?.hidden?nV:nW).current??il.current,[]),sg=(0,i.useCallback)(e=>{let t=nJ.current;for(let n of["pinned","group","archive"]){let r=CSS.escape(`session:${n}:${e}`),i=t?.querySelector(`[data-row-key="${r}"] .session-tree-main`);if(i&&i.getClientRects().length>0)return i}return sf()},[sf]),sx=(0,i.useCallback)(e=>{let t=CSS.escape(`group:${e}`),n=nJ.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);return n&&n.getClientRects().length>0?n:sf()},[sf]),sv=(0,i.useCallback)(async e=>{let t=await it(e);return t||rJ(e=>e+1),t},[it]);(0,i.useEffect)(()=>{rZ!==rG.current&&(rG.current=rZ,rV(eJ("sidebar.uiStateFailed",{error:ie??""})))},[rZ,ie,rV,eJ]);let sb=(0,i.useCallback)((e,t,n)=>{let r=si.get(e),i=si.get(t);r&&i&&r!==i&&r.pinned===i.pinned&&(sv({action:"move-project",projectKey:e,anchorKey:t,position:n,add:i7.unorderedKeysByBand[r.pinned?"pinned":"other"].slice(-500)}),rO.current+=1,rW({id:rO.current,at:Date.now(),rowKey:`group:${e}`}))},[sv,i7.unorderedKeysByBand,si]),sy=(0,i.useCallback)(e=>{nm||(ng(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ex();if(t)try{t.setItem(el,e)}catch{}}(e))},[nm]),sj=(0,i.useCallback)(e=>{e!==ro.current&&rt(e?"out":"in"),nz(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ex();if(t)try{t.setItem(eh,String(e))}catch{}}(e)},[rt]),sk=(0,i.useCallback)(e=>{let t=e.target;t instanceof Element&&nY.current.set(t,t.scrollTop)},[]);(0,i.useLayoutEffect)(()=>{for(let e of[nJ.current,nG.current])if(e&&!e.hidden)for(let t of e.querySelectorAll(".session-tree-scroll, .sidebar-files-scroll")){let e=nY.current.get(t);void 0!==e&&t.scrollTop!==e&&(t.scrollTop=e)}},[nf,n9,nm,nS]);let sw=(0,i.useCallback)(e=>{if(rz(null),rd(!0),tW(!1),sy("sessions"),void 0!==e){if(n5.includes(e)){let t=n5.filter(t=>t!==e);n6(t),ey(t)}rO.current+=1,rB({id:rO.current,at:Date.now(),rowKey:`archive:${e}`,block:"start"})}},[n5,rd,sy]),sS=(0,i.useRef)(null),sC=(0,i.useRef)(n9),sN=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(sC.current===n9)return;if(sC.current=n9,n9)return void r$(sS.current);let e=nJ.current?.querySelector('[data-row-key="footer-archived"] button'),t=e&&e.getClientRects().length>0?e:sf();r$(t),t&&document.activeElement===t&&(sN.current=t)},[n9,sf]);let sE=(0,i.useRef)(null),sI=(0,i.useRef)(nm);(0,i.useLayoutEffect)(()=>{if(sI.current===nm)return;sI.current=nm;let e=sE.current;e&&(!e.isConnected||0===e.getClientRects().length)&&r$(sf())},[nm,sf]);let s$=e=>{if("ArrowLeft"!==e.key&&"ArrowRight"!==e.key&&"Home"!==e.key&&"End"!==e.key)return;e.preventDefault();let t="Home"===e.key?"sessions":"End"===e.key||"sessions"===nf?"files":"sessions";sy(t),("sessions"===t?nW:nV).current?.focus()},sT=(0,i.useCallback)((e,t)=>{sv({action:"set",ids:[e.root.id],pinned:t})},[sv]),sM=(0,i.useCallback)((e,t)=>{nt(n=>{let r=new Set(n);if(t)for(let t of H(e))r.delete(t);else r.add(e.root.id);return r})},[]),sR=(0,i.useCallback)(e=>{0!==e.length&&nt(t=>{let n=new Set(t);for(let t of e)t!==r_.current&&n.add(t);return n.size===t.size?t:n})},[]),sA=(0,i.useCallback)(e=>{let t=e.filter(e=>!e.root.transient);if(0===t.length)return;let n=ir(t.map(e=>e.root.id)),r=t.flatMap(e=>H(e)),i=r.filter(e=>ne.has(e));for(let e of P(t))sv({action:"set",ids:e.map(e=>e.root.id),archived:!0}).then(t=>{if(t||0===i.length)return;let n=new Set(e.flatMap(e=>H(e)));sR(i.filter(e=>n.has(e)))});i.length>0&&nt(e=>{let t=new Set(e);for(let e of r)t.delete(e);return t}),rV(1===t.length?eJ("sidebar.archivedToast",{title:rI(nq(t[0].root),28)}):eJ("sidebar.archivedManyToast",{count:t.length}),[{id:"undo",label:eJ("sidebar.undo"),onClick:()=>{for(let e of P(n))sv({action:"restore",entries:e});sR(i),r5(()=>sg(t[0].root.id))}},{id:"view",label:eJ("sidebar.viewArchive"),onClick:()=>sw()}])},[sv,r5,sg,sw,sR,rV,ir,eJ,ne]),sL=(0,i.useCallback)(e=>{H(e).some(e=>t8.has(e))||sA([e])},[sA,t8]),sz=(0,i.useCallback)(e=>{if(0===e.length)return;let t=e.map(e=>e.root.id),n=ir(t);for(let e of P(t))sv({action:"set",ids:e,archived:!1});rV(1===e.length?eJ("sidebar.restoredToast",{title:rI(nq(e[0].root),28)}):eJ("sidebar.restoredManyToast",{count:e.length}),[{id:"undo",label:eJ("sidebar.undo"),onClick:()=>{for(let e of P(n))sv({action:"restore",entries:e});r5(()=>sg(e[0].root.id))}}])},[sv,sg,r5,rV,ir,eJ]),sP=(0,i.useCallback)(e=>sz([e]),[sz]),sW=(0,i.useCallback)(e=>{e.root.transient||(rA(null),rg(e.root.id))},[]),sO=(0,i.useCallback)(async(e,t)=>{let n=e.root,r=nq(n),i=t.trim();if(rg(e=>e===n.id?null:e),t!==r&&i!==(n.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(n.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:i})}),iv()}catch{}},[iv]),sF=(0,i.useCallback)(e=>{rM(e.key)},[]),sD=(0,i.useCallback)(e=>{rM(t=>t===e?null:t),r5(()=>sx(e))},[r5,sx]),sB=(0,i.useCallback)((e,t)=>{sD(e.key);let n=function(e,t){let n=t.trim();if(n===e.name)return null;let r=""===n||n===q(e.root);return r&&null===e.customName?null:{action:"rename-project",projectKey:e.key,name:r?null:n}}(e,t);n&&sv(n)},[sv,sD]),sH=(0,i.useCallback)(async e=>{let t=e.root;if(!t.transient){rA(e=>e===t.id?null:e);try{await fetch(`/api/sessions/${encodeURIComponent(t.id)}`,{method:"DELETE"}),eN?.(t.id),iv()}catch{}}},[iv,eN]),s_=(0,i.useCallback)((e,t)=>{t?sH(e):(rg(null),rA(e.root.id))},[sH]),sU=(e,t)=>{if(sN.current=null,n9){let e=nJ.current?.querySelector(".sidebar-sessions-view .session-tree-scroll");e&&nY.current.delete(e),rd(!1)}let n=g(e);if(Object.hasOwn(i9,n)&&!1===i9[n]){let e={...nX};delete e[n],e[n]=!0,sm(e,[n])}iq(e,void 0,void 0,{keepSidebarOpen:null!==t}),iv();let r=t?`[data-row-key="${CSS.escape(t)}"]`:null;rO.current+=1,rW({id:rO.current,at:Date.now(),rowKey:`session:group:${e.id}`,takeFocusFrom:e=>null!==r&&null!==e.closest(r)||e===sN.current})},sK=(0,i.useRef)(sU);sK.current=sU;let sq=(0,i.useRef)(new Set),sV=(0,i.useCallback)(async e=>{let t=e.family.root;if(t.transient||sq.current.has(t.id))return;sq.current.add(t.id);let n=r_.current;try{var r;let i,s,o=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),l=await o.json().catch(()=>({}));if(!o.ok||!l.session){let{key:e,params:t}=function(e,t){switch(e){case"not_found":return{key:"sidebar.forkNotFound"};case"unsaved":return{key:"sidebar.forkUnsaved"};case"empty":return{key:"sidebar.forkEmpty"};case"subagent":case"request-denied":return{key:"sidebar.forkUnavailable"};default:return{key:"sidebar.forkFailed",params:{error:t}}}}(l.code,l.error??`HTTP ${o.status}`);rV(eJ(e,t)),"not_found"===l.code&&iv();return}let a=l.session,d=nq(a),{head:c,tail:u}=(r=eJ("sidebar.forkedToast",{title:d}),((s=(i=eE(d)?.suffix)?r.lastIndexOf(i):-1)>0?{head:r.slice(0,s),tail:r.slice(s)}:null)??{head:eJ("sidebar.forkedToast",{title:rI(d,28)}),tail:void 0});if(r_.current!==n){eQ(e=>e.some(e=>e.id===a.id)?e:[a,...e]),nt(e=>new Set(e).add(a.id)),iv(),rV(c,[{id:"open",label:eJ("sidebar.open"),onClick:()=>sK.current(a,null)}],u);return}sK.current(a,e.key),rV(c,[],u)}catch(e){rV(eJ("sidebar.forkFailed",{error:e instanceof Error?e.message:String(e)}))}finally{sq.current.delete(t.id)}},[iv,rV,eJ]),sZ=(0,i.useRef)(new Set),[sJ,sG]=(0,i.useState)(()=>new Set),sY=(0,i.useCallback)(async e=>{let t=e.family.root;if(t.transient||sZ.current.has(t.id))return;sZ.current.add(t.id),sG(new Set(sZ.current)),rV(eJ("title.generating"));let n=await ek(t.id,fetch);(sZ.current.delete(t.id),sG(new Set(sZ.current)),"error"in n)?rV(eJ("title.failedWithError",{error:n.error})):(eQ(e=>e.map(e=>e.id===t.id?{...e,name:n.title}:e)),iv(),rV(eJ("title.updated")))},[iv,rV,eJ]),sX=(0,i.useCallback)(e=>{e.root.transient||window.open(u(e.root.id),"_blank","noopener,noreferrer")},[]),sQ=(0,i.useCallback)((e,t,n)=>{e.status.transient||rz({kind:"row",row:e,anchor:t,opener:n})},[]),s0=(0,i.useCallback)((e,t)=>{let n=e.family.root;if(n.id===rp||n.id===rR)return;if(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:window,n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)}({id:n.id,path:n.path,cwd:n.cwd,name:n.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{iv()}})){t.preventDefault(),t.stopPropagation();return}if(n.transient)return;t.preventDefault();let r=t.currentTarget instanceof HTMLElement?t.currentTarget:null,i=0===t.clientX&&0===t.clientY&&r?rT(r,"start"):{kind:"point",x:t.clientX,y:t.clientY},s=document.activeElement,o=s instanceof HTMLElement&&null!==r&&r.contains(s);r0.current=!o&&s instanceof HTMLElement&&s!==document.body?s:null,sQ(e,i,o?s:null)},[rR,iv,sQ,rp]),s1=(0,i.useMemo)(()=>({sessions:eY,uiState:r6,runningIds:t8,awaitingIds:t5,unreadIds:ne,selectedSessionId:y}),[eY,r6,t8,t5,ne,y]),s2=(0,i.useCallback)((e,t)=>{let n=er(s1,e.key,6048e5,Date.now()).length;rz({kind:"group",project:e,olderCount:n,anchor:rT(t,"end"),opener:t})},[s1]),s4=(0,i.useCallback)(e=>{sA(er(s1,e.key,6048e5,Date.now()).flatMap(e=>{let t=iX.get(e);return t?[t]:[]}))},[sA,iX,s1]),s8=(0,i.useCallback)((e,t)=>{rz(n=>n?.kind==="group"&&n.project.key===e?{...n,askDelete:t}:n)},[]),s3=(0,i.useCallback)((e,t)=>{rz(n=>n?.kind==="group"&&n.project.key===e?{...n,askRemove:t}:n)},[]),s5=(0,i.useRef)(new Set),s6=(0,i.useCallback)(async(e,t,n)=>{if(rz(null),!(0===t.length||s5.current.has(e))){s5.current.add(e),rV(eJ("sidebar.deletingSessions"));try{let e=await ew(t,fetch);for(let t of e.deleted)eN?.(t);if(iv().then(()=>r5(n)),null!==e.error)return void rV(eJ("sidebar.deleteFailed",{error:e.error}));let r=e.deletedRoots.length,i=[1===r?eJ("sidebar.deletedOneToast"):eJ("sidebar.deletedManyToast",{count:r})];e.running.length>0&&i.push(eJ("sidebar.keptRunningToast",{count:e.running.length})),rV(i.join(" \xb7 "))}finally{s5.current.delete(e)}}},[r5,iv,eN,rV,eJ]),s9=(0,i.useCallback)(e=>{let{ids:t}=ei(s1,e.key);s6(`project:${e.key}`,t,()=>sx(e.key))},[s6,sx,s1]),s7=(0,i.useCallback)(e=>{let t=null===e?null:CSS.escape(`archive:${e}`),n=null===t?null:nJ.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);if(n&&n.getClientRects().length>0)return n;let r=sS.current;return r&&r.getClientRects().length>0?r:sf()},[sf]),oe=(0,i.useCallback)(e=>e.flatMap(e=>{let t=iX.get(e);return t?[t]:[]}),[iX]),ot=(0,i.useCallback)((e,t)=>{if(rz(null),e.pinned&&sv({action:"pin-project",projectKey:e.key,root:e.root,pinned:!1}),null!==e.customName&&sv({action:"rename-project",projectKey:e.key,name:null}),e.current){let t=i7.projects.findIndex(t=>t.key===e.key),n=i7.projects[t+1]??i7.projects[t-1];iC.current=void 0===n,e7(n?.root??null)}let{ids:n,running:r}=ei(s1,e.key);if(t&&n.length>0)return void s6(`project:${e.key}`,n,()=>sx(e.key));let i=t?[]:oe(function(e,t){let n=[];for(let r of d(e.sessions))!(G(r)!==t||r.root.transient||U(r,e.uiState,e.runningIds))&&(_(r,e.runningIds)||n.push(r.root.id));return n}(s1,e.key));if(i.length>0)sA(i);else{let t=[eJ("sidebar.workspaceDeletedToast",{name:rI(e.name,28)})];r>0&&t.push(eJ("sidebar.keptRunningToast",{count:r})),rV(t.join(" \xb7 "))}r5(()=>sx(e.key))},[sv,sA,s6,oe,r5,sx,i7.projects,rV,eJ,s1]),on=(0,i.useCallback)((e,t)=>{rz({kind:"archive-group",project:e,anchor:rT(t,"end"),opener:t})},[]),or=(0,i.useCallback)(e=>{rz(t=>t?.kind==="archive"?null:{kind:"archive",anchor:rT(e,"end"),opener:e})},[]),oi=(0,i.useCallback)(e=>{rz(t=>t?.kind==="archive"?{...t,askDelete:e}:t?.kind==="archive-group"?{...t,askDelete:void 0!==e}:t)},[]),os=(0,i.useCallback)(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];for(let r of d(e.sessions))if((void 0===t.projectKey||G(r)===t.projectKey)&&U(r,e.uiState,e.runningIds)){if(void 0!==t.archivedBefore){let n=D(F(e.uiState,r.root.id)?.archivedAt);if(null===n||n>=t.archivedBefore)continue}n.push(r.root.id)}return n})(s1,"all"===e?{}:"old"===e?{archivedBefore:Date.now()-2592e6}:e),[s1]),oo=(0,i.useCallback)(e=>{let t=os(e);s6("string"==typeof e?`archive:${e}`:`archive-project:${e.projectKey}`,t,()=>"string"==typeof e?s7(null):s7(e.projectKey))},[os,s7,s6]),ol=(0,i.useCallback)(e=>{n6(e),ey(e)},[]),oa=(0,i.useCallback)(e=>{let t=sr.map(e=>e.project.key),n=n5.filter(e=>!t.includes(e));ol(e?n:[...n,...t])},[n5,sr,ol]),od=(0,i.useCallback)((e,t)=>{let n=n5.includes(e);if(t)return void oa(n);let r=n5.filter(t=>t!==e);ol(n?r:[...r,e])},[n5,ol,oa]),oc=(0,i.useCallback)(e=>{rz(null),iV(eI(e,e9))},[e9,iV]),ou=(0,i.useCallback)(()=>rz(null),[]);(0,i.useEffect)(()=>{if(null!==rL)return;let e=r0.current;if(r0.current=null,!e?.isConnected)return;let t=document.activeElement;t&&t!==document.body||e.focus({preventScroll:!0})},[rL]);let op=n9?sn:i7.rows;(0,i.useEffect)(()=>{rL?.kind!=="row"||op.some(e=>e.key===rL.row.key)||rz(null),rL?.kind!=="archive-group"||op.some(e=>e.key===`archive:${rL.project.key}`)||rz(null)},[rL,op]);let oh=rL?.kind==="row"?op.find(e=>"session"===e.kind&&e.key===rL.row.key)??rL.row:null,om=(0,i.useCallback)(e=>{iq(e.root)},[iq]),of=(0,i.useCallback)(e=>{let t={...nX};for(let n of i7.projects)delete t[n.key],t[n.key]=e(n);sm(t,null)},[nX,i7.projects,sm]),og=(0,i.useCallback)((e,t)=>{let n=si.get(e);if(!n)return;let r=!V(n,i9);if(t)return void of(()=>r);let i={...nX};delete i[e],i[e]=r,sm(i,[e])},[nX,si,sm,of,i9]),ox=(0,i.useCallback)(e=>{let t=i7.rows.find(t=>"group-more"===t.kind&&t.projectKey===e||"pinned-more"===t.kind&&e===O);(t?.kind==="group-more"||t?.kind==="pinned-more")&&n4(n=>{var r;return r=t.nextShown,{...n,[e]:Math.max(ee(n,e),Math.floor(r))}})},[i7.rows]),ov=(0,i.useCallback)(e=>{n4(t=>et(t,e))},[]),ob=(0,i.useCallback)(e=>{rY.current=e,rQ(e=>e+1),nm?sj(!1):sy("files")},[sj,nm,sy]),oy=nm?rc.open:"files"===nf;(0,i.useEffect)(()=>{let e=rY.current;e&&oy&&(rY.current=null,"project-list"===e?tv.current?.openMenu("project"):"file-search"===e?document.getElementById("file-search-input")?.focus({preventScroll:!0}):tv.current?.button("project")?.focus({preventScroll:!0}))},[oy,rX]);let oj=e=>{let{heading:t,headingTitle:n,notes:i,count:s,onConfirm:o,onCancel:l}=e;return(0,r.jsxs)("div",{className:"sidebar-menu-question",children:[(0,r.jsx)("div",{className:"sidebar-menu-header",title:n,children:t}),i.map(e=>(0,r.jsx)("p",{className:"sidebar-menu-question-text",children:e},e)),(0,r.jsxs)("div",{className:"sidebar-menu-question-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-confirm",disabled:0===s,onClick:o,children:eJ("sidebar.deleteCount",{count:s})}),!eG&&(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-cancel","data-sidebar-menu-autofocus":"",onClick:l,children:eJ("sidebar.cancel")})]})]})},ok=(e,t)=>oj({heading:t?eJ("sidebar.deleteArchivedInProjectHeading",{name:t.name}):eJ("old"===e?"sidebar.deleteOldArchivedHeading":"sidebar.deleteAllArchivedHeading"),headingTitle:t?.root,notes:[eJ("sidebar.deleteArchivedMessage")],count:os(e).length,onConfirm:()=>oo(e),onCancel:()=>oi(void 0)}),ow="",oS=null;if(rL?.kind==="row"&&oh)m=nq(oh.family.root),ow=eJ("sidebar.sessionActions"),v=(function(e,t){if(t.transient)return[];let n={kind:"action",id:"open-new-tab",shortcut:"T"};return"archive"===e?[{kind:"action",id:"unarchive",shortcut:"A"},{kind:"action",id:"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"generate-title",shortcut:"G"},{kind:"action",id:"fork",shortcut:"F"},{kind:"action",id:"share",shortcut:"S"},{kind:"action",id:"export",shortcut:"E"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]:[{kind:"action",id:"pinned"===e?"unpin":"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"generate-title",shortcut:"G"},{kind:"action",id:"fork",shortcut:"F"},{kind:"action",id:"share",shortcut:"S"},{kind:"action",id:"export",shortcut:"E"},{kind:"action",id:t.unread?"mark-read":"mark-unread",shortcut:"U"},t.running?{kind:"action",id:"archive",shortcut:"A",disabledReason:"running"}:{kind:"action",id:"archive",shortcut:"A"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]})(oh.context,oh.status).map((e,t)=>{if("separator"===e.kind)return{type:"separator",id:`separator-${t}`};let n=eJ(rw[e.id]),i="generate-title"===e.id&&sJ.has(oh.family.root.id),s="generate-title"===e.id&&!oh.family.root.detailsPending&&0===oh.family.root.messageCount;return{type:"item",id:e.id,label:i?eJ("title.generating"):"delete"===e.id?`${n}…`:n,icon:i?(0,r.jsx)(nK,{}):function(e){switch(e){case"open-new-tab":return(0,r.jsx)(nI,{});case"pin":return(0,r.jsx)(nj,{});case"unpin":return(0,r.jsx)(nk,{});case"rename":return(0,r.jsx)(nT,{});case"generate-title":return(0,r.jsx)(nM,{});case"fork":return(0,r.jsx)(nC,{});case"share":return(0,r.jsx)(nN,{});case"export":return(0,r.jsx)(nE,{});case"mark-read":return(0,r.jsx)(nA,{});case"mark-unread":return(0,r.jsx)(nR,{});case"archive":return(0,r.jsx)(nb,{});case"unarchive":return(0,r.jsx)(ny,{});case"delete":return(0,r.jsx)(n$,{})}}(e.id),shortcut:e.shortcut,danger:"delete"===e.id,disabled:void 0!==e.disabledReason||i||s,disabledReason:"running"===e.disabledReason?eJ("sidebar.cannotArchiveRunning"):void 0,title:s?eJ("title.noMessages"):void 0,onSelect:t=>{let{shiftKey:n}=t;return((e,t,n)=>{let{family:r}=t;switch(e){case"open-new-tab":sX(r);break;case"pin":sT(r,!0);break;case"unpin":sT(r,!1);break;case"rename":sW(r);break;case"generate-title":sY(t);break;case"fork":sV(t);break;case"share":tB(r.root);break;case"export":t_(r.root);break;case"mark-read":sM(r,!0);break;case"mark-unread":sM(r,!1);break;case"archive":sL(r);break;case"unarchive":sP(r);break;case"delete":s_(r,n)}})(e.id,oh,n)}}});else if(rL?.kind==="group"){let e,t,i,o,l,a=si.get(rL.project.key)??rL.project;m=a.name,ow=eJ("sidebar.projectActions",{name:a.name}),n=a,s=rL.olderCount,e=iQ.countByProject.get(n.key)??0,t=ei(s1,n.key),i=es(i7.projects,n.key,"up"),o=es(i7.projects,n.key,"down"),l=(null===n.customName?["rename-project"]:["rename-project","reset-project-name"]).map(e=>"rename-project"===e?{type:"item",id:e,label:eJ("sidebar.renameProject"),icon:(0,r.jsx)(nT,{}),onSelect:()=>sF(n)}:{type:"item",id:e,label:eJ("sidebar.resetProjectName"),icon:(0,r.jsx)(ny,{}),onSelect:()=>{sv({action:"rename-project",projectKey:n.key,name:null})}}),v=[{type:"item",id:"pin-project",label:eJ(n.pinned?"sidebar.unpinProject":"sidebar.pinProject"),icon:n.pinned?(0,r.jsx)(nk,{}):(0,r.jsx)(nj,{}),onSelect:()=>{sv({action:"pin-project",projectKey:n.key,root:n.root,pinned:!n.pinned})}},...l,{type:"item",id:"open-in-files",label:eJ("sidebar.openInFilesTab"),icon:(0,r.jsx)(nP,{}),onSelect:()=>{n.current||e7(n.root),ob("project-button")}},{type:"item",id:"open-new-tab",label:eJ("sidebar.openInNewTab"),icon:(0,r.jsx)(nI,{}),shortcut:"T",onSelect:()=>(e=>{let{cwd:t}=eI(e,e9);window.open(`?cwd=${encodeURIComponent(t)}`,"_blank","noopener,noreferrer")})(n)},{type:"separator",id:"separator-layout"},{type:"item",id:"move-up",label:eJ("sidebar.moveProjectUp"),icon:(0,r.jsx)(nw,{className:"sidebar-icon-up"}),disabled:null===i,onSelect:()=>{i&&sb(n.key,i.anchorKey,i.position)}},{type:"item",id:"move-down",label:eJ("sidebar.moveProjectDown"),icon:(0,r.jsx)(nw,{className:"sidebar-icon-down"}),disabled:null===o,onSelect:()=>{o&&sb(n.key,o.anchorKey,o.position)}},{type:"item",id:"collapse-others",label:eJ("sidebar.collapseOtherGroups"),icon:(0,r.jsx)(nw,{}),disabled:i7.projects.every(e=>V(e,i9)===(e.key===n.key)),onSelect:()=>of(e=>e.key===n.key)},{type:"item",id:"expand-all",label:eJ("sidebar.expandAllGroups"),icon:(0,r.jsx)(nw,{className:"sidebar-icon-down"}),disabled:i7.projects.every(e=>V(e,i9)),onSelect:()=>of(()=>!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"import-session",label:eJ("sidebar.importSession"),icon:(0,r.jsx)(nD,{}),onSelect:()=>tK(n.root)},{type:"item",id:"archive-older",label:eJ("sidebar.archiveOlderThanWeek",{count:s}),icon:(0,r.jsx)(nb,{}),disabled:0===s,onSelect:()=>s4(n)},{type:"item",id:"view-archived",label:eJ("sidebar.viewArchived",{count:e}),icon:(0,r.jsx)(nb,{}),disabled:0===e,onSelect:()=>sw(n.key)},{type:"item",id:"delete-all",label:eJ("sidebar.deleteProjectSessions",{count:t.ids.length}),icon:(0,r.jsx)(n$,{}),danger:!0,disabled:0===t.ids.length,onSelect:e=>{let{keepOpen:t}=e;t(),s8(n.key,!0)}},{type:"separator",id:"separator-workspace"},{type:"item",id:"delete-workspace",label:eJ("sidebar.deleteWorkspace"),icon:(0,r.jsx)(n$,{}),danger:!0,onSelect:e=>{let{keepOpen:t}=e;t(),s3(n.key,!0)}}],rL.askDelete?oS=(e=>{let{ids:t,running:n}=ei(s1,e.key);return oj({heading:eJ("sidebar.deleteProjectSessionsHeading",{name:e.name}),headingTitle:e.root,notes:[eJ("sidebar.deleteProjectSessionsMessage"),...n>0?[eJ("sidebar.deleteProjectSessionsRunning",{count:n})]:[]],count:t.length,onConfirm:()=>s9(e),onCancel:()=>s8(e.key,!1)})})(a):rL.askRemove&&(oS=(e=>{let{ids:t,running:n}=ei(s1,e.key);return(0,r.jsxs)("div",{className:"sidebar-menu-question",children:[(0,r.jsx)("div",{className:"sidebar-menu-header",title:e.root,children:eJ("sidebar.deleteWorkspaceHeading",{name:e.name})}),(0,r.jsx)("p",{className:"sidebar-menu-question-text",children:eJ("sidebar.deleteWorkspaceMessage")}),t.length>0&&(0,r.jsx)("p",{className:"sidebar-menu-question-text",children:eJ("sidebar.deleteWorkspaceSessions")}),n>0&&(0,r.jsx)("p",{className:"sidebar-menu-question-text",children:eJ("sidebar.deleteProjectSessionsRunning",{count:n})}),(0,r.jsxs)("div",{className:"sidebar-menu-question-buttons is-stacked",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-keep",onClick:()=>ot(e,!1),children:eJ(t.length>0?"sidebar.deleteWorkspaceKeep":"sidebar.deleteWorkspaceOnly")}),t.length>0&&(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-confirm",onClick:()=>ot(e,!0),children:eJ("sidebar.deleteWorkspaceAndSessions",{count:t.length})}),!eG&&(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-cancel","data-sidebar-menu-autofocus":"",onClick:()=>s3(e.key,!1),children:eJ("sidebar.cancel")})]})]})})(a)),f=264}else if(rL?.kind==="archive-group"){let e,t=sr.find(e=>e.project.key===rL.project.key)?.project??rL.project;m=t.name,ow=eJ("sidebar.archivedProjectActions",{name:t.name}),v=[{type:"item",id:"restore-all",label:eJ("sidebar.restoreAllArchived",{count:(e=os({projectKey:t.key})).length}),icon:(0,r.jsx)(ny,{}),disabled:0===e.length,onSelect:()=>sz(oe(e))},{type:"separator",id:"separator-delete"},{type:"item",id:"delete-all",label:eJ("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(n$,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),oi("all")}}],rL.askDelete&&(oS=ok({projectKey:t.key},t)),f=248}else if(rL?.kind==="archive"){let e,t,n;m=eJ("sidebar.archived"),ow=eJ("sidebar.archiveActions"),e=os("all"),t=os("old"),n=sr.filter(e=>!e.expanded).length,v=[{type:"item",id:"collapse-all",label:eJ("sidebar.collapseAllGroups"),icon:(0,r.jsx)(nw,{}),disabled:n===sr.length,onSelect:()=>oa(!1)},{type:"item",id:"expand-all",label:eJ("sidebar.expandAllGroups"),icon:(0,r.jsx)(nw,{className:"sidebar-icon-down"}),disabled:0===n,onSelect:()=>oa(!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"restore-all",label:eJ("sidebar.restoreAllArchived",{count:e.length}),icon:(0,r.jsx)(ny,{}),disabled:0===e.length,onSelect:()=>sz(oe(e))},{type:"item",id:"delete-old",label:eJ("sidebar.deleteOldArchived",{count:t.length}),icon:(0,r.jsx)(n$,{}),danger:!0,disabled:0===t.length,onSelect:e=>{let{keepOpen:t}=e;t(),oi("old")}},{type:"item",id:"delete-all",label:eJ("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(n$,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),oi("all")}}],rL.askDelete&&(oS=ok(rL.askDelete,null)),f=280}let oC={layout:eG?"mobile":"desktop",loading:e2||!r9,error:e5,renamingRootId:rp,renamingProjectKey:rx,confirmDeleteRootId:rR,activeMenuRowKey:rL?.kind==="row"?rL.row.key:rL?.kind==="group"?`group:${rL.project.key}`:rL?.kind==="archive-group"?`archive:${rL.project.key}`:null,onSelectFamily:om,onToggleGroup:og,onShowMore:ox,onShowLess:ov,onTogglePinned:()=>{let e=!n8;n3(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ex();if(t)try{t.setItem(eu,String(e))}catch{}}(e),e&&n4(e=>et(e,O))},onArchiveFamily:sL,onRestoreFamily:sP,onOpenRowMenu:sQ,onRowContextMenu:s0,onRenameCommit:(e,t)=>{sO(e,t)},onRenameCancel:()=>rg(null),onRenameProjectCommit:sB,onRenameProjectCancel:()=>{rx&&sD(rx)},onDeleteConfirm:e=>{sH(e)},onDeleteCancel:()=>{rA(null),rR&&r5(()=>sg(rR))},onGroupNew:oc,onGroupMenu:s2,onPinEmptyGroup:e=>{sv({action:"pin-project",projectKey:e.key,root:e.root,pinned:!0}),r5(()=>sx(e.key))},onToggleArchiveGroup:od,onArchiveGroupMenu:on,onOpenOtherProject:()=>{ob("project-list")},onOpenArchive:()=>sw(),onMoveGroup:sb},oN=e9??e$??null,oE=oN&&tq>0?eJ("sidebar.changedFiles",{count:tq}):void 0,oI=(0,i.useRef)(null),o$=!oN||0===tq;(0,i.useLayoutEffect)(()=>{let e=oI.current;if(o$&&e&&sE.current===e){var t,n;let r;t=document,n=sf(),(r=function(e){let t=e=>e?.tagName==="BUTTON"&&!e.disabled;for(let n=e.nextElementSibling;n;n=n.nextElementSibling)if(t(n))return n;for(let n=e.previousElementSibling;n;n=n.previousElementSibling)if(t(n))return n;return null}(e)??n)&&t.activeElement===e?r.focus({preventScroll:!0}):eB(t,r)}},[o$,sf]);let oT=nm||"sessions"===nf,oM=!nm&&"files"===nf&&null!==oN,oR=(t=(nm?["below",eJ("sidebar.new")]:["tabs",eJ("sidebar.tabSessions"),eJ("sidebar.tabFiles"),eJ("sidebar.new"),oN&&tq>0?tq:"",nf]).join("\n"),h=(0,i.useCallback)(()=>{let e=is.current;if(e){for(let t of["0","1","2"])if(e.dataset.fit=t,e.scrollWidth<=e.clientWidth)return}},[is]),(0,i.useLayoutEffect)(()=>{let e=is.current;if(!e)return;h();let t=new ResizeObserver(h);return t.observe(e),()=>t.disconnect()},[is,h,t]),h),oA=i7.archivedCount,oL=nm?13:14,oz=(0,r.jsx)(ry,{onClick:()=>{oN&&ez?.(oN)},disabled:!oN||!ez,title:eJ("terminal.open"),children:(0,r.jsx)(nO,{size:oL})}),oP=(0,r.jsx)(ry,{onClick:()=>{iy().then(e=>{e&&nm&&sj(!1)})},disabled:!oN||ik,title:ik?eJ(t0?.reason==="remote"?"sidebar.openInExplorerRemoteOnly":"sidebar.openInExplorerUnsupported"):ij,children:(0,r.jsx)(nP,{size:oL})}),oW=(0,r.jsx)(ry,{onClick:()=>{nm&&nS&&sj(!1),np.current?.openUploadPicker()},disabled:!oN||t$,title:eJ("sidebar.uploadFilesTitle"),children:(0,r.jsx)(nD,{size:oL})}),oO=(0,r.jsx)(ry,{onClick:()=>{eD?eD():tI(e=>e+1),tQ(!0),nu.current&&clearTimeout(nu.current),nu.current=setTimeout(()=>tQ(!1),2e3)},disabled:!oN,title:eJ("sidebar.refreshExplorer"),done:tX,children:tX?(0,r.jsx)(nL,{size:oL}):(0,r.jsx)(nB,{size:oL})}),oF=e=>(0,r.jsx)(ry,{onClick:()=>{let e=!tG;tY(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ex();if(t)try{t.setItem(ep,String(e))}catch{}}(e)},disabled:!oN,title:eJ("sidebar.showIgnoredFiles"),pressed:tG,className:e,children:(0,r.jsx)(n_,{size:oL})}),oD=(0,r.jsx)(ry,{ref:oI,onClick:()=>{if(nm&&nS){sj(!1),tJ(!1);return}tJ(e=>!e)},disabled:o$,title:eJ("sidebar.changedFiles",{count:tq}),pressed:!o$&&!tZ,children:(0,r.jsx)(nH,{size:oL})});return(0,r.jsxs)("div",{ref:ig,className:`session-sidebar${nm?" is-files-below":""}${nm&&nS?" is-files-collapsed":""}${nm&&rc.moving?" is-files-folding":""}${rU?" has-toast":""}`,style:{"--sidebar-files-height":`${ih.width}px`},onFocus:e=>{sE.current=e.target},onBlur:e=>{(null!==e.relatedTarget||document.hasFocus())&&(e.currentTarget.contains(e.relatedTarget)||(sE.current=null))},children:[ti&&(0,r.jsx)(tR,{initialPath:to,busy:tc,error:ta,onCancel:()=>iz(ti),onSelect:e=>void iL(e)}),tD&&(0,r.jsx)(rf,{sessionId:tD.id,onClose:()=>tB(null)}),tH&&(0,r.jsx)(tz,{sessionId:tH.id,onExported:e=>{rV(eJ("export.savedTo",{path:e}))},onClose:()=>t_(null)}),null!==tU&&(0,r.jsx)(ns,{cwd:tU,onImported:e=>{tK(null),rV(eJ("import.importedNotice")),iv(),eZ?.(e)},onClose:()=>tK(null)}),(0,r.jsxs)("div",{ref:is,className:"sidebar-header",children:[nm&&(0,r.jsx)(nd,{onWidthChange:oR}),!nm&&(0,r.jsxs)("div",{className:"sidebar-tabs-list",role:"tablist","aria-label":eJ("sidebar.tabsLabel"),children:[(0,r.jsxs)("button",{ref:nW,type:"button",role:"tab",id:"session-sidebar-tab-sessions","aria-selected":"sessions"===nf,"aria-controls":"session-sidebar-panel-sessions",tabIndex:"sessions"===nf?0:-1,className:`sidebar-tab${"sessions"===nf?" is-selected":""}`,onClick:()=>sy("sessions"),onKeyDown:s$,children:[(0,r.jsx)(nU,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eJ("sidebar.tabSessions")})]}),(0,r.jsxs)("button",{ref:nV,type:"button",role:"tab",id:"session-sidebar-tab-files","aria-selected":"files"===nf,"aria-controls":"session-sidebar-panel-files",tabIndex:"files"===nf?0:-1,title:oE,className:`sidebar-tab${"files"===nf?" is-selected":""}`,onClick:()=>sy("files"),onKeyDown:s$,children:[(0,r.jsx)(nP,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eJ("sidebar.tabFiles")}),oN&&tq>0&&(0,r.jsx)("span",{className:"sidebar-tab-count","aria-hidden":"true",children:tq})]})]}),(0,r.jsx)("span",{className:"sidebar-header-spacer"}),(0,r.jsxs)("button",{type:"button",className:"sidebar-new-button",onClick:iJ,disabled:!e9,title:e9?eJ("sidebar.newSessionTitle",{path:e9}):eJ("sidebar.selectProject"),children:[(0,r.jsx)(nx,{size:12}),(0,r.jsx)("span",{className:"sidebar-new-label",children:eJ("sidebar.new")})]}),(0,r.jsx)("button",{ref:il,type:"button",onClick:()=>{if(oM)return void tL(e=>!e);if(!oT){sy("sessions"),tW(!0);return}tW(e=>!e)},title:oM?eJ("sidebar.searchFiles"):eJ("sidebar.toggleSessionSearch"),"aria-label":oM?eJ("sidebar.searchFiles"):eJ("sidebar.toggleSessionSearch"),"aria-expanded":oM?tM:tP,"aria-controls":oM?"file-search-input":"session-search-input",className:`sidebar-search-toggle${(oM?tM:tP)?" is-active":""}`,children:(0,r.jsx)(nF,{size:16})})]}),(0,r.jsxs)("div",{ref:nJ,id:"session-sidebar-panel-sessions",role:nm?"region":"tabpanel","aria-label":nm?eJ("sidebar.tabSessions"):void 0,"aria-labelledby":nm?void 0:"session-sidebar-tab-sessions",hidden:!nm&&"sessions"!==nf,className:"sidebar-panel sidebar-sessions-panel",onScrollCapture:sk,children:[tP&&(0,r.jsx)("div",{className:"sidebar-search",children:(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:tO,maxLength:200,"aria-label":eJ("sidebar.searchSessions"),placeholder:eJ("sidebar.searchSessions"),onChange:e=>tF(e.target.value),onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.stopPropagation(),tF(""))},className:"sidebar-search-input"})}),(0,r.jsx)(rm,{open:tP,query:tO,selectedSessionId:y,onSelectSession:iq,archivedSessionIds:iQ.ids,children:(0,r.jsxs)("div",{className:"sidebar-sessions-views",children:[(0,r.jsx)("div",{className:"sidebar-sessions-view",hidden:ru.mainHidden,inert:ru.mainInert,children:(0,r.jsx)(nZ,{...oC,rows:i7.rows,emptyLabel:eJ("sidebar.noSessions"),reveal:rP,onRevealHandled:rF})}),ru.archiveMounted&&(0,r.jsxs)("div",{className:`sidebar-sessions-view sidebar-archive-view${ru.archiveClass?` ${ru.archiveClass}`:""}`,inert:ru.archiveInert,onAnimationEnd:e=>{e.target===e.currentTarget&&rs()},children:[(0,r.jsxs)("div",{className:"sidebar-archive-bar",children:[(0,r.jsxs)("button",{ref:sS,type:"button",className:"sidebar-archive-back",title:eJ("sidebar.backToSessions"),"aria-label":`${eJ("sidebar.backToSessions")}: ${eJ("sidebar.archivedCount",{count:oA})}`,onClick:()=>rd(!1),children:[(0,r.jsx)(nw,{size:13,className:"sidebar-icon-back"}),(0,r.jsx)("span",{children:eJ("sidebar.archived")}),(0,r.jsxs)("span",{className:"sidebar-archive-count",children:["\xb7 ",oA]})]}),(0,r.jsx)("button",{type:"button",className:`sidebar-archive-menu-button${rL?.kind==="archive"?" is-active":""}`,title:eJ("sidebar.archiveActions"),"aria-label":eJ("sidebar.archiveActions"),"aria-haspopup":"menu","aria-expanded":rL?.kind==="archive",disabled:0===sr.length,onClick:e=>or(e.currentTarget),children:(0,r.jsx)(nv,{size:13})})]}),(0,r.jsx)(nZ,{...oC,rows:sn,emptyLabel:eJ("sidebar.noArchived"),reveal:rD,onRevealHandled:rH})]})]})})]}),nm&&rc.open&&(0,r.jsx)("div",{...ih.separatorProps,"aria-controls":"session-sidebar-panel-files",className:`panel-resize-handle sidebar-files-resize-handle${ih.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-files",title:`${eJ("sidebar.resizeFiles")}: ${eJ("sidebar.resizeFilesHint")}`}),(0,r.jsxs)("div",{ref:nG,id:"session-sidebar-panel-files",role:nm?"region":"tabpanel","aria-label":nm?eJ("sidebar.tabFiles"):void 0,"aria-labelledby":nm?void 0:"session-sidebar-tab-files",hidden:!nm&&"files"!==nf,className:"sidebar-panel sidebar-files-panel",onScrollCapture:sk,onTransitionEnd:e=>{e.target===e.currentTarget&&"height"===e.propertyName&&rn()},children:[nm&&(0,r.jsxs)("div",{className:"sidebar-files-section",children:[(0,r.jsxs)("button",{type:"button",className:"sidebar-files-section-toggle","aria-expanded":!nS,"aria-controls":"session-sidebar-files-body",title:oE,onClick:()=>sj(!nS),children:[(0,r.jsx)(nw,{size:12,strokeWidth:3,className:`session-tree-chevron${nS?"":" is-open"}`}),(0,r.jsx)("span",{className:"sidebar-files-section-label",children:eJ("sidebar.tabFiles")}),oE&&(0,r.jsxs)("span",{className:"sidebar-files-section-count","aria-hidden":"true",children:["\xb7 ",tq]})]}),(0,r.jsxs)("div",{className:"sidebar-files-keys",role:"group","aria-label":eJ("sidebar.fileActions"),children:[oz,oP,oW,oO,oF(),oD,(0,r.jsx)(ry,{onClick:()=>{if(nS){tL(!0),ob("file-search");return}tL(e=>!e)},disabled:!oN,title:eJ("sidebar.searchFiles"),expanded:tM,controls:"file-search-input",children:(0,r.jsx)(nF,{size:13})})]})]}),(0,r.jsxs)("div",{id:"session-sidebar-files-body",className:"sidebar-files-body",hidden:nm&&rc.bodyHidden,inert:nm&&rc.bodyInert,children:[(0,r.jsxs)("div",{className:"sidebar-files-head",children:[(0,r.jsx)(rh,{handleRef:tv,layout:nm?"row":"stacked",context:sc??{project:null,worktrees:null,currentWorktreePath:null,projects:sd},mobile:eG,label:eJ("sidebar.projectAndWorktree"),placeholder:W&&!iS.current?"":eJ("sidebar.selectProject"),homeDir:te,projectActivity:i0,worktreeHint:i8,newWorktreeTitle:eJ("sidebar.createWorktreeTitle"),onPick:iK,onUseDefaultDirectory:()=>{iD()},onOpenFolder:iF,onRefreshWorktrees:iU,onCreateWorktree:iH,onRemoveWorktree:i_}),!nm&&oN&&(0,r.jsxs)("div",{className:"sidebar-files-actions",role:"group","aria-label":eJ("sidebar.fileActions"),children:[ez&&oz,oP,oW,oO,oF("sidebar-files-views-start"),oD]})]}),oN&&iw&&(0,r.jsxs)("div",{role:"alert",className:"sidebar-files-error",children:[(0,r.jsx)("span",{className:"sidebar-files-error-text",children:iw}),(0,r.jsx)(tA,{onClick:()=>t4(null),title:eJ("files.dismissError")})]}),(0,r.jsx)("div",{ref:io,className:"sidebar-files-scroll scrollbar-subtle",children:oN&&(0,r.jsx)(nr,{ref:np,cwd:oN,onOpenFile:eR??(()=>{}),refreshKey:tE,onAtMention:eH,onAtMentions:e_,onUploadBusyChange:tT,changesCollapsed:tZ,onChangesCountChange:tV,fileSearchOpen:tM,onFileSearchOpenChange:tL,showHidden:tG})})]})]}),(0,r.jsx)(rl,{open:null!==rL,anchor:rL?.anchor??null,sheet:eG,ariaLabel:ow,title:m,items:v,cancelLabel:eJ("sidebar.cancel"),focusCancel:null!==oS,onClose:ou,returnFocusTo:rL?.opener??null,width:f,children:oS}),(0,r.jsx)(rv,{toast:rU,onDismiss:()=>rK(null),dismissLabel:eJ("sidebar.dismiss")})]})}var rR=n(5772);let rA=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,rL=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,rz=/\x1B_pi:c\x07/g;function rP(e){return e.replace(rz,"").replace(rA,"")}function rW(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(rL);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let i=String.fromCodePoint(r);t.push({start:n,end:n+i.length,char:i}),n+=i.length}return t}function rO(e,t){let n=rW(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function rF(e){return rW(e)[0]?.char}let rD=/[▀-▟]/,rB={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Home:"\x1b[H",End:"\x1b[F",Insert:"\x1b[2~",Delete:"\x1b[3~",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Escape:"\x1b",Backspace:""},rH={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};function r_(e){return"custom"===e.role&&!e.display}function rU(e){return"user"===e.role||"custom"===e.role&&!r_(e)&&("compaction"===e.customType||"pi-web:subagent-notification"===e.customType||"subagent-notification"===e.customType)}function rK(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function rq(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(e.content??[]).filter(e=>!rK(e,t))}function rV(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function rZ(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!t.isStreaming&&"length"===e.stopReason}function rJ(e){return(e.content??[]).some(e=>"text"===e.type?e.text.trim().length>0:"image"===e.type||"toolCall"===e.type)}function rG(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rq(e,t),r=n.findLastIndex(e=>"text"!==e.type&&"image"!==e.type);return -1===r?{answerBlocks:n,processBlocks:[]}:{answerBlocks:n.slice(r+1),processBlocks:n.slice(0,r+1)}}var rY=n(19870);function rX(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function rQ(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function r0(e){let t=e.toLowerCase();return"apply_patch"===t||t.startsWith("apply_patch_")||t.endsWith(".apply_patch")||t.endsWith("_apply_patch")}function r1(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.input;if("string"==typeof t&&t.length>0)return t}return"string"==typeof t?t:""}function r2(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function r4(e){if(!r2(e)||!r2(e.result))return!1;let t=e.result.failures;return Array.isArray(t)&&t.length>0}function r8(){let e=[],t=[],n=[],r=()=>({lineNo:null,text:"",type:"empty"}),i=()=>{let i=Math.max(t.length,n.length);for(let s=0;s<i;s++)e.push({type:"line",left:t[s]??r(),right:n[s]??r()});t=[],n=[]};return{rows:e,context(t,n){i(),e.push({type:"line",left:{lineNo:n,text:t,type:"context"},right:{lineNo:n,text:t,type:"context"}})},removed(e,n){t.push({lineNo:n,text:e,type:"removed"})},added(e,t){n.push({lineNo:t,text:e,type:"added"})},gap(){i(),e.length>0&&"gap"!==e[e.length-1].type&&e.push({type:"gap",count:null})},finish(){i(),e.length>0&&"gap"===e[e.length-1].type&&e.pop()}}}function r3(e){if(!e.includes("*** Begin Patch")&&!/\*\*\* (?:Add|Delete|Update) File: /.test(e))return null;let t=[],n=null,r=null,i=null;for(let s of e.split(/\r?\n/)){let e=s.match(/^\*\*\* (Add|Delete|Update) File: (.+)$/);if(e){let s=e[1]?.toLowerCase()??"update",o=(e[2]??"").trim();n?.finish(),i=s,r={oldPath:"add"===s?void 0:o,newPath:"delete"===s?void 0:o,rows:(n=r8()).rows},t.push(r);continue}if(/^\*\*\* Move to: /.test(s)){let e=s.replace(/^\*\*\* Move to: /,"").trim();r&&"update"===i&&(r.newPath=e);continue}if(!n||!r)continue;let o=n;if(!s.startsWith("*** ")){if("update"===i&&s.startsWith("@@")){o.gap();continue}if("update"===i){let e=s[0],t=s.slice(1);"+"===e?o.added(t,null):"-"===e?o.removed(t,null):" "===e?o.context(t,null):""!==s&&o.context(s,null)}else if("add"===i){if(""===s)continue;n.added(s.startsWith("+")?s.slice(1):s,null)}else if("delete"===i){if(""===s)continue;n.removed(s.startsWith("-")?s.slice(1):s,null)}}}n?.finish();let s=t.filter(e=>e.rows.length>0);return s.length>0?s:null}function r5(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e.files;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.filePath||"string"!=typeof e.diff)continue;let t=r8();for(let n of e.diff.split(/\r?\n/)){let e=n.match(/^([+\- ])\s*(\d+) (.*)$/);if(!e)continue;let[,r,i,s]=e,o=Number(i);"+"===r?t.added(s,o):"-"===r?t.removed(s,o):t.context(s,o)}t.finish();let r="add"===e.operation,i="delete"===e.operation;n.push({oldPath:r?void 0:e.filePath,newPath:i?void 0:e.movePath??e.filePath,rows:t.rows})}let r=n.filter(e=>e.rows.length>0);return r.length>0?r:null}function r6(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function r9(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function r7(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}function ie(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return n<60?`${n}m ${r}s`:`${Math.floor(n/60)}h ${n%60}m ${r}s`}function it(e){let t=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
4
+
5
+ `}function ir(e){return!e.trim()||e.endsWith("\n\n")?"":e.endsWith("\n")?"\n":"\n\n"}var ii=n(32316),is=n(2849),io=n(8436);function il(e){let{active:t,size:n=14}=e;return(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z",stroke:t?"#d4a017":void 0,fill:t?"rgba(250, 204, 21, 0.18)":"none",style:{filter:t?"drop-shadow(0 0 2px rgba(250, 204, 21, 0.35))":"none"}}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]})}var ia=n(7834);let id=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,ic=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/;function iu(e){let t,n=[],r=null,i=0,s=0,o=0,l=0,a=null,d=[],c=[],u=()=>({lineNo:null,text:"",type:"empty"}),p=()=>{if(!r){d=[],c=[];return}let e=Math.max(d.length,c.length);for(let t=0;t<e;t++){let e=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"removed"}:u(),n=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:u();r.rows.push({type:"line",left:e,right:n})}d=[],c=[]};for(let u of e.split(/\r?\n/)){if(!(o>0||l>0)){if(u.startsWith("--- ")){p(),t=im(u.slice(4));continue}if(u.startsWith("+++ ")){p(),r={oldPath:t,newPath:im(u.slice(4)),rows:[]},n.push(r),a=null;continue}}let e=u.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),p(),i=Number(e[1]),s=Number(e[3]),o=void 0===e[2]?1:Number(e[2]),l=void 0===e[4]?1:Number(e[4]);let t=0===o?i+1:i,d=0===l?s+1:s;if(a){let e=t-a.old,n=d-a.new;(e>0||n>0)&&r.rows.push({type:"gap",count:e===n?e:null})}a={old:t+o,new:d+l},r.rows.push({type:"hunk",text:u});continue}if(!r)continue;if(u.startsWith("\\ ")){p(),r.rows.push({type:"hunk",text:u});continue}let h=u[0],m=u.slice(1);" "===h?(p(),r.rows.push({type:"line",left:{lineNo:i++,text:m,type:"context"},right:{lineNo:s++,text:m,type:"context"}}),o>0&&o--,l>0&&l--):"-"===h?(d.push({lineNo:i++,text:m}),o>0&&o--):"+"===h?(c.push({lineNo:s++,text:m}),l>0&&l--):""!==u&&(p(),r.rows.push({type:"hunk",text:u}))}p();let h=n.filter(e=>e.rows.some(e=>"line"===e.type));return h.length>0?h:null}function ip(e){let t=[];for(let n of e.rows)if("hunk"!==n.type){if("gap"===n.type){t.push(n);continue}if("context"===n.left.type&&"context"===n.right.type){t.push({type:"context",text:n.right.text,oldLineNo:n.left.lineNo,newLineNo:n.right.lineNo});continue}"empty"!==n.left.type&&t.push({type:"removed",text:n.left.text,oldLineNo:n.left.lineNo,newLineNo:null}),"empty"!==n.right.type&&t.push({type:"added",text:n.right.text,oldLineNo:null,newLineNo:n.right.lineNo})}return t}function ih(e,t){return 1===e?t("diff.unchangedLine"):t("diff.unchangedLines",{count:e})}function im(e){return e.split(" ")[0].trim()}let ig=new Set,ix="pi-thinking-expanded",iv="pi-thinking-expanded-changed";function ib(){try{return"true"===window.localStorage.getItem(ix)}catch{return!1}}function iy(e){let{files:t,onOpenFile:n}=e,{t:i}=(0,tn.s)();return 0===t.length?null:(0,r.jsx)("div",{"aria-label":i("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:t.map(e=>{let{filePath:t}=e,s=(0,tH.WP)(t);return(0,r.jsxs)("button",{type:"button",title:t,"aria-label":i("chat.openWrittenFile",{name:s}),onClick:()=>n?.(t),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:6,cursor:"pointer"},children:[tB(s,12),(0,r.jsx)("span",{children:s})]},t)})})}let ij="codemode",ik=new Set(["running","ok","error","cancelled"]);function iw(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function iS(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function iC(e){if(!iw(e)||!Array.isArray(e.calls))return{calls:[],omitted:0};let t=e.calls.flatMap(e=>{let t=function(e){if(!iw(e)||"string"!=typeof e.name)return null;let t="string"==typeof e.status&&ik.has(e.status)?e.status:"ok",n=iS(e.durationMs),r=iS(e.cost);return{id:"string"==typeof e.id?e.id:"",name:e.name,args:"string"==typeof e.args?e.args:"",status:t,...void 0!==n?{durationMs:n}:{},..."string"==typeof e.error&&e.error?{error:e.error}:{},...void 0!==r&&r>0?{cost:r}:{}}}(e);return t?[t]:[]}),n=iS(e.omittedCalls);return{calls:t,omitted:void 0!==n&&n>0?Math.floor(n):0}}let iN=/^Script (completed|failed)\nWall time ([\d.]+) seconds\nOutput:\n$/;function iE(e){return`$${e>=.01?e.toFixed(2):e.toPrecision(2)}`}let iI={running:{icon:"…",color:"#d97706"},ok:{icon:"✓",color:"#16a34a"},error:{icon:"✗",color:"#f87171"},cancelled:{icon:"⊘",color:"var(--text-dim)"}};function i$(e){var t;let{call:n}=e,{t:i}=(0,tn.s)(),s=iI[n.status],o=void 0===(t=n.durationMs)?"":t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(1)}s`;return(0,r.jsxs)("li",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:6,minWidth:0},children:[(0,r.jsx)("span",{role:"img","aria-label":i(`codemode.status.${n.status}`),title:i(`codemode.status.${n.status}`),style:{color:s.color,width:12,flexShrink:0,textAlign:"center"},children:s.icon}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontWeight:600,flexShrink:0},children:n.name}),n.args&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:n.args}),o&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,marginLeft:"auto",fontVariantNumeric:"tabular-nums"},children:o}),void 0!==n.cost&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:iE(n.cost)})]}),n.error&&(0,r.jsx)("div",{style:{color:"#f87171",paddingLeft:18,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n.error})]})}function iT(e){let t,{calls:n,omitted:s,isError:o}=e,{t:l}=(0,tn.s)(),[a,d]=(0,i.useState)(!1);if(0===n.length&&0===s)return null;let c=a?0:Math.max(0,n.length-20),u=c>0?n.slice(c):n,p=(t=n.filter(e=>void 0!==e.cost)).length>1?t.reduce((e,t)=>e+(t.cost??0),0):null;return(0,r.jsxs)("div",{style:{borderTop:o?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",background:"var(--bg-subtle)",padding:"6px 10px",fontFamily:"var(--font-mono)",fontSize:"calc(11.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,display:"flex",flexDirection:"column",gap:3,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"inherit",fontSize:11},children:l("codemode.calls")}),s>0&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:l("codemode.omittedCalls",{count:s})}),c>0&&(0,r.jsx)("button",{type:"button",onClick:()=>d(!0),style:{alignSelf:"flex-start",padding:0,border:"none",background:"none",color:"var(--accent)",cursor:"pointer",font:"inherit"},children:l("codemode.showEarlierCalls",{count:c})}),(0,r.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:3,minWidth:0},children:u.map((e,t)=>(0,r.jsx)(i$,{call:e},e.id||`${c+t}`))}),null!==p&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:l("codemode.modelCost",{cost:iE(p)})})]})}var iM=n(9701);let iR=new Map,iA="transcriptNotices";function iL(e){if("object"!=typeof e||null===e)return[];let t=e[iA];return Array.isArray(t)?t:[]}function iz(e){return e<1e3?e.toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${Math.round(e/1e3)}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${Math.round(e/1e6)}M`}let iP="#d97706";function iW(e,t){let n=t>=.01?`$${t.toFixed(2)}`:void 0;return n?e("transcriptNotice.costSuffix",{cost:n}):""}function iO(e,t){switch(t.kind){case"cache_miss":{let n={tokens:iz(t.missedTokens),cost:iW(e,t.missedCost)};if(t.modelChanged)return e("transcriptNotice.cacheMissModelSwitch",n);if(void 0!==t.idleMinutes)return e("transcriptNotice.cacheMissIdle",{...n,minutes:t.idleMinutes});return e("transcriptNotice.cacheMiss",n)}case"cache_warm":var n;return e("transcriptNotice.cacheWarmed",{note:t.note?e("transcriptNotice.cacheWarmedNote",{note:t.note}):"",cost:(n=t.cost,`$${n.toFixed(6).replace(/(\.\d{3}\d*?)0+$/,"$1")}`)});case"summary_cost":return e("compaction"===t.source?"transcriptNotice.compactionCost":"transcriptNotice.branchSummaryCost",{tokens:iz(t.tokens),cost:iW(e,t.cost)});case"thinking_dropped":return e(1===t.count?"transcriptNotice.thinkingDroppedOne":"transcriptNotice.thinkingDropped",{count:t.count})}}let iF=(0,i.memo)(function(e){let{notices:t}=e,{t:n}=(0,tn.s)(),i=t.filter(e=>"summary_cost"!==e.kind||"compaction"!==e.source);return 0===i.length?null:(0,r.jsx)("div",{className:"transcript-notices",style:{display:"flex",flexDirection:"column",gap:2,margin:"-6px 0 12px"},children:i.map((e,t)=>{let i="cache_warm"!==e.kind;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:12,lineHeight:1.5,color:i?iP:"var(--text-dim)",overflowWrap:"anywhere"},children:[i&&(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:3},children:[(0,r.jsx)("path",{d:"M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsx)("span",{children:iO(n,e)})]},t)})})}),iD=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function iB(e){let t=0,n=0;for(let r of e)iD.test(r)?t++:n++;return t+n/4}let iH=new Map;function i_(e){let{children:t,className:n,...s}=e,{t:o}=(0,tn.s)(),[l,a]=(0,i.useState)(!1);if(t.length<=1e5)return(0,r.jsx)(is.m,{className:n,...s,children:t});if(!l){var d;return(0,r.jsxs)("button",{onClick:()=>a(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",o("i18n.largeMessageReveal",{size:(d=t.length)>=1e6?`${(d/1e6).toFixed(1)} MB`:d>=1e3?`${Math.round(d/1e3)} KB`:`${d} B`})]})}return(0,r.jsx)("div",{className:n,style:{maxHeight:420,overflow:"auto",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:t})})}function iU(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(r)return i;let s=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0});return`${s} ${i}`}let iK=(0,i.memo)(function(e){let{message:t,isStreaming:n,toolResults:i,modelNames:s,cwd:o,onOpenFile:l,onOpenSubagent:a,entryId:d,searchBlock:c,onFork:u,forking:p,onEditContent:h,onCancelEdit:m,isEditing:f,showTimestamp:g,prevTimestamp:x,sessionId:v,writtenFiles:b,turnDurationMs:y,onCompact:j,isCompacting:k,compactError:w}=e;return"user"===t.role?(0,r.jsx)(iq,{message:t,cwd:o,onOpenFile:l,entryId:d,onFork:u,forking:p,onEditContent:h,onCancelEdit:m,isEditing:f}):"assistant"===t.role?(0,r.jsx)(iV,{message:t,isStreaming:n,toolResults:i,modelNames:s,cwd:o,onOpenFile:l,onOpenSubagent:a,showTimestamp:g,prevTimestamp:x,sessionId:v,entryId:d,searchBlock:c,writtenFiles:b,turnDurationMs:y,onCompact:j,isCompacting:k,compactError:w}):"toolResult"===t.role?null:"custom"===t.role?"compaction"===t.customType?(0,r.jsx)(si,{message:t}):(0,r.jsx)(sa,{message:t,cwd:o,onOpenFile:l}):"bashExecution"===t.role?(0,r.jsx)(sy,{message:t,sessionId:v}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&function(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}(e.message,e.toolResults,t.toolResults)&&e.modelNames===t.modelNames&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.onOpenSubagent===t.onOpenSubagent&&e.entryId===t.entryId&&e.searchBlock===t.searchBlock&&e.onFork===t.onFork&&e.forking===t.forking&&e.onEditContent===t.onEditContent&&e.onCancelEdit===t.onCancelEdit&&e.isEditing===t.isEditing&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.writtenFiles===t.writtenFiles&&e.turnDurationMs===t.turnDurationMs&&e.sessionId===t.sessionId&&e.onCompact===t.onCompact&&e.isCompacting===t.isCompacting&&e.compactError===t.compactError);function iq(e){let{message:t,cwd:n,onOpenFile:s,entryId:o,onFork:l,forking:a,onEditContent:d,onCancelEdit:c,isEditing:u}=e,{t:p}=(0,tn.s)(),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),b=("string"==typeof t.content?t.content:t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).replace(/\r\n?/g,"\n"),y="string"==typeof t.content?[]:t.content.filter(e=>"image"===e.type),j=np(b),k=j?.search(/\s/)??-1,w=j?-1===k?j:j.slice(0,k):"",S=j&&-1!==k?j.slice(k+1):"",C=iU(t.timestamp),N=!!o&&!!l,E=j??b,I=j?function(e,t){if("string"==typeof e.content)return{...e,content:t};let n=[],r=!1;for(let i of e.content){if("text"!==i.type){n.push(i);continue}r||(n.push({...i,text:t}),r=!0)}return r||n.unshift({type:"text",text:t}),{...e,content:n}}(t,j):t,$=y.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!b},children:y.map((e,t)=>{let n=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,r.jsx)(io.k,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid rgba(59,130,246,0.15)"}})},t)})}),T=!!o&&!!d,M=!!u&&!!c;return(0,r.jsxs)("div",{style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,r.jsx)("div",{style:{flex:1,minWidth:0,background:u?"color-mix(in srgb, var(--accent) 14%, var(--user-bg))":"var(--user-bg)",border:u?"1px solid color-mix(in srgb, var(--accent) 62%, var(--user-bg))":"1px solid rgba(59,130,246,0.2)",boxShadow:u?"0 0 0 2px color-mix(in srgb, var(--accent) 16%, transparent)":void 0,borderRadius:12,padding:"8px 12px",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",maxHeight:300,overflowY:"auto"},children:j?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[$,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,r.jsxs)("button",{onClick:()=>v(e=>!e),title:p(x?"i18n.collapse":"i18n.expand"),"aria-expanded":x,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",textAlign:"left"},children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.75,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),S&&(0,r.jsx)("span",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word",minWidth:0,flex:1},children:S})]}),x&&(0,r.jsx)(is.m,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:s,children:function(e){let t=e.match(nu);if(!t)return null;let n=t[4],r=void 0===n?9:11+n.length;return e.slice(e.indexOf("\n")+1,e.length-r)}(b)??b})]}):(0,r.jsxs)(r.Fragment,{children:[$,b&&(0,r.jsx)(i_,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:s,children:b})]})})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,r.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!h,pointerEvents:h?"auto":"none",transition:"opacity 0.12s"},children:(0,r.jsxs)("button",{onClick:()=>{(0,ia.D)(E).then(()=>{g(!0),setTimeout(()=>g(!1),1500)})},title:p("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:f?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{f||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{f||(e.currentTarget.style.color="var(--text-dim)")},children:[f?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,r.jsx)("span",{className:"message-action-label",children:p(f?"i18n.copied":"i18n.copy")})]})}),(N||T||M)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:h||a||M?1:0,pointerEvents:h||a||M?"auto":"none",transition:"opacity 0.12s"},children:[T&&!M&&(0,r.jsxs)("button",{onClick:()=>d(I,o),title:p("i18n.editFromHereTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,r.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]}),(0,r.jsx)("span",{className:"message-action-label",children:p("i18n.editFromHere")})]}),M&&(0,r.jsxs)("button",{type:"button",onClick:c,title:p("i18n.cancel"),"aria-label":p("i18n.cancel"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:500,whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6L6 18"})}),(0,r.jsx)("span",{className:"message-action-label",children:p("i18n.cancel")})]}),N&&(0,r.jsxs)("button",{onClick:()=>{l(o)},disabled:a,title:p(a?"i18n.creatingSession":"i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:a?"var(--accent)":"var(--text-dim)",cursor:a?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{a||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{a||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{className:"message-action-label",children:p(a?"i18n.creating":"i18n.newSession")})]})]}),C&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:C})]})]})}function iV(e){var t,n,s,o,l;let a,d,c,u,p,h,{message:m,isStreaming:f,toolResults:g,modelNames:x,cwd:v,onOpenFile:b,onOpenSubagent:y,showTimestamp:j,prevTimestamp:k,sessionId:w,entryId:S,searchBlock:C,writtenFiles:N,turnDurationMs:E,onCompact:I,isCompacting:$,compactError:T}=e,{t:M}=(0,tn.s)(),R=j?iU(m.timestamp):null,A=(0,i.useMemo)(()=>(m.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(e=>{let{block:t}=e;return!rK(t,{isStreaming:f})}),[m.content,f]),L=(0,i.useMemo)(()=>A.map(e=>{let{block:t}=e;return t}),[A]),z=rV(m,{isStreaming:f}),P=rZ(m,{isStreaming:f}),W=P&&!rJ(m),[O,F]=(0,i.useState)(!1),[D,B]=(0,i.useState)(!1),H=(0,i.useRef)(null),_="number"!=typeof m.timestamp?null:`${m.provider??""}/${m.model??""}@${m.timestamp}`,U=(0,i.useRef)(_);U.current=_;let[K,q]=(0,i.useState)(null),V=(0,i.useRef)(A);V.current=A;let Z=(0,i.useRef)(new Map),J=(0,i.useMemo)(()=>{if(!f)return Z.current=new Map,0;let e=new Map,t=0;for(let{block:n,originalIndex:r}of A){let i="text"===n.type?n.text:"thinking"===n.type?n.thinking:"toolCall"===n.type?n.rawInput??JSON.stringify(n.input??{})??"":null;if(null===i)continue;let s=function(e,t){var n,r;if(!e||!t.startsWith(e.text))return iB(t);let i=e.tokens,s=e.text.length;return s>0&&s<t.length&&(n=e.text.charCodeAt(s-1))>=55296&&n<=56319&&(r=t.charCodeAt(s))>=56320&&r<=57343&&(i-=.25,s--),i+iB(t.slice(s))}(Z.current.get(r),i);e.set(r,{text:i,tokens:s}),t+=s}return Z.current=e,t},[A,f]),G=(0,i.useRef)(J);G.current=J;let Y=(0,i.useRef)(new Map),[X,Q]=(0,i.useState)(new Map),ee="assistant"===m.role?iX(m.durationMs):void 0,et=(0,i.useMemo)(()=>{let e=ee??(m.timestamp&&k?m.timestamp-k:void 0);if(void 0===e)return;let t=Math.round(e/1e3);return t>0?t:void 0},[ee,m.timestamp,k]),en=(0,i.useMemo)(()=>{let e=new Map;if(!g)return e;for(let[t,n]of g){let r=iX(n.durationMs)??(n.timestamp&&m.timestamp?n.timestamp-m.timestamp:void 0);void 0!==r&&r>=iQ&&e.set(t,r)}return e},[g,m.timestamp]),er=L.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),ei=m.usage?(s=m.usage,a=[],s.input&&a.push({icon:"up",before:"↑",text:iz(s.input)}),s.output&&a.push({icon:"down",before:"↓",text:iz(s.output)}),s.cacheRead&&a.push({text:`R${iz(s.cacheRead)}`}),s.cacheWrite&&a.push({text:`W${iz(s.cacheWrite)}`}),s.cost?.total&&a.push({text:`$${s.cost.total.toFixed(4)}`}),a):[];if(void 0!==E){let e;ei.length>0&&ei.push({text:"\xb7"});let t=ie(E);ei.push((o=M("chat.turnDuration",{time:t}),l=t,(e=o.indexOf(l))<0?{text:o}:{icon:"clock",before:o.slice(0,e),text:l,after:o.slice(e+l.length)}))}return((0,i.useEffect)(()=>{if(!f){let e=new Date().getTime();Q(t=>{let n=new Map(t);for(let[t,r]of Y.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),H.current=null,q(null);return}let e=setInterval(()=>{var e;let t,n=V.current,r=Date.now();n.forEach(e=>{let{originalIndex:t}=e;Y.current.has(t)||Y.current.set(t,r)}),Q(e=>{let t=!1,i=new Map(e);for(let e=0;e<n.length-1;e++){let s=n[e].originalIndex,o=n[e+1].originalIndex;if(!i.has(s)&&Y.current.has(s)){let e=Y.current.get(s),n=Y.current.get(o)??r;i.set(s,Math.round((n-e)/1e3)),t=!0}}return t?i:e});let i=G.current;if(0===i)return;H.current??=function(e,t,n){let r=null===e?void 0:iR.get(e);if(r)return r;let i={at:n,tokens:t};return null!==e&&(iR.set(e,i),iR.size>32&&iR.delete(iR.keys().next().value)),i}(U.current,i,r);let s=(e=H.current,(t=(r-e.at)/1e3)>.5?(i-e.tokens)/t:null);null!==s&&q(s)},300);return()=>clearInterval(e)},[f]),0!==L.length||f||z||P)?(0,r.jsxs)("div",{"data-message-role":"assistant","data-entry-id":S,style:{marginBottom:16},onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",marginBottom:4,display:"flex",alignItems:"center",gap:6},children:[m.provider&&(0,r.jsx)("span",{children:(t=m.provider,n=m.model,d=t.toLowerCase(),c=n.toLowerCase(),u=Object.entries(x??{}).flatMap(e=>{let[t,n]=e,r=t.indexOf(":");return r>0&&t.slice(0,r).toLowerCase()===d?[{id:t.slice(r+1).toLowerCase(),name:n}]:[]}),u.find(e=>e.id===c)?.name??u.find(e=>c.endsWith(`/${e.id}`))?.name??Object.entries(x??{}).find(e=>{let[t]=e;return t.toLowerCase()===c})?.[1]??`${t}/${n}`)}),f&&(p=Math.round(J),(0,r.jsx)(r.Fragment,{children:p>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:"var(--text)"},title:M("i18n.estimatedTokens"),children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:2,fontSize:11,fontWeight:400},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),p]}),null!==K&&(h=K>=50?"#53b3cb":K>=30?"#9bc53d":K>=15?"#f9c22e":"#e01a4f",(0,r.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",borderRadius:4,background:h,color:"#fff",fontSize:11,fontWeight:400},children:[K.toFixed(1)," t/s"]}))]})}))]}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:A.map(e=>{let{block:t,originalIndex:n}=e;return(0,r.jsx)(iZ,{block:t,searchTarget:t===C,toolResults:g,isStreaming:f,streamingDuration:X.get(n)??("thinking"===t.type?et:void 0),toolCallDurations:en,cwd:v,onOpenFile:b,onOpenSubagent:y,sessionId:w,entryId:S,blockIndex:n},n)})}),z&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(L.length>0),padding:"7px 10px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,background:"rgba(239,68,68,0.07)",color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",z]}),P&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:L.length>0||z?8:0,padding:"7px 10px",border:"1px solid rgba(234,179,8,0.3)",borderRadius:6,background:"rgba(234,179,8,0.07)",color:"#ca8a04",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[M(W?"chat.truncatedWithoutAnswer":"chat.truncatedByOutputLimit"),W&&I&&(0,r.jsx)("button",{type:"button",onClick:I,disabled:$,style:{display:"block",marginTop:8,padding:"3px 8px",border:"1px solid currentColor",borderRadius:5,background:"transparent",color:"inherit",cursor:$?"default":"pointer",font:"inherit"},children:M($?"chat.compacting":"chat.compactContext")}),W&&T&&(0,r.jsx)("div",{style:{marginTop:8,color:"#ef4444",whiteSpace:"pre-wrap"},children:T})]}),N&&N.length>0&&(0,r.jsx)(iy,{files:N,onOpenFile:b}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[ei.length>0&&!f&&(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",columnGap:7,fontSize:11,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:ei.map((e,t)=>(0,r.jsxs)(i.Fragment,{children:[t>0&&" ",(0,r.jsx)(sb,{part:e})]},t))}),er&&!f&&(0,r.jsxs)("button",{onClick:()=>{(0,ia.D)(er).then(()=>{B(!0),setTimeout(()=>B(!1),1500)})},title:M("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:D?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!O,pointerEvents:O?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{D||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{D||(e.currentTarget.style.color="var(--text-dim)")},children:[D?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,r.jsx)("span",{className:"message-action-label",children:M(D?"i18n.copied":"i18n.copy")})]}),R&&!f&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto",whiteSpace:"nowrap"},children:R})]})]}):null}function iZ(e){let{block:t,searchTarget:n,toolResults:i,isStreaming:s,streamingDuration:o,toolCallDurations:l,cwd:a,onOpenFile:d,onOpenSubagent:c,sessionId:u,entryId:p,blockIndex:h}=e;if("text"===t.type)return(0,r.jsx)("div",{"data-message-text":!0,"data-search-target":n||void 0,children:(0,r.jsx)(iJ,{block:t,isStreaming:s,cwd:a,onOpenFile:d})});if("thinking"===t.type)return(0,r.jsx)(iY,{block:t,duration:o,sessionId:u,entryId:p,blockIndex:h});if("toolCall"===t.type){let e=i?.get(t.toolCallId),n=l?.get(t.toolCallId);return(0,r.jsx)(i0,{block:t,result:e,duration:n,onOpenSubagent:c})}return null}function iJ(e){let{block:t,isStreaming:n,cwd:i,onOpenFile:s}=e;return(0,r.jsx)(i_,{isStreaming:n,cwd:i,onOpenFile:s,children:t.text})}function iG(e){let{text:t}=e,n=(0,i.useMemo)(()=>(function(e){let t=[],n=0;for(;e.length-n>8e3;){let r=n+8e3,i=r+8e3,s=e.slice(r,i+1),o=s.indexOf("\n");for(;o>=0&&/\n\r?$/.test(e.slice(r+o-2,r+o));)o=s.indexOf("\n",o+1);if(o>=0){let i=r+o;if(i===e.length-1)break;t.push({text:e.slice(n,i),lineBreak:!0}),n=i+1}else if(e.length>i){let r=e.charCodeAt(i-1),s=r>=55296&&r<=56319?i-1:i;t.push({text:e.slice(n,s),lineBreak:!1}),n=s}else break}return t.push({text:e.slice(n),lineBreak:!1}),t})(t),[t]);return 1===n.length?t:n.map((e,t)=>(0,r.jsx)("div",{children:e.text},t))}function iY(e){var t;let{block:n,duration:s,sessionId:o,entryId:l,blockIndex:a}=e,{t:d}=(0,tn.s)(),[c,u]=(0,i.useState)(ib),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(!1),[g,x]=(0,i.useState)(null),v=`${o}:${l}:${a}`,[b,y]=(0,i.useState)(v);b!==v&&(y(v),h(null),f(!1),x(null));let j=(0,i.useRef)(d);j.current=d;let k=(t=n.thinking,t.trimStart().match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,i.useEffect)(()=>{let e=()=>u(ib());return window.addEventListener(iv,e),()=>window.removeEventListener(iv,e)},[]),(0,i.useEffect)(()=>{if(!c||!n.deferred||null!==p)return;if(!o||!l)return void x(j.current("i18n.thinkingUnavailable"));let e=!1;return f(!0),x(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=iH.get(r);if(i)return iH.delete(r),iH.set(r,i),i;let s=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw iH.delete(r),e});if(iH.set(r,s),iH.size>100){let e=iH.keys().next().value;e&&iH.delete(e)}return s})(o,l,a).then(t=>{e||(h(t),f(!1))}).catch(t=>{e||(x(t instanceof Error?t.message:String(t)),f(!1))}),()=>{e=!0}},[c,n.deferred,p,o,l,a]),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:6,minWidth:0,border:"1px solid var(--border)",borderRadius:7,padding:"6px 10px",background:"var(--bg)",fontFamily:"var(--font-mono)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":c,"aria-label":`${d("i18n.thinking")}${k?`: ${k}`:""}`,title:d("i18n.thinking"),onClick:()=>u(e=>!e),style:{display:"inline-flex",alignItems:"center",gap:6,width:c?14:"100%",flexShrink:+!c,minWidth:0,minHeight:"1.5em",padding:0,background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,r.jsx)(il,{active:c}),!c&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k?(0,r.jsx)(ii.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:k}):"..."})]}),c&&(0,r.jsx)("div",{style:{flex:1,minWidth:0,color:g?"#f87171":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:m?d("i18n.loadingThinking"):g??(0,r.jsx)(iG,{text:(n.deferred?p:n.thinking)??""})}),void 0!==s&&(0,r.jsxs)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:[s,"s"]})]})}function iX(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}let iQ=100;function i0(e){var t,n,s,o;let l,{block:a,result:d,duration:c,onOpenSubagent:u}=e,{t:p}=(0,tn.s)(),[h,m]=(0,i.useState)(()=>{var e;return void 0!==(e=a.toolCallId)&&ig.has(e)}),f=function(e){if(void 0!==e.rawInput||!rX(e.toolName))return null;let{content:t}=e.input;return"string"!=typeof t||""===t?null:Object.keys(e.input).every(e=>sp.has(e))?t:null}(a),g=f??(s=a).rawInput??JSON.stringify(s.input,null,2),x=void 0!==a.rawInput,v=rQ(a.toolName),b=d&&!d.isError?function(e){let t=e.details;if(!st(t))return null;let n="string"==typeof t.patch?t.patch:null;if(n)return{text:n};let r="string"==typeof t.diff?t.diff:null;return r?{text:r}:null}(d):null,y=b?.text,j=(0,i.useMemo)(()=>(function(e){if(!e)return null;let t=iu(e);return t?.length===1&&i5(t[0])||null})(y),[y]),k=function(e,t){if(!r0(e.toolName))return null;let n=r3(r1(e.input,e.rawInput));if(n)return n;let r=t&&!t.isError?t.details:void 0;if(st(r)){let e=r5(r.preview);if(e)return e}return null}(a,d),w=r0(a.toolName)?0===(l=function(e){let t=[];for(let n of e.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm)){let e=(n[1]??"").trim();e&&!t.includes(e)&&t.push(e)}return t}(r1((o=a).input,o.rawInput))).length?null:l.join(", ").slice(0,120):null,S=a.toolName!==ij||x?null:iw(t=a.input)&&"string"==typeof t.code?t.code:null,C=null===S?null:{code:S,...iC(d?.details)},N=null!==C&&void 0!==d&&0===d.content.length,E=h&&null===f&&null===C&&null===k?function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let t=Object.entries(e);if(0===t.length)return null;let n=[];for(let[e,r]of t){if(null!==r&&"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r)return null;let t=null===r?"null":String(r);n.push({key:e,value:""===t?"(empty)":t,multiline:t.includes("\n")})}return n}(x?(0,iM.o2)(a.rawInput):a.input):null,I=function(e,t){if(!e.startsWith("mcp__")||!("object"==typeof t&&null!==t&&!Array.isArray(t)))return null;let{server:n,tool:r}=t;return"string"==typeof n&&"string"==typeof r&&n&&r?{server:n,tool:r}:null}(a.toolName,d?.details),$=d?C?function(e){let[t,...n]=e;return t?.type==="text"&&"string"==typeof t.text&&iN.test(t.text)?n:[...e]}(d.content):d.content:[],T=d?$.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,M=I&&null!==T?function(e){let t=e.trim();if(t.length>2e5||!/^[[{]/.test(t))return e;try{return JSON.stringify(JSON.parse(t),null,2)}catch{return e}}(T):T,R=sc($),A=null!==M&&("(no output)"===M.trim()||""===M.trim()),L=(d?.isError??!1)||r0(a.toolName)&&r4(d?.details),z=(n=d?.details)&&"object"==typeof n&&"pi-web-subagent"===n.kind&&"string"==typeof n.sessionId?d.details:null,P=C?C.calls.length+C.omitted:0;return(0,r.jsxs)("div",{style:{borderRadius:7,overflow:"hidden",fontSize:12,border:L?"1px solid rgba(248,113,113,0.45)":"1px solid rgba(34,197,94,0.25)",background:L?"rgba(248,113,113,0.05)":"rgba(34,197,94,0.04)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:[(0,r.jsxs)("button",{onClick:()=>{var e;let t=!h;e=a.toolCallId,e&&(t?ig.add(e):ig.delete(e)),m(t)},style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:[(0,r.jsx)("span",{title:I?a.toolName:void 0,style:{color:L?"#f87171":"#16a34a",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:I?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{style:{fontWeight:500,opacity:.75},children:[I.server,"/"]}),I.tool]}):a.toolName}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:x?p("chat.generatingToolInput"):w??(C?function(e){for(let t of e.split(/\r?\n/)){let e=t.trim();if(e&&!e.startsWith("// @options:"))return e}return""}(C.code):function(e,t){let n=e.input;if(!n||"object"!=typeof n)return"";let r=Object.keys(n);return 0===r.length?"":"command"in n?String(n.command).slice(0,120):"path"in n?String(n.path).slice(0,120):"file_path"in n?String(n.file_path).slice(0,120):t?t.slice(0,120):"pattern"in n?String(n.pattern).slice(0,120):"query"in n?String(n.query).slice(0,120):String(n[r[0]]).slice(0,120)}(a,j))}),P>0&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:1===P?p("codemode.callCountOne"):p("codemode.callCount",{count:P})}),void 0!==c&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:function(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t),r=Math.floor(n/60),i=n%60;return r<60?`${r}m ${i}s`:`${Math.floor(r/60)}h ${r%60}m ${i}s`}(c)}),(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:h?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),z&&u&&(0,r.jsx)("button",{type:"button",onClick:()=>u(z.sessionId,z.description||z.profile),title:p("subagent.openTab"),"aria-label":p("subagent.openTab"),style:{width:32,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",background:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})})]}),h&&(x||!v)&&!k&&(E?(0,r.jsx)("div",{style:{padding:"6px 10px 8px",background:"var(--bg-subtle)",borderTop:L?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)"},children:(0,r.jsx)(sg,{fields:E})}):(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",background:"var(--bg-subtle)",borderTop:L?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:C?C.code.replace(/\r/g,"").trimEnd():g})),h&&C&&(0,r.jsx)(iT,{calls:C.calls,omitted:C.omitted,isError:L}),R.length>0&&(0,r.jsx)(sn,{images:R,isError:L}),h&&k&&(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(i4,{files:k})}),h&&d&&k&&L&&(0,r.jsx)(sr,{text:M??"",isEmpty:A,isError:L}),h&&d&&!k&&!N&&(b?(0,r.jsx)(i1,{diff:b}):(!A||0===R.length)&&(0,r.jsx)(sr,{text:M??"",isEmpty:A,isError:L}))]})}function i1(e){let{diff:t}=e;return(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(i2,{text:t.text})})}function i2(e){let{text:t}=e,n=(0,i.useMemo)(()=>iu(t),[t]);return n?(0,r.jsx)(i4,{files:n}):(0,r.jsx)(se,{text:t})}function i4(e){let{files:t}=e,n=tp()?"stacked":"split";return(0,r.jsx)(i8,{files:t,layout:n})}function i8(e){let{files:t,layout:n}=e,{t:i}=(0,tn.s)(),s=t.length>1;return(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden",background:"var(--bg)"},children:t.map((e,t)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===t?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55},children:[s&&"split"===n&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(i9,{title:e.oldPath||i("i18n.before"),side:"left"}),(0,r.jsx)(i9,{title:e.newPath||i("i18n.after"),side:"right"})]}),s&&"stacked"===n&&i5(e)&&(0,r.jsx)("div",{title:i5(e),style:{position:"sticky",top:0,zIndex:1,padding:"5px 10px",color:"var(--text-dim)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i5(e)}),"split"===n&&(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:"gap"===e.type?(0,r.jsx)(i3,{gap:e},t):(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(i7,{cell:e.left,side:"left"}),(0,r.jsx)(i7,{cell:e.right,side:"right"})]},t))}),"stacked"===n&&ip(e).map((e,t)=>"gap"===e.type?(0,r.jsx)(i3,{gap:e},t):(0,r.jsx)(i6,{line:e},t))]},t))})}function i3(e){let{gap:t}=e,{t:n}=(0,tn.s)();return(0,r.jsx)("div",{style:{gridColumn:"1 / -1",padding:"0 10px",color:"var(--text-dim)",background:"var(--bg-panel)",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)",userSelect:"none"},children:null===t.count?"⋯":`⋯ ${ih(t.count,n)}`})}function i5(e){return e.newPath&&"/dev/null"!==e.newPath?e.newPath:e.oldPath||e.newPath||""}function i6(e){let{line:t}=e;return(0,r.jsx)(i7,{side:"right",cell:{lineNo:"removed"===t.type?t.oldLineNo:t.newLineNo,text:t.text,type:t.type}})}function i9(e){let{title:t,side:n}=e;return(0,r.jsx)("div",{title:t,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===n?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})}function i7(e){let{cell:t,side:n}=e,i="added"===t.type?"rgba(34,197,94,0.12)":"removed"===t.type?"rgba(248,113,113,0.13)":"empty"===t.type?"var(--bg-subtle)":"transparent",s="added"===t.type?"+":"removed"===t.type?"-":" ",o="added"===t.type?"#22c55e":"removed"===t.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:i,borderRight:"left"===n?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:t.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:o,userSelect:"none",fontWeight:"context"===t.type||"empty"===t.type?400:700,flexShrink:0},children:s}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===t.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.text||"\xa0"})]})}function se(e){let{text:t}=e,n=t.split(/\r?\n/);return(0,r.jsx)("div",{style:{maxHeight:520,overflowY:"auto",overflowX:"hidden",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,minWidth:0},children:n.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"rgba(34,197,94,0.12)":"removed"===n?"rgba(248,113,113,0.13)":"hunk"===n?"rgba(96,165,250,0.12)":"transparent",borderLeft:"added"===n?"3px solid #22c55e":"removed"===n?"3px solid #f87171":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"#22c55e":"removed"===n?"#f87171":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function st(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sn(e){let{images:t,isError:n}=e;return(0,r.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",padding:"10px",background:"var(--bg)",borderTop:`1px solid ${n?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`},children:t.map((e,t)=>{let n=su(e);return n?(0,r.jsx)(io.k,{src:n,style:{maxWidth:"100%"},children:(0,r.jsx)("img",{src:n,alt:"",loading:"lazy",style:{display:"block",maxWidth:"min(100%, 720px)",maxHeight:520,borderRadius:6,objectFit:"contain",border:"1px solid var(--border)"}})},`${n}-${t}`):null})})}function sr(e){let{text:t,isEmpty:n,isError:i}=e,{t:s}=(0,tn.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${i?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`,background:i?"rgba(248,113,113,0.04)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:i?"#f87171":n?"var(--text-dim)":"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:n?"italic":"normal",opacity:n?.6:1},children:n?s("i18n.noOutput"):t})})}function si(e){let{message:t}=e,{t:n}=(0,tn.s)(),[s,o]=(0,i.useState)(!1),l=sd(t.content),a=iU(t.timestamp),d=t.details?.tokensBefore,c=iL(t).find(e=>"summary_cost"===e.kind&&"compaction"===e.source);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),a&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:a})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":s,title:n(s?"i18n.collapse":"i18n.expand"),onClick:()=>o(e=>!e),style:{display:"flex",alignItems:"flex-start",gap:8,width:"100%",padding:0,border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:4,color:"var(--text-muted)",transform:s?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"calc(15px + var(--chat-font-size-offset, 0px))",fontWeight:700,lineHeight:1.35},children:n("i18n.conversationCompacted")}),"number"==typeof d&&Number.isFinite(d)&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:n("i18n.compactedFromTokens",{tokens:d.toLocaleString()})}),c&&(0,r.jsx)("span",{style:{display:"block",marginTop:2,color:iP,fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:iO(n,c)})]})]}),s&&(0,r.jsx)(ss,{summary:l})]})]})})}function ss(e){let{summary:t}=e,{t:n}=(0,tn.s)(),s=(0,i.useMemo)(()=>{let e,n,r,i,s;return e=[],n=[],r=t.match(ic),i=r?.[1]??"",s=r?.index===void 0?t:t.slice(0,r.index),i.replace(id,(t,r,i)=>{let s=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...s):n.push(...s),""}),{body:s.trim(),readFiles:e,modifiedFiles:n}},[t]);return(0,r.jsxs)("div",{style:{marginTop:10},children:[(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:n("i18n.compactionDescription")}),s.body?(0,r.jsx)(is.m,{className:"markdown-compaction-message",children:s.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:n("i18n.noSummary")}),(0,r.jsx)(so,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})}function so(e){let{readFiles:t,modifiedFiles:n}=e,{t:i}=(0,tn.s)();if(0===t.length+n.length)return null;let s=[];return t.length>0&&s.push(`${t.length} read`),n.length>0&&s.push(`${n.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:i("i18n.fileContext",{details:s.join(", ")})}),n.length>0&&(0,r.jsx)(sl,{title:i("i18n.modifiedFiles"),files:n}),t.length>0&&(0,r.jsx)(sl,{title:i("i18n.readFiles"),files:t})]})}function sl(e){let{title:t,files:n}=e;return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:t}),(0,r.jsx)("ul",{className:"compaction-file-list",children:n.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function sa(e){let{message:t,cwd:n,onOpenFile:s}=e,{t:o}=(0,tn.s)(),[l,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=sd(t.content),m=sc(t.content),f=void 0!==t.details,g=f?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(t.details):"",x=t.customType||"extension",v=iU(t.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:l?"1px solid var(--border)":"none",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:(0,r.jsxs)("button",{type:"button",onClick:()=>a(e=>!e),"aria-expanded":l,title:o(l?"i18n.collapse":"i18n.expand"),style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1,padding:0,border:"none",background:"none",color:"inherit",cursor:"pointer",fontSize:"inherit",textAlign:"left"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650,flexShrink:0},children:x}),!l&&h&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:h.slice(0,300).replace(/\s+/g," ").trim()}),v&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,flexShrink:0},children:v}),(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:l?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})}),l&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[m.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!h},children:m.map((e,t)=>{let n=su(e);return n?(0,r.jsx)(io.k,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t):null})}),h?(0,r.jsx)(is.m,{className:"markdown-custom-message",keepTextLayout:!0,cwd:n,onOpenFile:s,children:h}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:o("i18n.noMessage")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[h||g?(0,r.jsx)("button",{onClick:()=>{(0,ia.D)(h||g).then(()=>{p(!0),setTimeout(()=>p(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:u?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(u?"i18n.copied":"i18n.copy")}):null,f&&(0,r.jsx)("button",{onClick:()=>c(e=>!e),style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(d?"i18n.hideDetails":"i18n.showDetails")})]}),f&&d&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:g})]})]})})}function sd(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function sc(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function su(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}let sp=new Set(["path","file_path","content"]),sh={padding:"4px 12px 4px 0",color:"var(--text-dim)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",whiteSpace:"nowrap",verticalAlign:"top"},sm={padding:"4px 0",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},sf={margin:0,padding:"8px 10px",maxHeight:260,overflow:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",font:"inherit",lineHeight:1.5,whiteSpace:"pre-wrap"};function sg(e){let{fields:t}=e;return(0,r.jsx)("table",{style:{borderCollapse:"collapse"},children:(0,r.jsx)("tbody",{children:t.map(e=>(0,r.jsxs)("tr",{children:[(0,r.jsx)("td",{style:sh,children:e.key}),(0,r.jsx)("td",{style:sm,children:e.multiline?(0,r.jsx)("pre",{style:sf,children:e.value}):e.value})]},e.key))})})}let sx={up:"M6 10.5V1.5M2.5 5 6 1.5 9.5 5",down:"M6 1.5v9M2.5 7 6 10.5 9.5 7",clock:"M6 1.25a4.75 4.75 0 1 0 0 9.5 4.75 4.75 0 1 0 0-9.5M6 3.5V6l1.75 1"},sv={fontSize:0};function sb(e){let{part:t}=e;return t.icon?(0,r.jsxs)("span",{children:[t.before&&(0,r.jsx)("span",{style:sv,children:t.before}),(0,r.jsx)("svg",{width:"clock"===t.icon?10:9,height:"clock"===t.icon?10:9,viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,style:{display:"inline",verticalAlign:"clock"===t.icon?"-0.1em":"-0.05em",marginRight:"clock"===t.icon?3:1},children:(0,r.jsx)("path",{d:sx[t.icon]})}),t.text,t.after&&(0,r.jsx)("span",{style:sv,children:t.after})]}):(0,r.jsx)("span",{children:t.text})}function sy(e){let{message:t,sessionId:n}=e,{t:s}=(0,tn.s)(),[o,l]=(0,i.useState)(null),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),p=!t.output&&void 0===t.exitCode&&!t.cancelled,h=t.cancelled||void 0!==t.exitCode&&0!==t.exitCode,m=n&&t.fullOutputPath?`/api/agent/${encodeURIComponent(n)}/bash-output?path=${encodeURIComponent(t.fullOutputPath)}`:null,f=t.truncated&&m&&null===o,g=o??t.output;async function x(){if(m){d(!0),u(null);try{let e=await fetch(m),t=await e.json();t.success?l(t.data?.output??""):u(t.error??"failed")}catch(e){u(String(e))}finally{d(!1)}}}let v=t.excludeFromContext?"bash (local)":"bash",b={type:"toolCall",toolCallId:`bash-${t.timestamp??""}`,toolName:v,input:{command:t.command}},y=p?void 0:{role:"toolResult",toolCallId:b.toolCallId,toolName:v,content:g?[{type:"text",text:g}]:[],isError:h,timestamp:t.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(i0,{block:b,result:y}),t.truncated&&m&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[f&&(0,r.jsx)("button",{onClick:x,disabled:a,style:{background:"none",border:"none",color:"var(--accent)",cursor:a?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s(a?"chat.loadingFullOutput":"chat.viewFullOutput")}),(0,r.jsx)("a",{href:`${m}&download=1`,style:{marginLeft:10*!!f,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:s("chat.downloadFullOutput")}),c&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",c,")"]})]})]})}function sj(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}let sk=new Map;function sw(e){return`parked-new:${e}`}function sS(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function sC(e){return!e.value&&0===e.images.length}function sN(e){let t=sk.get(e);return t?sS(t):null}function sE(e,t){sC(t)?sk.delete(e):sk.set(e,sS(t))}function sI(e){sk.delete(e)}function s$(e,t){return e.trim()?t.trim()?`${e}
6
+
7
+ ${t}`:e:t}function sT(e,t,n,r){let i=[...t??[],...r].filter(sj).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:s$(e,n),images:i}}function sM(e,t,n){let r=sN(e)??{value:"",images:[]},i=sT(t,n,r.value,r.images);return sE(e,i),i}function sR(e,t,n){if(e===t)return n?sS(n):sN(t);let r=sN(e),i=n&&!sC(n)?sS(n):r??(n?sS(n):null),s=sN(t);if(sI(e),!i)return s;let o=s?sT(s.value,s.images,i.value,i.images):i;return sE(t,o),sS(o)}let sA=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,sL=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,sz=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,sP=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,sW=/^[ \t]{0,3}(`{3,}|~{3,})/;function sO(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function sF(e){return"/mcp"===e.trim()}let sD="pi-enter-send-mode",sB="enter",sH=null,s_=new Set;function sU(){return null===sH&&(sH=function(){try{let e=window.localStorage.getItem(sD);return"ctrlEnter"===e?"ctrlEnter":"enter"}catch{return sB}}()),sH}function sK(e){return s_.add(e),()=>{s_.delete(e)}}function sq(e){sH=e;try{window.localStorage.setItem(sD,e)}catch{}s_.forEach(e=>e())}function sV(){return(0,i.useSyncExternalStore)(sK,sU,()=>sB)}let sZ="pi-chat-content-width",sJ="pi-chat-content-font-size",sG={width:820,fontSize:14},sY=null,sX=new Set;function sQ(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function s0(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function s1(e){try{return window.localStorage.getItem(e)}catch{return null}}function s2(e){let{width:t,fontSize:n}=e;"u">typeof document&&(document.documentElement.style.setProperty("--chat-content-max-width",`${t}px`),document.documentElement.style.setProperty("--chat-content-font-size",`${n}px`))}function s4(){return sY||s2(sY={width:sQ(s1(sZ)),fontSize:s0(s1(sJ))}),sY}function s8(e){return sX.add(e),()=>{sX.delete(e)}}function s3(e,t){let n="width"===e?sQ(t):s0(t);s2(sY={...s4(),[e]:n});try{window.localStorage.setItem("width"===e?sZ:sJ,String(n))}catch{}sX.forEach(e=>e())}let s5=e=>s3("width",e),s6=e=>s3("fontSize",e);function s9(){return{...(0,i.useSyncExternalStore)(s8,s4,()=>sG),setWidth:s5,setFontSize:s6}}let s7=[{value:100,label:"settings.fontWeightThin"},{value:200,label:"settings.fontWeightExtraLight"},{value:300,label:"settings.fontWeightLight"},{value:400,label:"settings.fontWeightRegular"},{value:500,label:"settings.fontWeightMedium"},{value:600,label:"settings.fontWeightSemiBold"}],oe={ui:"pi-ui-font-family",mono:"pi-mono-font-family",uiWeight:"pi-ui-font-weight",monoWeight:"pi-mono-font-weight"},ot={ui:"",mono:"",uiWeight:400,monoWeight:400};function on(e){let t="string"==typeof e?Number(e):e;return s7.find(e=>e.value===t)?.value??400}function or(e){return"string"==typeof e&&e.length<=500?e:""}let oi=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded"]),os=["ui","mono"],oo=Object.keys(oe),ol=null,oa=new Set;function od(){let e={...ot};for(let t of os)try{e[t]=or(window.localStorage.getItem(oe[t]));let n=`${t}Weight`;e[n]=on(window.localStorage.getItem(oe[n]))}catch{}return e}function oc(e){for(let t of os){let n=`--font-${t}`,r=function(e,t){let n=or(t).split(",").flatMap(e=>{let t=e.trim().replace(/\s+/g," "),n=t.length>=2&&('"'===t[0]||"'"===t[0])&&t.endsWith(t[0]);return(n&&(t=t.slice(1,-1).trim()),t)?[!n&&oi.has(t.toLowerCase())?t.toLowerCase():JSON.stringify(t)]:[]}).join(", ");return n?`${n}, var(--font-${e}-default)`:""}(t,e[t]);r?document.documentElement.style.setProperty(n,r):document.documentElement.style.removeProperty(n);let i=e[`${t}Weight`];400===i?document.documentElement.style.removeProperty(`${n}-weight`):document.documentElement.style.setProperty(`${n}-weight`,String(i))}}function ou(){return ol||oc(ol=od()),ol}function op(){oa.forEach(e=>e())}function oh(e){if(null!==e.key&&!Object.values(oe).includes(e.key))return;let t=od(),n=ou();oo.every(e=>t[e]===n[e])||(ol=t,oc(t),op())}function om(e){return 0===oa.size&&window.addEventListener("storage",oh),oa.add(e),ou(),()=>{oa.delete(e),0===oa.size&&window.removeEventListener("storage",oh)}}function of(e){let t=ou(),n=oo.filter(n=>t[n]!==e[n]);if(n.length){for(let t of(ol=e,oc(e),n))try{e[t]===ot[t]?window.localStorage.removeItem(oe[t]):window.localStorage.setItem(oe[t],String(e[t]))}catch{}op()}}function og(e,t){of({...ou(),[e]:or(t)})}function ox(e,t){of({...ou(),[`${e}Weight`]:on(t)})}function ov(e){of({...ou(),[e]:"",[`${e}Weight`]:400})}function ob(){return{...(0,i.useSyncExternalStore)(om,ou,()=>ot),setFontPreference:og,setFontWeight:ox,resetFontPreference:ov}}function oy(e){let{active:t,onSelect:n,children:s}=e,[o,l]=(0,i.useState)(!1);return(0,r.jsx)("div",{onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{background:t?"var(--bg-selected)":o?"var(--bg-hover)":"transparent",transition:"background 0.1s"},children:(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":t,onClick:n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0,padding:"7px 12px",border:"none",background:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:t?600:400,textAlign:"left",whiteSpace:"nowrap"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),s]})})}function oj(e){let t,n,s,o,l,a,d,c,u,p,h,{options:m,value:f,onChange:g,onReselect:x,onClear:v,emptyLabel:b,selectedLabel:y,disabled:j=!1,busy:k=!1,isAutoSelection:w=!1,ariaLabel:S,variant:C="toolbar",placement:N="up",recent:E,thinkingLevel:I,onSelectRecent:$}=e,{t:T}=(0,tn.s)(),M=tp(),R=(0,i.useRef)(null),A=(0,i.useRef)(null),[L,z]=(0,i.useState)(!1),[P,W]=(0,i.useState)(null),[O,F]=(0,i.useState)(""),D=j||k,B=(t=O.trim().toLocaleLowerCase())?m.filter(e=>`${e.name} ${e.modelId} ${e.provider}/${e.modelId}`.toLocaleLowerCase().includes(t)):m,H=m.length>8,_=[];for(let e of B){let t=_.find(t=>t.provider===e.provider);t?t.options.push(e):_.push({provider:e.provider,options:[e]})}let U=$&&!O.trim()?(E??[]).map(e=>({entry:e,name:m.find(t=>t.provider===e.provider&&t.modelId===e.modelId)?.name??e.modelId,active:e.provider===f?.provider&&e.modelId===f?.modelId&&e.thinkingLevel===(I??null)})):[],K=y??(f?m.find(e=>e.modelId===f.modelId&&e.provider===f.provider)?.name??f.modelId:b??T(m.length>0?"chat.selectModel":"chat.noModels"));(0,i.useEffect)(()=>{let e=e=>{R.current&&!R.current.contains(e.target)&&A.current&&!A.current.contains(e.target)&&(z(!1),F(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{if(!L)return;let e=()=>{let e=R.current?.querySelector("button")?.getBoundingClientRect();e?.height&&W({top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width})},t=window.visualViewport,n=new MutationObserver(e);return n.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-keyboard-open"]}),window.addEventListener("resize",e),t?.addEventListener("resize",e),t?.addEventListener("scroll",e),()=>{n.disconnect(),window.removeEventListener("resize",e),t?.removeEventListener("resize",e),t?.removeEventListener("scroll",e)}},[L]),(0,i.useEffect)(()=>{D&&(z(!1),F(""))},[D]);let q="field"===C?{display:"flex",alignItems:"center",gap:7,width:"100%",minWidth:0,height:34,padding:"0 9px",overflow:"hidden",border:"1px solid var(--border)",borderRadius:5,background:D?"var(--bg-panel)":"var(--bg)",color:D?"var(--text-dim)":"var(--text)",cursor:D?"default":"pointer",fontSize:12,textAlign:"left"}:{display:"flex",alignItems:"center",justifyContent:M?"flex-start":void 0,gap:6,width:M?"100%":void 0,maxWidth:M?"100%":220,height:32,padding:M?"8px 10px":"8px 12px",overflow:"hidden",border:"none",borderRadius:9,background:L?"var(--bg-hover)":"none",color:"var(--text-muted)",cursor:D?"not-allowed":"pointer",fontSize:12,opacity:D?.5:1,transition:"background 0.12s, color 0.12s"};return(0,r.jsxs)("div",{ref:R,className:`model-selector is-${C}${D?" is-disabled":""}`,style:{position:"relative",width:"field"===C||M?"100%":void 0,minWidth:0,flex:"toolbar"===C&&M?"1 1 auto":void 0},onKeyDown:e=>{"Escape"===e.key&&L&&(e.preventDefault(),e.stopPropagation(),F(""),z(!1))},children:[(0,r.jsxs)("button",{type:"button","aria-label":S,"aria-haspopup":"listbox","aria-expanded":L,"aria-busy":k||void 0,disabled:D,title:k?T("chat.switchingModel"):D?K:T(m.length>0||v?"chat.changeModel":"chat.noAvailableModels"),style:q,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();W({top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width}),z(e=>(e&&F(""),!e))},onMouseEnter:e=>{D||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{if(D){e.currentTarget.style.background="field"===C?"var(--bg-panel)":"none",e.currentTarget.style.color="field"===C?"var(--text-dim)":"var(--text-muted)";return}e.currentTarget.style.background=L?"var(--bg-hover)":"field"===C?"var(--bg)":"none",e.currentTarget.style.color="field"===C?"var(--text)":"var(--text-muted)"},children:[k?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:K}),"field"===C&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),L&&P&&(n=window.visualViewport?.offsetTop??0,s=window.visualViewport?.height??window.innerHeight,o=window.visualViewport?.width??window.innerWidth,a=(l=Math.min(P.top-6,n+s-8))-n-8,d=n+s-P.bottom-6-8,u=Math.max(120,Math.min((c="up"===N||a>d)?a:d,.6*s)),p=c?{top:l,transform:"translateY(-100%)"}:{top:P.bottom+6},h=M?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:P.left,width:"max-content",minWidth:P.width,maxWidth:Math.max(P.width,o-P.left-8)},(0,r.jsxs)("div",{ref:A,role:"listbox","aria-label":S,style:{position:"fixed",...p,...h,zIndex:500,display:"flex",flexDirection:"column",maxHeight:u,overflow:"hidden",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:c?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:[H&&(0,r.jsx)("div",{style:{flexShrink:0,padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:O,onChange:e=>F(e.target.value),placeholder:T("chat.filterModels"),"aria-label":T("chat.filterModels"),autoFocus:!M,autoComplete:"off",spellCheck:!1,style:{boxSizing:"border-box",width:"100%",minWidth:220*!M,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[v&&!O.trim()&&(0,r.jsx)(oy,{active:!f,onSelect:()=>{z(!1),F(""),v()},children:(0,r.jsx)(ow,{label:b??T("i18n.default")})}),U.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:ok(!!v),children:T("chat.recentModels")}),U.map(e=>{let{entry:t,name:n,active:i}=e;return(0,r.jsxs)(oy,{active:i,onSelect:()=>{z(!1),F(""),!i&&$?.(t)},children:[(0,r.jsx)(ow,{label:n}),(0,r.jsxs)("span",{style:{flexShrink:0,marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,fontWeight:400},children:[t.provider," \xb7 ",t.thinkingLevel??"auto"]})]},`${t.provider}:${t.modelId}:${t.thinkingLevel??""}`)})]}),0===_.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:T(O.trim()?"chat.noMatchingModels":"chat.noAvailableModels")}):_.map((e,t)=>(0,r.jsxs)("div",{children:[(_.length>1||U.length>0)&&(0,r.jsx)("div",{style:ok(t>0||!!v||U.length>0),children:e.provider}),e.options.map(e=>(0,r.jsx)(oy,{active:e.modelId===f?.modelId&&e.provider===f?.provider,onSelect:()=>{let t;return t=e.modelId===f?.modelId&&e.provider===f?.provider,void(z(!1),F(""),!t||w?g(e.provider,e.modelId):x?.(e.provider,e.modelId))},children:(0,r.jsx)(ow,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function ok(e){return{padding:"6px 12px 4px",borderTop:e?"1px solid var(--border)":"none",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:0,textTransform:"uppercase"}}function ow(e){let{label:t}=e;return(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let oS=["configured","chat-only","read-only","default","full"],oC={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},oN=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function oE(e,t,n){return t<=0?0:((e+n)%t+t)%t}function oI(e,t,n,r){e.setRangeText(r,t,n,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))}function o$(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:r.length,s=e.selectionStart,o=e.selectionEnd;if(e.focus(),s===o&&t<=s&&n>=o){let i=e.value.length-(n-t)+r.length;for(let n=s-t;n>0&&e.selectionStart>t&&document.execCommand("delete");n--);if(document.execCommand("insertText",!1,r))for(let t=n-o;t>0&&e.value.length>i&&document.execCommand("forwardDelete");t--);else oI(e,t,e.selectionStart+(n-o),r)}else e.setSelectionRange(t,n),document.execCommand("insertText",!1,r)||oI(e,t,n,r);i!==r.length&&e.setSelectionRange(t+i,t+i)}function oT(e){let t=e.scrollTop??0,n=("number"==typeof e.selectionEnd?e.selectionEnd:e.value.length)>=e.value.length||e.scrollHeight>e.clientHeight&&t+e.clientHeight>=e.scrollHeight-4;e.style.height="auto",e.style.height=`${e.value?Math.min(e.scrollHeight,200):e.clientHeight}px`,e.style.overflowY=e.value&&e.scrollHeight>e.clientHeight?"auto":"hidden",e.scrollTop=n?e.scrollHeight:t}function oM(e,t){let n=null,r=()=>{n=null,t(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8;return Math.max(0,Math.floor(e-t-n))}(e.getBoundingClientRect().bottom,function(e){let t=window.visualViewport?.offsetTop??0;for(let n=e.parentElement;n;n=n.parentElement){let e=window.getComputedStyle(n).overflowY;("auto"===e||"scroll"===e||"hidden"===e||"clip"===e)&&(t=Math.max(t,n.getBoundingClientRect().top+n.clientTop))}return t}(e)))},i=()=>{null!==n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r();let s=e.parentElement,o=s?.parentElement,l="u">typeof ResizeObserver&&s?new ResizeObserver(i):null;s&&l?.observe(s),o&&l?.observe(o);let a=window.visualViewport;return a?.addEventListener("resize",i),a?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{l?.disconnect(),a?.removeEventListener("resize",i),a?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let oR=["auto","off","minimal","low","medium","high","xhigh","max"],oA={auto:"chat.thinkingUseDefault",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"};function oL(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let oz=[{name:"compact",description:"chat.commandCompact",source:"builtin"},{name:"auto-compact",description:"chat.commandAutoCompact",source:"builtin"},{name:"reload",description:"chat.commandReload",source:"builtin"},{name:"name",description:"chat.commandName",source:"builtin"},{name:"session",description:"chat.commandSession",source:"builtin",availableWhileStreaming:!0},{name:"context",description:"command.contextDescription",source:"builtin",availableWhileStreaming:!0},{name:"copy",description:"chat.commandCopy",source:"builtin",availableWhileStreaming:!0},{name:"clone",description:"chat.commandClone",source:"builtin"},{name:"side",description:"chat.commandSide",source:"builtin",availableWhileStreaming:!0},{name:"share",description:"chat.commandShare",source:"builtin",availableWhileStreaming:!0},{name:"export",description:"command.exportDescription",source:"builtin",availableWhileStreaming:!0},{name:"import",description:"chat.commandImport",source:"builtin"},{name:"hotkeys",description:"chat.commandHotkeys",source:"builtin",availableWhileStreaming:!0}];function oP(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return oz.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let oW=["builtin","extension","prompt","skill"],oO={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},oF={builtin:0,extension:1,prompt:2,skill:3};function oD(e,t){return"builtin"===e.source?t(e.description):e.description??""}function oB(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function oH(e){return{data:e.data,mimeType:e.mimeType}}function o_(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function oU(e){return(e??[]).filter(sj).slice(0,10).map(o_)}function oK(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function oq(e){let{kind:t,text:n}=e;return(0,r.jsxs)("div",{title:n,style:{display:"flex",alignItems:"center",gap:8,padding:"3px 10px",fontSize:12,color:"var(--text-muted)",minWidth:0},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",padding:"1px 7px",borderRadius:999,border:`1px solid ${"steer"===t?"color-mix(in srgb, var(--accent) 45%, transparent)":"var(--border)"}`,color:"steer"===t?"var(--accent)":"var(--text-dim)"},children:t}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]})}function oV(e){let{tone:t,title:n,body:i,onClose:s}=e,{t:o}=(0,tn.s)(),l="error"===t?"239,68,68":"234,179,8";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid rgba(${l},0.3)`,borderRadius:6,background:`rgba(${l},0.07)`,color:`rgb(${l})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:n}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:i})]}),s&&(0,r.jsx)("button",{type:"button",onClick:s,"aria-label":o("sidebar.dismiss"),style:{flexShrink:0,background:"none",border:"none",padding:"0 2px",cursor:"pointer",color:"inherit",opacity:.7,fontSize:13,lineHeight:1},children:"\xd7"})]})}function oZ(e){let{cwd:t}=e,{t:n}=(0,tn.s)();return t?(0,r.jsx)(oV,{tone:"error",title:n("chat.cwdMissingTitle"),body:n("chat.cwdMissingBody",{cwd:t})}):null}function oJ(e){let{error:t}=e,{t:n}=(0,tn.s)();return t?(0,r.jsx)(oV,{tone:"error",title:n("chat.modelError"),body:t}):null}function oG(e){let{warnings:t}=e,{t:n}=(0,tn.s)();return t&&0!==t.length?(0,r.jsx)(oV,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}let oY=(0,i.memo)((0,i.forwardRef)(function(e,t){let n,s,o,l,a,{onSend:d,onAbort:c,onSteer:u,onSideChat:p,onFollowUp:h,isStreaming:m,model:f,isAutoModelSelection:g,modelNames:x,modelList:v,modelError:b,missingCwd:y,modelScopeWarnings:j,onModelChange:k,modelSwitching:w,recentModels:S,onSelectRecentModel:C,onCompact:N,onAbortCompaction:E,isCompacting:I,compactError:$,onDismissCompactError:T,compactResult:M,toolPreset:R,onToolPresetChange:A,thinkingLevel:L,isAutoThinkingSelection:z=!1,onThinkingLevelChange:P,availableThinkingLevels:W,thinkingLevelMap:O,retryInfo:F,queuedMessages:D,inputHistory:B=[],onRecallQueue:H,slashCommands:_,slashCommandsLoading:U,onLoadSlashCommands:K,onBuiltinCommand:q,soundEnabled:V,onSoundToggle:Z,onAudioUnlock:J,onPromptWithStreamingBehavior:G,draftKey:Y,cwd:X,onAttachFiles:Q,compact:ee=!1}=e,{t:et}=(0,tn.s)(),{fontSize:en}=s9(),{ui:er,uiWeight:ei}=ob(),es=tp(),eo=sV(),[el,ea]=(0,i.useState)(()=>Y?sN(Y)?.value??"":""),[ed,ec]=(0,i.useState)(!1),[eu,ep]=(0,i.useState)(!1),[eh,em]=(0,i.useState)(!1),[ef,eg]=(0,i.useState)(()=>Y?oU(sN(Y)?.images):[]),ex=el.trimStart(),ev=0===ef.length&&ex.startsWith("!"),eb=ev&&ex.startsWith("!!"),[ey,ej]=(0,i.useState)(!1),[ek,ew]=(0,i.useState)(0),[eS,eC]=(0,i.useState)(null),[eN,eE]=(0,i.useState)(null),[eI,e$]=(0,i.useState)(!1),[eT,eM]=(0,i.useState)(null),[eR,eA]=(0,i.useState)(0),[eL,ez]=(0,i.useState)(!1),[eP,eW]=(0,i.useState)(!1),[eO,eF]=(0,i.useState)(0),[eD,eB]=(0,i.useState)(!1),eH=(0,i.useRef)(!1),[e_,eU]=(0,i.useState)(null),[eK,eq]=(0,i.useState)(!1),[eV,eZ]=(0,i.useState)(null),[eJ,eG]=(0,i.useState)(null),eY=X&&eJ?.cwd===X?eJ.values:{},eX=(0,i.useRef)(null),eQ=(0,i.useRef)(null),e0=(0,i.useRef)(null),e1=(0,i.useRef)(null),e2=(0,i.useRef)(null),e4=(0,i.useRef)(null),e8=(0,i.useRef)(!1),e3=(0,i.useRef)(0),e5=(0,i.useRef)(!1),e6=(0,i.useRef)(null),e9=(0,i.useRef)([]),e7=(0,i.useRef)(null),te=(0,i.useRef)([]),tt=(0,i.useRef)([]),tr=(0,i.useRef)(null),ti=(0,i.useRef)(null),ts=(0,i.useRef)(Y),to=(0,i.useRef)(el),tl=(0,i.useRef)(ef),ta=(0,i.useRef)(0);to.current=el,tl.current=ef,(0,i.useImperativeHandle)(t,()=>({insertIfEmpty(e){let t=eX.current;(t?t.value:el).trim()||(to.current=e,ea(e),eE(null),requestAnimationFrame(()=>{t&&(t.focus(),oT(t))}))},replaceMessage(e){var t,n,r;let i=eX.current;if(t=i?i.value:el,n=tl.current.length,r=ta.current,t.trim()||0!==n||0!==r)return;let s="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),o=oU("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return sj(r)?[r]:[]}));to.current=s,tl.current=o,ea(s),eE(null),eW(!1),eg(e=>(e.forEach(oK),o)),requestAnimationFrame(()=>{i&&(i.focus(),oT(i))})},prependText(e){if(!e.trim())return;let t=eX.current,n=[e,t?t.value:el].filter(e=>e.trim()).join("\n\n");to.current=n,ea(n),eE(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),oT(t))})},rekeyDraft(e,t){if(e===t)return;if(ts.current!==e)return void sR(e,t);let n={value:to.current,images:tl.current.map(oH)},r=sR(e,t,n)??{value:"",images:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType);if(ts.current=t,i)return;let s=oU(r.images);to.current=r.value,tl.current=s,ea(r.value),eg(e=>(e.forEach(oK),s)),eE(null),eW(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=ts.current,i=n??r,s=i===r,o=!s&&i?sN(i):null,l=sT(e,t,s?to.current:o?.value??"",s?tl.current.map(oH):o?.images??[]);if(i&&sE(i,l),!s)return;let a=t?.length?[...oU(t).slice(0,Math.max(0,10-tl.current.length)),...tl.current].slice(0,10):tl.current;to.current=l.value,tl.current=a,ea(t=>{let n=s$(e,t);return to.current=n,n}),eE(null),eW(!1),t?.length&&eg(e=>{let n=Math.max(0,10-e.length),r=oU(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tl.current=i,i}),requestAnimationFrame(()=>{let e=eX.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),oT(e))})},focus(){let e=eX.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length))},insertText(e){let t=eX.current;if(!t)return void ea(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n);o$(t,n,r,(i.length>0&&!i.endsWith(" ")?" ":"")+e),eE(null)},insertQuote(e){let t=eX.current;if(!t)return void ea(t=>t+ir(t)+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length;o$(t,n,r,ir(t.value.slice(0,n))+e),eE(null)},addImages(e){td(e)}}));let td=(0,i.useCallback)(async e=>{if(ee)return;let t=Math.max(0,10-tl.current.length-ta.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){ta.current+=n.length;try{let e=await Promise.all(n.map(async e=>{var t;return{...await (t=e.type,new Promise((n,r)=>{let i=new FileReader;i.onload=()=>{let e="string"==typeof i.result?i.result.split(",")[1]:void 0;e?n({data:e,mimeType:t}):r(Error("Failed to read image"))},i.onerror=r,i.readAsDataURL(e)})),previewUrl:URL.createObjectURL(e)}}));eg(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(oK);let r=[...t,...n];return tl.current=r,r})}finally{ta.current-=n.length}}},[ee]),tc=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",Q?Q(t):td(t)},[Q,td]),tu=(0,i.useCallback)(e=>{eg(t=>{let n=[...t],[r]=n.splice(e,1);return r&&oK(r),tl.current=n,n})},[]),th=(0,i.useCallback)(()=>{tl.current=[],eg(e=>(e.forEach(oK),[]))},[]),tm=(0,i.useCallback)(()=>{to.current="",ea(""),eE(null),eW(!1),Y&&sI(Y),ts.current&&ts.current!==Y&&sI(ts.current),th(),eX.current&&(eX.current.style.height="auto")},[th,Y]);(0,i.useEffect)(()=>{Y&&ts.current===Y&&sE(Y,{value:el,images:ef.map(oH)})},[ef,Y,el]),(0,i.useEffect)(()=>{let e=ts.current;if(e===Y)return;e&&sE(e,{value:to.current,images:tl.current.map(oH)});let t=Y?sN(Y):null;ts.current=Y;let n=t?.value??"",r=oU(t?.images);to.current=n,tl.current=r,ea(n),eE(null),eW(!1),eg(e=>(e.forEach(oK),r))},[Y]);let tf=(0,i.useCallback)(()=>{let e=eX.current;e&&(e.value?oT(e):(e.style.height="auto",e.style.overflowY="hidden"))},[]);(0,i.useLayoutEffect)(tf,[el,en,er,ei,tf]),(0,i.useEffect)(()=>{let e=eX.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tf())});return n.observe(e),()=>n.disconnect()},[tf]),(0,i.useEffect)(()=>{let e=eX.current;if(!e)return;let t=t=>{if("insertLineBreak"!==t.inputType||t.isComposing)return;let n=function(e,t,n){let r;if(t!==n)return null;let i=e.lastIndexOf("\n",t-1)+1,s=e.indexOf("\n",t),o=-1===s?e.length:s,l=e.slice(i,o),a=function(e){if(sP.test(e))return null;let t=sA.exec(e);if(t)return{indent:t[1],marker:t[2],number:null,delimiter:"",spacing:t[3],task:void 0!==t[4],length:t[0].length};let n=sL.exec(e)??sz.exec(e);return n?{indent:n[1],marker:"",number:n[2],delimiter:n[3],spacing:n[4],task:void 0!==n[5],length:n[0].length}:null}(l);return!a||t-i<a.length||function(e){let t=null;for(let n of e.split("\n")){let e=sW.exec(n)?.[1];e&&(null===t?t=e:e[0]===t[0]&&e.length>=t.length&&n.trim()===e&&(t=null))}return null!==t}(e.slice(0,i))?null:""===l.slice(a.length).trim()?{start:i,end:o,text:""}:{start:t,end:t,text:`
8
+ ${r=null===a.number?a.marker:`${String(Number(a.number)+1).padStart(a.number.length,"0")}${a.delimiter}`,`${a.indent}${r}${a.spacing}${a.task?"[ ] ":""}`}`}}(e.value,e.selectionStart,e.selectionEnd);n&&(t.preventDefault(),e.setSelectionRange(n.start,n.end),document.execCommand(n.text?"insertText":"delete",!1,n.text))};return e.addEventListener("beforeinput",t),()=>e.removeEventListener("beforeinput",t)},[]),(0,i.useEffect)(()=>()=>{tl.current.forEach(oK)},[]);let tg=(0,i.useCallback)(async e=>{if(ef.length||!e.startsWith("/")||!q)return!1;if(eH.current)return!0;eH.current=!0,eB(!0);try{var t,n;let r=await q(e);if(!r.handled)return!1;return r.error||(t=to.current,n=tl.current.length,0!==n||t.trim()!==e)||tm(),!0}finally{eH.current=!1,eB(!1)}},[ef.length,tm,q]),tx=(0,i.useCallback)(async()=>{var e;let t=el.trim();(t||ef.length)&&(J?.(),(!m||oP(e=t)||sF(e))&&await tg(t)||m||(tm(),d(t,ef.length?ef:void 0)))},[el,ef,m,tg,d,tm,J]),tv=!ee&&el.startsWith("/")&&!/\s/.test(el.slice(1))?el.slice(1).toLowerCase():null,tb=(()=>{var e;let t,n;return null===tv?[]:(e=[...m?oz.filter(e=>e.availableWhileStreaming):oz,..._??[]],((n=(t=e.map(e=>{let t,n;return{command:e,rank:(t=e.name.toLowerCase(),(n="skill"===e.source&&t.startsWith("skill:")?t.slice(6):t)===tv||t===tv?0:n.startsWith(tv)||t.startsWith(tv)?1:t.includes(tv)?2:3)}})).filter(e=>{let{rank:t}=e;return t<3})).length>0?n:t.filter(e=>{let{command:t}=e;return oD(t,et).toLowerCase().includes(tv)})).sort((e,t)=>e.rank-t.rank||oF[e.command.source]-oF[t.command.source]||oN.compare(e.command.name,t.command.name)).map(e=>{let{command:t}=e;return t}))})(),{commands:ty,groups:tj}=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",r=0,i=oW.map(i=>{let s=e.filter(e=>e.source===i),o="skill"!==i||n?s:[...s.filter(e=>!oB(e,t)),...s.filter(e=>oB(e,t))];return{source:i,items:o.map(e=>({command:e,index:r++}))}}).filter(e=>e.items.length>0);return{commands:i.flatMap(e=>e.items.map(e=>{let{command:t}=e;return t})),groups:i}}(tb,eY,tv??""),tk=1===tb.length?et(tv?"chat.match":"chat.command"):et(tv?"chat.matches":"chat.commands",{count:tb.length}),tw=!!el.trim()||ef.length>0,tS=ee||es&&m,tC=ef.length>0&&!function(e,t){if(!e)return!0;let n=t?.find(t=>t.provider===e.provider&&t.id===e.modelId);return!n||!n.input||n.input.includes("image")}(f,v)&&!eL;(0,i.useEffect)(()=>{0===ef.length&&ez(!1)},[ef.length]);let tN=(0,i.useCallback)((e,t)=>{if(!X)return void eE(null);let n=t??e.length;eE(t_(e.slice(0,n)))},[X]),tE=eN?.query??null,tI=i.useMemo(()=>null!==tE&&e_&&e_.cwd===X?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:20,r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:tK(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:tK(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||tU(e.entry.path)-tU(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(e_.entries,tE):[],[tE,e_,X]),t$=!!(tE&&e_?.truncated&&e_.cwd===X);(0,i.useEffect)(()=>{if(!t$||!X||!tE)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(tE)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>eZ({cwd:X,query:tE,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[t$,tE,X]);let tT=t$&&null!==eV&&eV.cwd===X&&eV.query===tE,tM=tT?eV.matches:tI,tR=null===eN?null:`${eN.start}:${+!!eN.quoted}:${eN.query}`;(0,i.useEffect)(()=>{if(null===tR){e$(!1),eA(0);return}e$(!0),eA(0)},[tR]);let tL=null!==eN;(0,i.useEffect)(()=>{if(!tL||!X)return;let e=tr.current;e&&e.cwd===X&&Date.now()-e.fetchedAt<1e4||ti.current===X||(ti.current=X,eq(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eU({cwd:X,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>tU(e.path)-tU(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tr.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tr.current=null}).finally(()=>{ti.current=null,eq(!1)}))},[tL,X]);let tz=(0,i.useCallback)(e=>{if(!eN)return;let t=eX.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eN.quoted&&'"'===t.value[n]?1:0),i=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,eN.quoted),s=eN.start+i.cursorOffset;o$(t,eN.start,r,i.text,i.cursorOffset),eE(t_(t.value.slice(0,s)))},[eN]);(0,i.useEffect)(()=>{eR>=tM.length&&eA(Math.max(0,tM.length-1))},[tM.length,eR]),(0,i.useEffect)(()=>{te.current.length=tM.length},[tM.length]),(0,i.useEffect)(()=>{eI&&te.current[eR]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eR,eI]),(0,i.useEffect)(()=>{eO>=B.length&&eF(Math.max(0,B.length-1))},[B.length,eO]),(0,i.useEffect)(()=>{tt.current.length=B.length},[B.length]),(0,i.useEffect)(()=>{eP&&tt.current[eO]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eO,eP]);let tP=(0,i.useCallback)(e=>{ea(e),eW(!1),eF(0),eE(null),requestAnimationFrame(()=>{let t=eX.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),oT(t))})},[]),tW=(0,i.useCallback)(e=>{let t=`/${e.name} `;ea(t),ej(!1),ew(0),requestAnimationFrame(()=>{let e=eX.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),oT(e))})},[]),tF=(0,i.useCallback)(()=>{let e=el.trim();e&&!ef.length&&p&&(tm(),p(e))},[el,ef,p,tm]),tD=(0,i.useCallback)(e=>{let t=el.trim();if(!t&&!ef.length)return;J?.();let n=ef.length?ef:void 0,r=()=>{if(t.startsWith("/")&&G){tm(),G(t,"steer"===e?"steer":"followUp",n);return}tm(),"steer"===e&&u?u(t,n):"followup"===e&&h&&h(t,n)};!ef.length&&q&&oP(t)?tg(t):!ef.length&&q&&sF(t)?tg(t).then(e=>{e||r()},()=>r()):r()},[el,ef,q,G,u,h,tm,J,tg]),tH=(0,i.useCallback)(e=>{let t=ty.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,ek-1);if("right"===e)return Math.min(t,ek+1);let n=e9.current[ek];if(!n)return"down"===e?Math.min(t,ek+1):Math.max(0,ek-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,o=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===ek)continue;let t=e9.current[n];if(!t)continue;let r=t.getBoundingClientRect(),a=r.top+r.height/2-s;if("down"===e?a<=4:a>=-4)continue;let d=1e3*Math.abs(a)+Math.abs(r.left+r.width/2-i);d<l&&(o=n,l=d)}return o>=0?o:"down"===e?Math.min(t,ek+1):Math.max(0,ek-1)},[ty.length,ek]),tq=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=es||"ctrlEnter"===eo?n&&(e.ctrlKey||e.metaKey):n,i=es?r:n,s=Date.now()-e3.current<100,o=e8.current||t.isComposing||229===t.keyCode;if(i&&(o||s)){s&&e.preventDefault();return}if(eP&&!o){if("ArrowDown"===e.key){e.preventDefault(),eF(e=>Math.min(Math.max(0,B.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eF(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eW(!1);return}if(("Tab"===e.key||i)&&B[eO]){e.preventDefault(),tP(B[eO]);return}}if(ey&&null!==tv){if("ArrowDown"===e.key){e.preventDefault(),ew(tH("down"));return}if("ArrowUp"===e.key){e.preventDefault(),ew(tH("up"));return}if("ArrowRight"===e.key){e.preventDefault(),ew(tH("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),ew(tH("left"));return}if("Escape"===e.key){e.preventDefault(),ej(!1);return}let t=ty[ek];if("Tab"===e.key&&t){e.preventDefault(),tW(t);return}if(i&&t){e.preventDefault(),r&&function(e,t,n){if("builtin"===t.source)return"builtin"===t.source&&e.trim()===`/${t.name}`&&(!n||!0===t.availableWhileStreaming);return sO(t)&&sF(e)}(el,t,m)?(ej(!1),tx()):tW(t);return}}if(eI&&null!==eN&&!o){if("ArrowDown"===e.key){e.preventDefault(),eA(e=>oE(e,tM.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eA(e=>oE(e,tM.length,-1));return}if("Escape"===e.key){e.preventDefault(),e$(!1);return}if(("Tab"===e.key||i)&&tM[eR]){e.preventDefault(),tz(tM[eR]);return}}if("ArrowUp"===e.key&&!o&&!m&&B.length>0&&0===el.trim().length){e.preventDefault(),ej(!1),e$(!1),eF(B.length-1),eW(!0);return}if("Escape"===e.key&&!o&&m&&c){e.preventDefault(),c();return}r&&(e.preventDefault(),m&&(u||h)?tD(e.altKey&&h||!u?"followup":"steer"):tx())},[es,eo,m,u,h,c,ey,tv,ty,ek,tW,tD,tx,tH,eI,eN,tM,eR,tz,eP,B,eO,tP,el]),tV=(0,i.useCallback)(()=>{let e=eX.current;e&&oT(e)},[]),tZ=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!ee&&t.length){e.preventDefault(),td(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),s=function(e,t){let n="",r=0,i=!1;for(let{label:s,href:o,occurrence:l}of t){if(!s||!o)continue;let t=0;for(let n=0;n<=l&&!((t=e.indexOf(s,n?t+s.length:0))<0);n++);if(t<r)continue;let a=s.replace(/([\\[\]])/g,"\\$1"),d=o.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${d})`,r=t+s.length,i=!0}return i?n+e.slice(r):null}(r,Array.from(i.querySelectorAll("a[href]"),e=>{let t=e.textContent??"",n=i.createRange();return n.setStart(i.body,0),n.setEndBefore(e),{label:t,href:e.getAttribute("href")?.trim()??"",occurrence:t?n.toString().split(t).length-1:0}}));if(null===s)return;let o=e.currentTarget,l=o.selectionStart,a=o.value.slice(0,l)+s+o.value.slice(o.selectionEnd);e.preventDefault(),to.current=a,ea(a),eW(!1),tN(a,l+s.length),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(l+s.length,l+s.length)})},[ee,td,tN]);(0,i.useEffect)(()=>{if(null===tv){ej(!1),ew(0),e5.current=!1;return}ej(!0),ew(0),!e5.current&&K&&(e5.current=!0,Promise.resolve(K()).catch(()=>{e5.current=!1}))},[tv,K]),(0,i.useEffect)(()=>{if(!ey||!X)return;let e=!1;return eG({cwd:X,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;eG({cwd:X,values:n})}).catch(()=>{e||eG({cwd:X,values:{}})}),()=>{e=!0}},[ey,X]),(0,i.useEffect)(()=>{ek>=ty.length&&ew(Math.max(0,ty.length-1))},[ty.length,ek]),(0,i.useEffect)(()=>{e9.current.length=ty.length},[ty.length]),(0,i.useEffect)(()=>{ey&&e9.current[ek]?.scrollIntoView({block:"nearest",inline:"nearest"})},[ek,ey]),(0,i.useLayoutEffect)(()=>{if(!ey||null===tv)return void eC(null);let e=e6.current;if(e)return oM(e,e=>{eC(t=>t===e?t:e)})},[ey,tv]),(0,i.useLayoutEffect)(()=>{if(!eI||null===eN)return void eM(null);let e=e7.current;if(e)return oM(e,e=>{eM(t=>t===e?t:e)})},[eI,eN]);let tJ=v&&v.length>0?v.map(e=>({provider:e.provider,modelId:e.id,name:e.name})):Object.entries(x??{}).map(e=>{let[t,n]=e;return{provider:f?.provider??"unknown",modelId:t,name:n}}),tG=M?Math.max(0,M.tokensBefore-M.estimatedTokensAfter):0,tY=M?`${M.reason&&"manual"!==M.reason?`${M.reason[0].toUpperCase()}${M.reason.slice(1)} `:et("chat.compacted")} ${oL(M.tokensBefore)} -> ${oL(M.estimatedTokensAfter)} tokens (${et("chat.tokensSaved",{saved:oL(tG)})})`:null,tX=L&&"auto"!==L?L:null,tQ="auto"!==(n=tX??"auto")&&O?O[n]??n:n,t0=Object.entries(oC).find(e=>{let[,t]=e;return t===(R??"configured")})?.[0]??"configured",t1="chat-only"===t0?et("chat.chatOnly"):t0;(0,i.useEffect)(()=>{let e=e=>{eQ.current&&!eQ.current.contains(e.target)&&ec(!1),e0.current&&!e0.current.contains(e.target)&&ep(!1),e1.current&&!e1.current.contains(e.target)&&em(!1),!e2.current||e2.current.contains(e.target)||eX.current?.contains(e.target)||eW(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&ec(!1)},[m]);let t2=(0,i.useRef)(-1/0);(0,i.useLayoutEffect)(()=>{if(m)return()=>{t2.current=performance.now()}},[m]);let t4=e=>{var t,n;return t=e.detail,n=performance.now()-t2.current,t>0&&n<600};return(0,i.useEffect)(()=>{es||em(!1)},[es]),(0,r.jsxs)("fieldset",{disabled:eD,"aria-busy":eD,className:ee?void 0:"chat-input-shell",style:{...ee?{flexShrink:0}:{display:"flex",flexDirection:"column",minHeight:0},minWidth:0,margin:0,border:0,background:"transparent",padding:ee?0:"0 16px 8px",paddingRight:ee?0:es?16:52,opacity:eD?.5:1,transition:"opacity 0.15s"},children:[!ee&&(0,r.jsx)("input",{ref:e4,type:"file",accept:Q?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tc}),(0,r.jsxs)("div",{style:{...ee?void 0:{display:"flex",flexDirection:"column",minHeight:0,width:"100%"},maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(oZ,{cwd:y}),(0,r.jsx)(oJ,{error:b}),(0,r.jsx)(oG,{warnings:j}),tC&&(s=v?.find(e=>e.provider===f?.provider&&e.id===f?.modelId),(0,r.jsx)(oV,{tone:"warning",title:et("chat.imageNotSupportedTitle"),body:et("chat.imageNotSupportedBody",{model:s?.name||f?.modelId||""}),onClose:()=>ez(!0)})),(D?.steering.length??0)+(D?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:72,marginBottom:8,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:et("chat.queued",{count:(D?.steering.length??0)+(D?.followUp.length??0)})}),H&&(0,r.jsxs)("button",{onClick:H,title:et("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),et("chat.recall")]})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(180px, calc(var(--app-viewport-height, 100dvh) * 0.25))",overflowY:"auto",overscrollBehavior:"contain"},children:[D?.steering.map((e,t)=>(0,r.jsx)(oq,{kind:"steer",text:e},`steer-${t}`)),D?.followUp.map((e,t)=>(0,r.jsx)(oq,{kind:"follow-up",text:e},`followup-${t}`))]})]}),F&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(234,179,8,0.08)",border:"1px solid rgba(234,179,8,0.25)",borderRadius:6,fontSize:12,color:"rgba(180,130,0,0.9)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),et("chat.retrying",{attempt:F.attempt,max:F.maxAttempts}),F.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",F.errorMessage]})]}),tY&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(16,185,129,0.08)",border:"1px solid rgba(16,185,129,0.24)",borderRadius:6,fontSize:12,color:"rgba(5,150,105,0.95)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),tY]}),$&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,marginBottom:8,padding:T?"3px 3px 3px 10px":"7px 10px",background:"rgba(239,68,68,0.07)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,padding:T?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:$}),T&&(0,r.jsx)(tA,{onClick:T,title:et("chat.dismissCompactError")})]}),ef.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ef.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(io.k,{src:e.previewUrl,children:(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:6,border:"1px solid var(--border)",display:"block"}})},e.previewUrl),(0,r.jsx)("button",{type:"button",onClick:()=>tu(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},t))}),(0,r.jsxs)("div",{style:{position:"relative",minWidth:0},children:[eP&&B.length>0&&(0,r.jsxs)("div",{ref:e2,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:et("chat.inputHistory"),style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:B.map((e,t)=>{let n=t===eO;return(0,r.jsxs)("button",{ref:e=>{tt.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tP(e)},onMouseEnter:()=>eF(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),ey&&null!==tv&&(0,r.jsxs)("div",{ref:e6,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eS?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eS}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:U?et("chat.loadingCommands"):et("chat.slashCommands",{label:tk})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:et("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:U||0!==tb.length?tj.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:et(oO[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(e=>{let{command:t,index:n}=e,i=n===ek,s=oB(t,eY);return(0,r.jsxs)("button",{ref:e=>{e9.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tW(t)},onMouseEnter:()=>ew(n),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${i?"var(--accent)":"var(--border)"}`,borderRadius:7,background:i?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:i?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:s?"var(--text-dim)":void 0},children:["/",t.name,s&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:et("chat.dormant")})]}),t.description&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:oD(t,et)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:et("chat.noCommands")})})]}),eI&&null!==eN&&(o=eK&&(!e_||e_.cwd!==X),l=1===tM.length?et("chat.match"):et("chat.matches",{count:tM.length}),a=e_?.truncated&&!tT?eN.query?et("chat.searchingAll"):et("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:e7,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eT?"min(48vh, 400px)":`min(48vh, 400px, ${eT}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:o?et("chat.loadingFiles"):et("chat.files",{label:l,hint:a})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:et("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:o||0!==tM.length?tM.map((e,t)=>{let n=t===eR,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{te.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tz(e)},onMouseEnter:()=>eA(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(tO,{size:14}):tB(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:s}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:t$&&!tT?et("chat.searching"):et("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:tS?void 0:"chat-composer-row",style:{minWidth:0,display:"flex",flexDirection:tS?"column":"row",gap:8,alignItems:tS?"stretch":"center",background:"var(--bg)",border:ee?"none":`1px solid ${ev?"var(--tool-bg)":m&&(u||h)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!ee,padding:ee?0:es?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:ee?"none":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{ref:eX,className:"chat-input-textarea","aria-label":ee?et("chat.askInSideChat"):void 0,value:el,onChange:e=>{to.current=e.target.value,ea(e.target.value),eW(!1),tN(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tN(t.value,t.selectionStart)},onKeyDown:tq,onCompositionStart:()=>{e8.current=!0},onCompositionEnd:e=>{e8.current=!1,e3.current=Date.now();let t=e.currentTarget;tN(t.value,t.selectionStart)},onInput:tV,onPaste:tZ,placeholder:I?et("chat.compactingPlaceholder"):m&&(u||h)?et("chat.steerPlaceholder"):m?et("chat.agentPlaceholder"):et("chat.messagePlaceholder"),rows:1,style:{flex:tS?"none":1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.6,fontFamily:"inherit",minHeight:ee?96:24,maxHeight:200,overflow:"auto"}}),m?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[p&&(0,r.jsx)("button",{type:"button",onClick:tF,disabled:!el.trim()||ef.length>0,title:et("chat.sideChatHint"),"aria-label":et("chat.sideChat"),className:`bg-transparent ${el.trim()&&!ef.length?"cursor-pointer text-text-muted hover:bg-bg-hover hover:text-text":"cursor-not-allowed text-text-dim"}`,style:{width:38,display:"grid",placeItems:"center",padding:0,border:"1px solid var(--border)",borderRadius:8,transition:"background 0.12s"},children:(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}),(0,r.jsx)("path",{d:"M13 8.5v7M9.5 12h7"})]})}),u&&(0,r.jsxs)("button",{onClick:()=>tD("steer"),disabled:!tw,title:et("chat.steerHint"),"aria-label":et("chat.steer"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tw?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tw?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tw?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:et("chat.steer")})]}),h&&(0,r.jsxs)("button",{onClick:()=>tD("followup"),disabled:!tw,title:`${et("chat.followUpHint")} (${es?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-label":et("chat.followUp"),"aria-keyshortcuts":es?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tw?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tw?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tw?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:et("chat.followUp")})]})]}):(0,r.jsxs)("button",{onClick:tx,disabled:!el.trim()&&!ef.length,title:et("chat.send"),"aria-label":et("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...es?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:el.trim()||ef.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:el.trim()||ef.length?"var(--accent-contrast)":"var(--text-dim)",cursor:el.trim()||ef.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:el.trim()||ef.length?"0 1px 3px color-mix(in srgb, var(--accent) 25%, transparent)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),!es&&et("chat.send")]})]})]}),ev&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eb?"var(--text-muted)":"var(--accent)",marginTop:4},children:[et("chat.shell")," \xb7 ",eb?et("chat.outputLocal"):et("chat.outputModel")]}),!ee&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:es?4:8,display:es?"grid":"flex",gridTemplateColumns:es?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:es?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>e4.current?.click(),title:et("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:ef.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=ef.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ef.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(tJ.length>0||f||b)&&k&&(0,r.jsx)(oj,{options:tJ,value:f,onChange:k,onReselect:k,disabled:m,busy:w,isAutoSelection:g,recent:S,thinkingLevel:tX,onSelectRecent:C})]}),!es&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:e1,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:es?0:"auto"},children:[es&&(0,r.jsx)("button",{type:"button",title:eh?void 0:et("chat.moreControls"),"aria-label":et("chat.moreControls"),"aria-expanded":eh,"aria-hidden":eh||void 0,tabIndex:eh?-1:void 0,onClick:()=>{em(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:32,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:eh?"default":"pointer",fontSize:12,fontWeight:500,visibility:eh?"hidden":"visible",pointerEvents:eh?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eh||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eh||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:et("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:es?eh?"flex":"none":"flex",alignItems:"center",gap:es?1:2,...es?{position:"absolute",right:0,bottom:0,zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"nowrap",justifyContent:"flex-end",border:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:10,background:"color-mix(in srgb, var(--bg-panel) 92%, var(--bg))",boxShadow:"0 8px 24px rgba(0,0,0,0.14)",backdropFilter:"blur(10px)"}:null},children:[P&&(0,r.jsxs)("div",{ref:e0,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>ep(e=>!e),title:m?et("chat.currentReasoning",{level:tQ}):et("chat.changeReasoning",{level:tQ}),"aria-label":et("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:es?"0 6px":"8px 12px",width:es?"auto":void 0,height:32,background:eu?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=eu?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(!es||eh)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:tQ})]}),eu&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...es?{left:0}:{right:0},zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:180},children:oR.filter(e=>!W||"auto"===e||W.includes(e)).map(e=>{let t="auto"===e?z:!z&&tX===e,n=et(oA[e]),i="auto"!==e&&O?O[e]:void 0,s=null!=i&&i!==e?i:e,o=null!=i&&i!==e;return(0,r.jsxs)(oy,{active:t,onSelect:()=>{if(ep(!1),"auto"===e){z||P("auto");return}(!t||z)&&P(e)},children:[(0,r.jsxs)("span",{style:{flex:1},children:[s,o&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:n})]},e)})})]}),!m&&A&&(0,r.jsxs)("div",{ref:eQ,style:{position:es?"static":"relative"},children:[(0,r.jsxs)("button",{onClick:e=>{m||t4(e)||ec(e=>!e)},disabled:m,title:et("chat.changeToolPreset")+`: ${t1}`,"aria-label":et("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:es?"0 6px":"8px 12px",width:es?"auto":void 0,height:32,background:ed?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:m?"not-allowed":"pointer",fontSize:12,opacity:m?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ed?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(!es||eh)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t1})]}),ed&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:es?"calc(100vw - 16px)":void 0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:120},children:oS.map(e=>{let t,n=oC[e],i=(R??"configured")===n;return t="configured"===e?et("chat.configuredTools"):"chat-only"===e?et("chat.chatOnly"):"read-only"===e?et("chat.readOnlyTools",{count:4}):"default"===e?et("chat.builtInTools",{count:4}):et("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{ec(!1),i||A(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!m||I)&&N&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:I?E:e=>{t4(e)||N()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:es?"0 6px":"8px 12px",width:es?"auto":void 0,height:32,background:I?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:I?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=I?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=I?"#ef4444":"var(--text-muted)"},title:I?et("chat.stopCompaction"):et("chat.compactContext"),"aria-label":I?et("chat.stopCompaction"):et("chat.compactContext"),children:I?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!es||eh)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:et("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(!es||eh)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:et("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:c,title:et("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:9,color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.16)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),et("chat.stop")]}),void 0!==Z&&(0,r.jsx)("button",{onClick:Z,title:V?et("chat.disableSound"):et("chat.enableSound"),"aria-label":V?et("chat.disableSound"):et("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:V?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:V?1:.55,transition:"background 0.12s, color 0.12s, opacity 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.opacity="1"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=V?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=V?"1":"0.55"},children:V?(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),(0,r.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,r.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})}),es&&eh&&(0,r.jsx)("button",{type:"button",title:et("chat.collapseControls"),"aria-label":et("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ec(!1),ep(!1),em(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]})]})]})}));var oX=n(88374),oQ=n(68925);let o0="pi-web:minimap-preview-locked";function o1(){try{return window.localStorage}catch{return null}}function o2(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:o1();if(!e)return!1;try{return"true"===e.getItem(o0)}catch{return!1}}var o4=n(88576),o8=n.n(o4);function o3(e){let{level:t,children:n,headingIndex:i,onClick:s}=e;return(0,r.jsx)("button",{type:"button",className:o8().heading,"data-level":t,"data-preview-heading-index":i??void 0,disabled:null===i||!s,onClick:e=>{e.stopPropagation(),null!==i&&s?.(i)},children:n})}let o5=[...oQ.iA??[],function(){return e=>{if(!Array.isArray(e.children))return;let t=e.children.filter(e=>"heading"===e.type&&"number"==typeof e.depth&&e.depth<=3);if(t.length>0){t.forEach((e,t)=>{e.data={...e.data,hProperties:{...e.data?.hProperties,"data-preview-heading-index":t}}}),e.children=t;return}let n=e.children.find(e=>"paragraph"===e.type);e.children=n?[n]:[]}}],o6=[[oX.A,{throwOnError:!1,strict:!1}]];function o9(e){let t=e?.properties,n=t?.dataPreviewHeadingIndex??t?.["data-preview-heading-index"];return"number"==typeof n?n:"string"==typeof n&&/^\d+$/.test(n)?Number(n):null}let o7=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:s}=e,o=(0,i.useMemo)(()=>(0,oQ.Ep)(t),[t]);return t?(0,r.jsx)("div",{className:o8().outline,children:(0,r.jsx)(ii.oz,{remarkPlugins:o5,rehypePlugins:o6,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(o3,{level:1,headingIndex:o9(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(o3,{level:2,headingIndex:o9(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(o3,{level:3,headingIndex:o9(i),onClick:n,children:t})},h4:()=>null,h5:()=>null,h6:()=>null,p:e=>{let{children:t}=e;return(0,r.jsx)("button",{type:"button",className:o8().paragraph,onClick:s,children:t})},blockquote:()=>null,ul:()=>null,ol:()=>null,pre:()=>null,table:()=>null,hr:()=>null,a:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},code:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})}},children:o})}):null}),le=(0,i.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:s,messageRefs:o,onRevealHistory:l,turnsBefore:a,railSlot:d}=e,{t:c}=(0,tn.s)(),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)([]),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(600),[b,y]=(0,i.useState)(!1),[j,k]=(0,i.useState)(o2),[w,S]=(0,i.useState)(null),C=(0,i.useRef)(!1),N=(0,i.useRef)(null),E=(0,i.useRef)([]),I=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),$=(0,i.useRef)(null),T=(0,i.useRef)(new Map),M=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(null),L=(0,i.useRef)(t);L.current=t;let z=(0,i.useMemo)(()=>(function(e,t){if(0===e.length)return{nodes:[],gap:50,fillsHeight:!1};let n=Math.max(1,t),r=Math.max(0,n-12-48);if(1===e.length)return{nodes:[{...e[0],topRatio:12/n}],gap:50,fillsHeight:!1};let i=r/(e.length-1),s=Math.min(50,i);return{nodes:e.map((e,t)=>({...e,topRatio:(12+t*s)/n})),gap:s,fillsHeight:i<=50}})(h,x),[h,x]),{nodes:P,gap:W}=z;I.current=z;let O=(0,i.useCallback)(e=>{R.current={index:e,until:Date.now()+1600},g(e)},[]),F=(0,i.useCallback)((e,t)=>{let n=R.current;if(n&&Date.now()<n.until)return void g(n.index);R.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void g(null);let i=e.scrollTop+.3*e.clientHeight;g(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),D=(0,i.useCallback)(()=>{let e=s.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=E.current;p(t>20),F(e,n)},[s,F]),B=(0,i.useRef)(null),H=(0,i.useCallback)(()=>{B.current||(B.current=setTimeout(()=>{B.current=null;let e=s.current,t=N.current;if(!e||!t)return;let r=o.current,i=e.getBoundingClientRect(),l=[],a=0,d=null,c=n();for(let t of c?[...L.current,c]:L.current){let n=rU(t);if(!n&&"assistant"!==t.role)continue;let s=r?.[a];if(a++,n){d=null;let n=s?.getBoundingClientRect();d={userMessage:t,assistantPreviews:[],scrollTop:n?n.top-i.top+e.scrollTop:null,toolCount:0},l.push(d);continue}if(!d)continue;d.toolCount+="assistant"===t.role&&Array.isArray(t.content)?t.content.reduce((e,t)=>e+ +("toolCall"===t.type),0):0;let o=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=rG(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);o&&d.assistantPreviews.push({markdown:o,element:s})}let u=l.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));v(t.clientHeight),E.current=u,m(u),p(e.scrollHeight-e.clientHeight>20),F(e,u);let h=A.current,f=h?u[h.nodeIndex]:null;if(h&&f){let t=void 0===h.assistantIndex?null:f.targetTurn.assistantPreviews[h.assistantIndex],n=f.targetTurn.scrollTop;if("assistant"===h.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===h.target){let r=void 0===h.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(h.headingIndex),s=r?.getBoundingClientRect();n=s?s.top-i.top+e.scrollTop:null}if(null===n)return;A.current=null,O(f.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,O,o,s,F]);(0,i.useEffect)(()=>{let e=s.current;if(e)return e.addEventListener("scroll",D,{passive:!0}),()=>e.removeEventListener("scroll",D)},[s,D]),(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=()=>{H(),D()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),B.current&&(clearTimeout(B.current),B.current=null)}},[H,s,D]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{H(),D()},50);return()=>clearTimeout(e)},[t.length,H,D]);let _=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;if(O(e.index),null===e.targetTurn.scrollTop){A.current={nodeIndex:e.index,target:"user"},l();return}let r=Math.max(0,e.targetTurn.scrollTop-.3*n.clientHeight);n.scrollTo({top:r,behavior:t})},[O,l,s]),U=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){A.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},l();return}let i=n.getBoundingClientRect(),o=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;O(e.index),n.scrollTo({top:Math.max(0,o),behavior:"smooth"})},[O,l,s]),K=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=I.current,i=N.current?.clientHeight??0;if(0===t.length||i<=0)return null;let s=Math.max(0,Math.min(i,e*i)),o=t[0].topRatio*i,l=n>0?Math.round((s-o)/n):0,a=Math.max(0,Math.min(t.length-1,l)),d=t[a];if(!r&&Math.abs(s-d.topRatio*i)>Math.max(10,n/2))return null;return d},[]),q=(0,i.useCallback)((e,t,n)=>{let r=s.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){A.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:n},l();return}let o=i.querySelectorAll("h1, h2, h3").item(n);if(!o)return;let a=r.getBoundingClientRect(),d=o.getBoundingClientRect().top-a.top+r.scrollTop-.3*r.clientHeight;O(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[O,l,s]),V=(0,i.useCallback)(()=>{M.current&&(clearTimeout(M.current),M.current=null)},[]),Z=(0,i.useCallback)(()=>{j||(V(),y(!0))},[V,j]),J=(0,i.useCallback)(()=>{let e=!j;k(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o1();if(t)try{t.setItem(o0,String(e))}catch{}}(e),e&&(V(),y(!1),S(null))},[V,j]),G=(0,i.useCallback)(()=>{V(),M.current=setTimeout(()=>{M.current=null,y(!1),S(null)},250)},[V]);(0,i.useEffect)(()=>()=>V(),[V]);let Y=(0,i.useCallback)(e=>{if(!u)return;C.current=!0,Z();let t=e.currentTarget.getBoundingClientRect();S(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=K(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&_(r,n)};n(e.clientY,"smooth");let r=e=>{C.current&&n(e.clientY,"auto")},i=()=>{C.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[K,_,Z,u]),X=null===w?null:K(w),Q=X?.index??null;if((0,i.useEffect)(()=>{if(!b||null===Q)return;let e=$.current,t=T.current.get(Q);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[h,b,Q]),!u||!d)return null;let ee=Math.max(1,(P.length>0?P[P.length-1].topRatio*x:12)-12),et=(0,r.jsxs)("div",{ref:N,onMouseDown:Y,onMouseEnter:Z,onMouseLeave:G,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();S((e.clientY-t.top)/t.height)},style:{width:36,flexShrink:0,position:"relative",cursor:"pointer",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[a>0&&(0,r.jsx)("div",{"data-minimap-earlier":"",style:{position:"absolute",left:"50%",top:0,height:12,width:1,background:"repeating-linear-gradient(to bottom, var(--text-dim) 0 2px, transparent 2px 4px)",transform:"translateX(-50%)",zIndex:0}}),(0,r.jsx)("div",{style:{position:"absolute",left:"50%",top:12,height:ee,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),P.map(e=>{let t=b&&X?.index===e.index,n=f===e.index;return(0,r.jsx)("div",{"data-minimap-node-index":e.index,"data-minimap-node-active":n?"":void 0,style:{position:"absolute",top:`${100*e.topRatio}%`,transform:"translateY(-50%)",left:0,right:0,height:Math.max(1,W),display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",zIndex:2},children:(0,r.jsx)("div",{style:{width:8,height:8,borderRadius:2,background:n?"rgba(128,128,128,0.42)":"rgba(128,128,128,0.16)",border:`1.5px solid ${n?"rgba(128,128,128,0.95)":"rgba(128,128,128,0.58)"}`,boxShadow:n?"0 0 0 2px var(--bg-panel)":"none",transition:"transform 0.1s, background 0.1s",transform:t?"scale(1.25)":"scale(1)"}})},e.index)}),(0,r.jsx)("button",{type:"button",className:o8().lock,"data-minimap-lock":j?"on":"off","aria-pressed":j,title:c(j?"chatMinimap.unlockPreview":"chatMinimap.lockPreview"),"aria-label":c("chatMinimap.lockPreview"),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),J()},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),j?(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"}):(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 7.9-.9"})]})}),b&&h.length>0&&(0,r.jsxs)("div",{ref:$,className:o8().preview,"data-minimap-preview-box":"",onMouseEnter:Z,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[a>0&&(0,r.jsx)("button",{type:"button",className:o8().earlier,"data-minimap-preview-earlier":"",onClick:()=>s.current?.scrollTo({top:0,behavior:"smooth"}),children:c("chatMinimap.earlierTurns",{count:a})}),h.map(e=>{var t;let n=Q===e.index;return(0,r.jsxs)("div",{ref:t=>{t?T.current.set(e.index,t):T.current.delete(e.index)},className:o8().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:o8().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(a+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:o8().toolBadge,role:"img",title:c("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),"aria-label":c("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),children:e.targetTurn.toolCount>99?"99+":e.targetTurn.toolCount})]}),(0,r.jsxs)("div",{className:o8().content,children:[(0,r.jsx)("button",{type:"button",className:o8().user,"data-minimap-preview-user":e.index,onClick:()=>{_(e,"smooth")},children:(0,r.jsx)("span",{className:o8().userText,children:"string"==typeof(t=e.targetTurn.userMessage).content?t.content.trim():t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()})}),e.targetTurn.assistantPreviews.map((t,n)=>(0,r.jsxs)("div",{className:o8().assistant,children:[(0,r.jsx)("button",{type:"button",className:o8().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>U(e,n),"aria-label":c("chatMinimap.locateAssistant"),title:c("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(o7,{markdown:t.markdown,onAnswerClick:()=>U(e,n),onHeadingClick:t=>q(e,n,t)})]},n))]})]},e.index)})]})]});return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{"aria-hidden":"true",style:{width:36,flexShrink:0}}),(0,tk.createPortal)(et,d)]})});var lt=n(6872),ln=n.n(lt);let lr="chat-view-tab-trajectory",li="chat-view-panel-trajectory";function ls(e){let{view:t,onChange:n,trajectoryDisabled:s,onTrajectoryIntent:o,iconWidth:l}=e,{t:a}=(0,tn.s)(),d=(0,i.useRef)(null),c=(0,i.useRef)(null),u=void 0!==l,p=u?{width:l}:void 0,h=a("chatView.chat"),m=a(s?"chatView.trajectoryUnavailable":"chatView.trajectory"),f=e=>{if("ArrowLeft"!==e.key&&"ArrowRight"!==e.key&&"Home"!==e.key&&"End"!==e.key)return;e.preventDefault();let r="Home"===e.key?"chat":"End"===e.key||"chat"===t?"trajectory":"chat";"trajectory"===r&&s||(n(r),("chat"===r?d:c).current?.focus())};return(0,r.jsxs)("div",{className:ln().tabs,role:"tablist","aria-label":a("chatView.tabsLabel"),children:[(0,r.jsxs)("button",{ref:d,type:"button",role:"tab","aria-selected":"chat"===t,"aria-label":u?h:void 0,tabIndex:"chat"===t?0:-1,title:h,className:ln().tab,style:p,"data-icon-only":u||void 0,"data-mobile-toolbar-action":u?"chat":void 0,onClick:()=>n("chat"),onKeyDown:f,children:[(0,r.jsx)(nU,{size:12}),!u&&(0,r.jsx)("span",{children:h})]}),(0,r.jsxs)("button",{ref:c,type:"button",role:"tab",id:lr,"aria-selected":"trajectory"===t,"aria-controls":"trajectory"===t?li:void 0,"aria-label":u?m:void 0,tabIndex:"trajectory"===t?0:-1,disabled:s,title:m,className:ln().tab,style:p,"data-icon-only":u||void 0,"data-mobile-toolbar-action":u?"trajectory":void 0,onClick:()=>n("trajectory"),onPointerEnter:o,onFocus:o,onKeyDown:f,children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"6",cy:"19",r:"3"}),(0,r.jsx)("path",{d:"M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15"}),(0,r.jsx)("circle",{cx:"18",cy:"5",r:"3"})]}),!u&&(0,r.jsx)("span",{children:a("chatView.trajectory")})]})]})}var lo=n(42790);function ll(e){let{text:t}=e,n=(0,i.useMemo)(()=>new lo.v().ansi_to_html(t).replaceAll('<a href="','<a target="_blank" rel="noopener noreferrer" href="'),[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function la(e){let t,n,s,{widgets:o,children:l}=e,{t:a}=(0,tn.s)(),d=(0,i.useId)(),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),[p,h]=(0,i.useState)(()=>o.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[m,f]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(o.map(e=>[e.key,[...e.lines]])),n=(e=c.current,e?Array.from(t,t=>{let[n,r]=t,i=e.get(n);return i&&i.length===r.length?r.some((e,t)=>e!==i[t])?n:null:i?n:null}).filter(e=>null!==e):[]);for(let[e,n]of(c.current=t,u.current))t.has(e)||(clearTimeout(n),u.current.delete(e));for(let e of(f(e=>{let r=new Set(Array.from(e).filter(e=>t.has(e)));for(let e of n)r.add(e);return r.size===e.size&&Array.from(r).every(t=>e.has(t))?e:r}),n)){let t=u.current.get(e);t&&clearTimeout(t),u.current.set(e,setTimeout(()=>{u.current.delete(e),f(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[o]),(0,i.useEffect)(()=>()=>{for(let e of u.current.values())clearTimeout(e);u.current.clear()},[]),0===o.length)return null;let g=o.find(e=>e.key===p&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=o.indexOf(g),n=`${d}-trigger-${t}`,s=`${d}-panel-${t}`,(0,r.jsxs)("section",{id:s,className:"extension-widget-panel","aria-labelledby":n,children:[(0,r.jsx)("div",{className:"extension-widget-panel-heading",children:g.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(ll,{text:g.lines.join("\n")})})]},g.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":a("chat.extensionWidgets"),children:o.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===g?.key,s=m.has(e.key),o=a(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),l=a("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),c=`${d}-trigger-${t}`,u=`${d}-panel-${t}`,p=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"extension-widget-update-pulse","aria-hidden":"true"}),(0,r.jsx)("span",{className:"extension-widget-placement","aria-hidden":"true",children:(0,r.jsx)("svg",{className:"extension-widget-placement-icon",viewBox:"0 0 8 6",width:"8",height:"6","data-direction":"belowEditor"===e.placement?"down":"up",focusable:"false",children:(0,r.jsx)("path",{d:"belowEditor"===e.placement?"M0 0h8L4 6z":"M4 0l4 6H0z"})})}),(0,r.jsx)("span",{className:"extension-widget-key",children:e.key})]});return n?(0,r.jsx)("button",{id:c,type:"button",className:`extension-widget-trigger${i?" is-expanded":""}${s?" is-updating":""}`,"aria-controls":u,"aria-expanded":i,"aria-label":`${l}: ${e.key}, ${o}`,title:`${e.key} - ${l} - ${i?a("i18n.collapse"):a("i18n.expand")}`,onClick:()=>{h(t=>{var n;return t===(n=e.key)?null:n})},children:p},e.key):(0,r.jsx)("div",{className:`extension-widget-trigger${s?" is-updating":""}`,"aria-label":`${l}: ${e.key}, ${o}`,title:`${e.key} - ${l}`,children:p},e.key)})}),l]})]})}let ld="command:";function lc(e){let{statuses:t,widgets:n=[],onCommand:i,commandsDisabled:s=!1}=e,o=function(e){let t=[];for(let n of[...e].sort((e,t)=>e.key.localeCompare(t.key))){let e=n.text.replace(/\r\n?/g,"\n").split("\n").map(e=>e.replace(/\t/g," ").replace(/ +/g," ").trim()).join("\n").trim(),r=function(e){if(!e.startsWith(ld))return null;let t=e.slice(ld.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=rP(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else rP(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===o.length&&0===n.length)return null;let l=o.some(e=>"command"===e.kind),a=o.map(e=>"text"===e.kind?rP(e.text):e.label).join(" "),d=o.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":a,title:a,children:(0,r.jsx)("span",{className:"extension-status-text",children:o.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(ll,{text:e.text})},t):(0,r.jsx)("button",{type:"button",className:"extension-status-item extension-status-command",disabled:!i||s,title:`${e.label} \xb7 ${e.command}`,"aria-label":`${e.label} (${e.command})`,onClick:()=>i?.(e.command),children:e.label},t))})}):null;return(0,r.jsx)("div",{className:`extension-status-shelf${n.length>0?" has-widgets":""}${o.length>0?" has-status":""}${l?" has-commands":""}`,children:n.length>0?(0,r.jsx)(la,{widgets:n,children:d}):d})}function lu(e){let{enterSendMode:t,idPrefix:n="hotkeys-section"}=e,{t:i}=(0,tn.s)(),s=sV(),o=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t="ctrlEnter"===e.enterSendMode,n=t?"Ctrl/Cmd+Enter":"Enter";return[{id:"composer",titleKey:"hotkeys.groupComposer",items:[{keys:n,descriptionKey:"hotkeys.sendMessage"},{keys:t?"Enter / Shift+Enter":"Shift+Enter",descriptionKey:"hotkeys.newLine"},{keys:n,descriptionKey:"hotkeys.steerMessage"},{keys:t?"Ctrl/Cmd+Alt+Enter":"Alt+Enter",descriptionKey:"hotkeys.followUpMessage"},{keys:"↑ / ↓",descriptionKey:"hotkeys.inputHistory"},{keys:"Tab / Enter",descriptionKey:"hotkeys.acceptCompletion"},{keys:"/",descriptionKey:"hotkeys.slashCommands"},{keys:"@",descriptionKey:"hotkeys.mentionFile"},{keys:"! / !!",descriptionKey:"hotkeys.bashCommand"}]},{id:"navigation",titleKey:"hotkeys.groupNavigation",items:[{keys:"Esc",descriptionKey:"hotkeys.escape"},{keys:"Ctrl+Alt+N",descriptionKey:"hotkeys.newSession"},{keys:"Alt+Click",descriptionKey:"hotkeys.toggleAllGroups"}]},{id:"sessionMenu",titleKey:"hotkeys.groupSessionMenu",items:[{keys:"P",descriptionKey:"hotkeys.menuPin"},{keys:"A",descriptionKey:"hotkeys.menuArchive"},{keys:"R",descriptionKey:"hotkeys.menuRename"},{keys:"G",descriptionKey:"hotkeys.menuGenerateTitle"},{keys:"F",descriptionKey:"hotkeys.menuFork"},{keys:"S",descriptionKey:"hotkeys.menuShare"},{keys:"E",descriptionKey:"hotkeys.menuExport"},{keys:"T",descriptionKey:"hotkeys.menuOpenNewTab"},{keys:"D / Shift+D",descriptionKey:"hotkeys.menuDelete"}]}]}({enterSendMode:t??s});return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:o.map(e=>(0,r.jsxs)("div",{role:"group","aria-labelledby":`${n}-${e.id}`,children:[(0,r.jsx)("div",{id:`${n}-${e.id}`,style:{color:"var(--text-muted)",fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:6},children:i(e.titleKey)}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",overflow:"hidden"},children:e.items.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"7px 10px",fontSize:12,borderTop:t>0?"1px solid var(--border)":void 0},children:[(0,r.jsx)("span",{style:{color:"var(--text)",minWidth:0},children:i(e.descriptionKey)}),(0,r.jsx)("code",{style:{flexShrink:0,padding:"2px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11},children:e.keys})]},e.descriptionKey))})]},e.id))})}function lp(e){let{enterSendMode:t,onClose:n}=e,{t:s}=(0,tn.s)(),o=(0,i.useRef)(null),l=(0,i.useRef)(n);(0,i.useEffect)(()=>{l.current=n},[n]),(0,i.useEffect)(()=>{if("u">typeof document)return eD(document,o.current,()=>{l.current()})},[]);let a=(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{e.target===e.currentTarget&&n()},children:(0,r.jsxs)("div",{ref:o,role:"dialog","aria-modal":"true","aria-labelledby":"hotkeys-dialog-title",tabIndex:-1,className:"project-trust-dialog",style:{width:520},children:[(0,r.jsx)("div",{className:"project-trust-body",children:(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"hotkeys-dialog-title",className:"project-trust-title",children:s("hotkeys.dialogTitle")}),(0,r.jsx)("div",{style:{marginTop:12},children:(0,r.jsx)(lu,{enterSendMode:t,idPrefix:"hotkeys-dialog-section"})})]})}),(0,r.jsx)("div",{className:"project-trust-footer",children:(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:n,children:s("hotkeys.close")})})]})});return"u">typeof document&&document.body?(0,tk.createPortal)(a,document.body):a}function lh(e,t){return e?.kind==="running_tools"&&e.tools.length>0?e:t?{kind:"waiting_model"}:{kind:"running_command"}}function lm(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function lf(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function lg(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function lx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function lv(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("assistant"!==e.role)return e;let n=e.content;if(!Array.isArray(n))return e;let r=n.map(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!lx(e)||"toolCall"!==e.type)return null;let n={type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input},r=t.includeStreamingRawInput?function(e){if("string"==typeof e.rawInput)return e.rawInput;if("string"==typeof e.partialJson)return e.partialJson;if("string"==typeof e.partialArgs)return e.partialArgs;let t=lx(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=lx(e.arguments)?e.arguments:null;return n&&r&&"string"==typeof r[n]?r[n]:void 0}(e):void 0;return void 0===r?n:{...n,rawInput:r}})(e,t)??e);return{...e,content:r}}function lb(e){if(!e||"object"!=typeof e)return null;let{reason:t,cwd:n}=e;return"cwd-missing"===t&&"string"==typeof n&&n?n:null}class ly extends Error{constructor(e,t,n,r,i){super(e),this.status=t,this.code=n,this.accepted=r,this.missingCwd=i,this.name="AgentCommandError"}}function lj(e){return e instanceof ly&&"prompt_rejected"===e.code&&!1===e.accepted}function lk(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function lw(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new ly(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted,lb(r)??void 0);return r.data}let lS={not_found:"sideChat.error.notFound",unsaved:"sideChat.error.unsaved",empty:"sideChat.error.empty",subagent:"sideChat.error.subagent",side:"sideChat.error.side"};async function lC(e,t,n){let r=await fetch(`/api/sessions/${encodeURIComponent(e)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({side:!0,...n?{name:n}:{}}),cache:"no-store"}),i=await r.json().catch(()=>null);return r.ok&&i?.sessionId&&i.session?{session:i.session}:{error:i?.code&&i.code in lS?t(lS[i.code]):i?.error??`HTTP ${r.status}`}}function lN(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let lE=new WeakMap;function lI(e){let t,n=lE.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return lE.set(e,t),t}function l$(e){let t=lN().get(e);return t?Date.now()-t.savedAt>6e5?(lN().delete(e),null):(lN().delete(e),lN().set(e,t),t):null}function lT(e){if(!e.sessionId||!e.revision)return!1;let t=lN();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(lI(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=lN();for(;e.size>8;){let t=e.keys().next().value;if(void 0===t)break;e.delete(t)}let t=0;for(let n of e.values())t+=lI(n);for(;t>0x2000000&&e.size>0;){let n=e.keys().next().value;if(void 0===n)break;let r=e.get(n);e.delete(n),r&&(t-=lI(r))}}(),lN().has(n.sessionId))}function lM(e){lN().delete(e)}var lR=n(14755);let lA="pi-tool-preset";function lL(){try{return window.localStorage}catch{return null}}let lz="pi-recent-models";function lP(){try{return window.localStorage??null}catch{return null}}function lW(e){return!!e&&"object"==typeof e&&"string"==typeof e.provider&&"string"==typeof e.modelId&&(null===e.thinkingLevel||"string"==typeof e.thinkingLevel)}function lO(e){if(!e)return[];try{let t=JSON.parse(e.getItem(lz)??"[]");if(!Array.isArray(t))return[];return t.filter(lW).slice(0,5).map(e=>{let{provider:t,modelId:n,thinkingLevel:r}=e;return{provider:t,modelId:n,thinkingLevel:r}})}catch{return[]}}function lF(e,t){return e.filter(e=>t.some(t=>t.provider===e.provider&&t.id===e.modelId))}function lD(e,t){if(!e.thinkingLevel)return null;let n=t?.[`${e.provider}:${e.modelId}`];return!n||n.includes(e.thinkingLevel)?e.thinkingLevel:null}function lB(e,t){return e&&t&&e.provider===t.provider&&e.modelId===t.modelId?e.thinkingLevel:null}function lH(e,t){t&&(e.tokens.input+=t.input??0,e.tokens.output+=t.output??0,e.tokens.cacheRead+=t.cacheRead??0,e.tokens.cacheWrite+=t.cacheWrite??0,e.cost+=t.cost?.total??0)}function l_(e){let t={userMessages:0,assistantMessages:0,toolCalls:0,toolResults:0,totalMessages:0,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0};for(let n of e)"custom"!==n.role&&(t.totalMessages+=1,"user"===n.role?t.userMessages+=1:"toolResult"===n.role?(t.toolResults+=1,lH(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),lH(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function lU(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function lK(e){return e>0?e>=.01?`$${e.toFixed(2)}`:"<$0.01":null}function lq(e){let t=e.cacheRead+e.cacheWrite+e.input;return e.cacheRead+e.cacheWrite<=0||t<=0?null:e.cacheRead/t*100}function lV(e){if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`}function lZ(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function lJ(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(lZ).filter(Boolean)}):JSON.stringify({text:"",images:[]})}let lG=(e,t)=>`live:${e??""}:${t}`;class lY extends Error{constructor(e,t){super(t??("ready_timeout"===e?"Timed out starting the agent session. Please try again.":"Failed to connect to the agent event stream. Please try again.")),this.status=e,this.name="AgentEventConnectionError"}}class lX{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.opens=0,this.retries=0,this.lastError=null,this.lastClose=null}close(e){let t=null!==this.lastError&&!(this.lastClose&&this.lastClose.at>=this.lastError.at);(this.current||this.retry||t)&&(this.lastClose={reason:e??null,at:Date.now()}),this.stopRetrying(),this.current&&this.discard(this.current,new lY("closed"))}snapshot(){let e=this.current,t=this.retry;return{sessionId:e?.sessionId??t?.sessionId??null,state:e?e.attempt.ready?"connected":"connecting":t?"retrying":"idle",readyState:e?e.source.readyState:null,openedAt:e?.openedAt??null,connectedAt:e?.connectedAt??null,lastSeenAt:e?.lastSeenAt??null,lastHeartbeatAt:e?.lastHeartbeatAt??null,events:e?.events??0,opens:this.opens,retries:this.retries,retryDueAt:t?.dueAt??null,watchdogArmed:!!(e&&null!==e.watchdog),staleAfterMs:this.options.staleAfterMs??null,lastError:this.lastError?{...this.lastError}:null,lastClose:this.lastClose?{...this.lastClose}:null}}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof lY?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){for(;;){let t=this.current;if(t&&t.sessionId===e){if(t.attempt.ready&&1===t.source.readyState)return}else t=this.open(e);if(await t.attempt.promise,this.current!==t){if(this.current?.sessionId===e)continue;throw new lY("closed")}if(1===t.source.readyState)return;this.lastClose={reason:"stuck",at:Date.now()},this.discard(t,new lY("closed"))}}open(e){let t,n,r;this.current&&(this.lastClose={reason:"replaced",at:Date.now()},this.discard(this.current,new lY("closed")));try{t=this.options.createSource(e)}catch(t){let e=t instanceof Error?t.message:String(t);throw this.lastError={reason:"error",message:e,at:Date.now()},new lY("closed",e)}this.opens+=1;let i=!1,s=new Promise((e,t)=>{n=e,r=t}),o=setTimeout(()=>{this.fail(d,new lY("ready_timeout"),"ready_timeout")},this.options.readinessTimeoutMs),l={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(o),n())},fail(e){i||(i=!0,clearTimeout(o),r(e))}},a=Date.now(),d={sessionId:e,source:t,attempt:l,watchdog:null,openedAt:a,connectedAt:null,lastSeenAt:null,lastHeartbeatAt:null,events:0};return this.current=d,t.onmessage=e=>{let t;if(this.current===d){d.lastSeenAt=Date.now();try{t=JSON.parse(e.data)}catch{return}if("heartbeat"===t.type){d.lastHeartbeatAt=d.lastSeenAt;return}if("connected"===t.type){d.connectedAt??=d.lastSeenAt,l.ready=!0,l.succeed(),this.stopRetrying();let e=this.options.staleAfterMs;e&&null===d.watchdog&&(d.watchdog=setInterval(()=>{Date.now()-(d.lastSeenAt??a)>e&&this.fail(d,new lY("closed"),"stale")},Math.max(1e3,Math.floor(e/3))))}else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(d,new lY("startup_error",e),"startup_error");return}d.events+=1,this.options.onEvent(t)}},t.onerror=()=>{this.fail(d,new lY("closed"),"error")},d}fail(e,t,n){this.current===e&&(this.lastError={reason:n,message:"startup_error"===n?t.message:null,at:Date.now()},this.discard(e,t),"startup_error"===t.status?this.stopRetrying():this.scheduleRetry(e.sessionId))}discard(e,t){null!==e.watchdog&&clearInterval(e.watchdog),e.watchdog=null,e.attempt.fail(t),e.source.close(),this.current===e&&(this.current=null)}scheduleRetry(e){if(!this.options.shouldMaintain(e)||this.retry?.sessionId===e)return;this.clearRetry();let t=setTimeout(()=>{this.retry?.timer===t&&(this.retry=null,this.retries+=1,this.maintain(e))},this.options.reconnectDelayMs);this.retry={sessionId:e,timer:t,dueAt:Date.now()+this.options.reconnectDelayMs}}stopRetrying(){this.retryGeneration+=1,this.clearRetry()}clearRetry(){this.retry&&clearTimeout(this.retry.timer),this.retry=null}}function lQ(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}function l0(e){return"u"<typeof document?()=>{}:(document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e))}let l1=()=>"hidden"===document.visibilityState,l2=()=>!1;function l4(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function l8(e){var t;return("message_start"===e.type||"message_end"===e.type)&&"object"==typeof(t=e.message)&&null!==t&&!Array.isArray(t)&&"system"===e.message.role}function l3(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function l5(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let l6={isStreaming:!1,streamingMessage:null};function l9(e,t,n){let r=e.streamingMessage;if(!r||!Number.isInteger(t)||t<0)return e;let i=[...r.content],s=n(i[t]);return s?(i[t]=s,{isStreaming:!0,streamingMessage:{...r,content:i}}):e}function l7(){let e=l6,t=new Set;return{getState:()=>e,dispatch(n){let r=function(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=lv(t.message,{includeStreamingRawInput:!0});return"assistant"===n.role?{isStreaming:!0,streamingMessage:n}:e}case"delta":var n=t.event;switch(n.type){case"text_start":return l9(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return l9(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return l9(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return l9(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return l9(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return l9(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return l9(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id??e.toolCallId,toolName:n.toolName??e.toolName,rawInput:""}:"string"!=typeof n.toolName?null:{type:"toolCall",toolCallId:n.id??"",toolName:n.toolName,input:{},rawInput:""});case"toolcall_delta":return l9(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id||e.toolCallId,toolName:n.toolName||e.toolName,rawInput:(e.rawInput??"")+n.delta}:null);case"toolcall_end":return l9(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return l6;default:return e}}(e,n);if(r!==e)for(let n of(e=r,t))n()},subscribe:e=>(t.add(e),()=>{t.delete(e)})}}function ae(e,t){let n=e.lastIndexOf(t);return -1===n?e:[...e.slice(0,n),...e.slice(n+1)]}function at(e,t){return e.reduce((e,n)=>"user"===n.role&&lJ(n)===t?e+1:e,0)}function an(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function ar(e){return e&&"auto"!==e?e:null}let ai=new Map,as=[2e3,5e3,1e4];function ao(e){return new Promise(t=>setTimeout(t,e))}function al(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function aa(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:al(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:al(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=al(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function ad(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function ac(e,t){let[n,r]=(0,i.useState)(()=>t(e.getState()));return(0,i.useLayoutEffect)(()=>{let n=()=>r(t(e.getState()));return n(),e.subscribe(n)},[e,t]),n}let au=e=>e.isStreaming,ap=e=>!!e.streamingMessage?.content.length,ah=e=>e.streamingMessage;function am(e){if(!e)return 0;if("string"==typeof e)return e.length;let t=0;for(let n of e)n&&"object"==typeof n&&("text"===n.type&&"string"==typeof n.text?t+=n.text.length:"image"===n.type&&(t+=4800));return t}let af={compactionTokens:0,userTokens:0,userCount:0,assistantTextTokens:0,assistantThinkingTokens:0,assistantCount:0,toolTrafficTokens:0,toolCallCount:0,toolResultCount:0,toolTrafficByTool:[]},ag=null,ax=null;function av(e){let{label:t}=e,[n,s]=(0,i.useState)(()=>ax);if((0,i.useEffect)(()=>{if(ax)return;let e=!1;return(ag??=fetch("/api/app-update").then(async e=>{if(!e.ok)return null;let t=await e.json();return t.updateAvailable&&t.latestVersion&&t.releaseUrl?t:null}).then(e=>(ax=e,e)).catch(()=>(ag=null,null))).then(t=>{!e&&t&&s(t)}),()=>{e=!0}},[]),!n)return null;let o=t(n.latestVersion);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"new-session-meta-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("a",{className:"new-session-update",href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:o,"aria-label":o,children:["v",n.latestVersion,(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M7 17 17 7"}),(0,r.jsx)("path",{d:"M7 7h10v10"})]})]})]})}function ab(e){let t,{messageCount:n,toolCallCount:s,durationMs:o,cacheMisses:l,defaultExpanded:a=!1,reveal:d=!1,children:c,t:u}=e,[p,h]=(0,i.useState)(a);(0,i.useLayoutEffect)(()=>{d&&h(!0)},[d]);let m=[`${n} ${u(1===n?"chat.message":"chat.messages")}`];s>0&&m.push(`${s} ${u(1===s?"chat.toolCall":"chat.toolCalls")}`),void 0!==o&&m.push(u("chat.turnDuration",{time:ie(o)}));let f=l&&!(p||d)?(t={count:l.count,tokens:iz(l.missedTokens),cost:iW(u,l.missedCost)},u(1===l.count?"transcriptNotice.foldCacheMiss":"transcriptNotice.foldCacheMisses",t)):void 0;return(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":p||d,"aria-label":[u("chat.processDetails"),...m,...f?[f]:[]].join(" \xb7 "),onClick:()=>h(e=>!e),style:{display:"flex",alignItems:"center",gap:8,width:"auto",maxWidth:"100%",minHeight:24,padding:"2px 0",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},title:u(p?"chat.collapseProcess":"chat.expandProcess"),children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:p?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[m.join(" \xb7 "),f&&(0,r.jsx)("span",{style:{color:iP},children:` \xb7 ${f}`})]})]}),(p||d)&&(0,r.jsx)("div",{style:{marginTop:8},children:c})]})}let ay=()=>{};function aj(e){var t;let s,{session:l,searchTarget:d,onSearchTargetHandled:c,initialScrollPosition:u,onScrollPositionChange:p,sessionRunning:h,newSessionCwd:m,newSessionDraftKey:f,newSessionContextBar:g,trajectoryView:x,initialNewSessionChoices:v,onNewSessionChoicesChange:b,onAgentEnd:y,onToolEnd:j,onAttentionNeeded:k,onSessionCreated:w,onSessionForked:S,panel:C=!1,onSideSession:N,modelsRefreshKey:E,chatInputRef:I,onBranchDataChange:$,onSystemPromptChange:T,onSystemToolsChange:M,onSystemInfoLoaderChange:R,onDebugSnapshotReaderChange:A,onSessionStatsChange:L,onSessionStatsPanelOpen:z,onMessageContextSummaryChange:P,onOpenSettings:W,onContextUsageChange:O,onOpenFile:F,onFilesUploaded:D,onOpenSubagent:B,quoteSelectionEnabled:H=!1,initialPrompt:_,onInitialPromptConsumed:U,soundEnabled:K=!0,onSoundToggle:q,playDoneSound:V=()=>{},unlockAudio:Z,holdAudio:J}=e,{t:G}=(0,tn.s)(),Y=tp(),X=!a(l?.relation),Q=(0,i.useRef)(V);Q.current=V;let ee=(0,i.useRef)(K);ee.current=K;let et=(0,i.useRef)(!1),en=(0,i.useCallback)(e=>{X&&ee.current&&!e.aborted&&!e.subagentsActive&&Q.current(),y?.(e)},[X,y]),er=(0,i.useRef)(d?null:u??null),[ei,es]=(0,i.useState)(()=>{let e=er.current;return e&&!e.atBottom?e:null}),[eo,el]=(0,i.useState)(!1),[ea,ed]=(0,i.useState)(!1),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[em,ef]=(0,i.useState)({open:!1}),{loading:eg,error:ex,messages:ev,activeToolResults:eb,entryIds:ey,messageKeys:ej,historyCursor:ek,hasEarlierMessages:ew,earlierTurnCount:eS,streamingStore:eC,agentRunning:eN,bashRunning:eE,pendingBash:eI,modelNames:e$,modelList:eT,modelError:eM,missingCwd:eR,modelScopeWarnings:eA,modelThinkingLevels:eL,modelThinkingLevelMaps:ez,toolPreset:eP,thinkingLevel:eW,retryInfo:eO,contextUsage:eF,forkingEntryId:eD,isCompacting:eB,compactError:eU,compactResult:eK,displayModel:eq,modelSwitching:eZ,sessionStats:eJ,slashCommands:eG,slashCommandsLoading:eY,queuedMessages:eX,notices:eQ,extensionDialog:e0,waitingExtensionDialogCount:e1,extensionCustomUi:e2,waitingExtensionCustomUiCount:e4,extensionStatuses:e8,extensionWidgets:e3,respondToExtensionUi:e5,sendExtensionCustomInput:e6,setNoticePaused:e9,addNotice:e7,isAutoModelSelection:te,isAutoThinkingSelection:tt,recentModels:tr,agentPhase:ti,isNew:ts,editEntryId:to,showScrollToBottom:tl,sessionIdRef:ta,scrollContainerRef:td,lastUserMsgRef:tc,promptAnchorActive:tu,handleSend:th,handleAbort:tm,startSideChat:tf,handleFork:tx,handleEditContent:tv,cancelEdit:tb,handleModelChange:ty,handleCompact:tj,handleSteer:tw,handleFollowUp:tS,handlePromptWithStreamingBehavior:tC,handleAbortCompaction:tN,dismissCompactError:tE,handleRecallQueue:tI,handleBuiltinSlashCommand:t$,handleToolPresetChange:tT,handleThinkingLevelChange:tM,handleSelectRecentModel:tR,loadSlashCommands:tA,scrollUserMsgToTop:tL,loadContext:tP,activeLeafId:tW,scrollToBottom:tO,scrollToMessage:tF}=function(e){let{session:t,newSessionCwd:r,newSessionDraftKey:s,onAgentEnd:o,onToolEnd:l,onAttentionNeeded:a,onSessionCreated:d,onSessionForked:c,onSideSession:u,modelsRefreshKey:p,onBranchDataChange:h,onSystemPromptChange:m,onSystemToolsChange:f,onSystemInfoLoaderChange:g,onSessionStatsPanelOpen:x,onOpenSettings:v,onHotkeysOpen:b,onShareSessionOpen:y,onExportSessionOpen:j,onImportSessionOpen:k,onDebugSnapshotReaderChange:w}=e,S=null===t&&null!==r,C=S?e.initialNewSessionChoices??null:null,[N,E]=(0,i.useState)(null),[I,$]=(0,i.useState)(!S),[T,M]=(0,i.useState)(null),[R,A]=(0,i.useState)(null),[L,z]=(0,i.useState)([]),[P,W]=(0,i.useState)(new Map),[O,F]=(0,i.useState)([]),[D,B]=(0,i.useState)(()=>new Map),[H,_]=(0,i.useState)(null),[U,K]=(0,i.useState)(!1),[q,V]=(0,i.useState)(0),[Z]=(0,i.useState)(l7),J=Z.dispatch,[G,Y]=(0,i.useState)(!1),[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)({}),[ei,es]=(0,i.useState)([]),[eo,el]=(0,i.useState)([]),[ea,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[em,ef]=(0,i.useState)([]),[eg,ex]=(0,i.useState)({}),[ev,eb]=(0,i.useState)({}),[ey,ej]=(0,i.useState)(()=>C?.model??null),[ek,ew]=(0,i.useState)(null),[eS,eC]=(0,i.useState)(lR.Q8),[eN,eE]=(0,i.useState)(()=>C?.thinkingLevel??null),[eI,e$]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(null),[eR,eA]=(0,i.useState)(null),[eL,ez]=(0,i.useState)(null),[eP,eW]=(0,i.useState)(null),[eO,eF]=(0,i.useState)(null),eD=(0,i.useRef)(0),eB=(0,i.useRef)(0),[eU,eK]=(0,i.useState)(null),[eq,eZ]=(0,i.useState)(null),[eJ,eG]=(0,i.useState)(null),[eY,eX]=(0,i.useState)(null),[eQ,e0]=(0,i.useState)(null),[e1,e2]=(0,i.useState)(!1),[e4,e8]=(0,i.useState)(!1),[e3,e5]=(0,i.useState)(!0),[e6,e9]=(0,i.useState)(null),[e7,te]=(0,i.useState)(null),[tt,tn]=(0,i.useState)(null),[tr,ti]=(0,i.useState)(!1),[ts,to]=(0,i.useState)(!1),[tl,ta]=(0,i.useState)([]),[td,tc]=(0,i.useState)(!1),[tu,tp]=(0,i.useReducer)(aa,{visible:[],pending:[]}),[th,tm]=(0,i.useState)(null),[tf,tg]=(0,i.useState)([]),[tx,tv]=(0,i.useState)([]),[tb,ty]=(0,i.useState)([]),[tj,tk]=(0,i.useState)([]),[tw,tS]=(0,i.useState)({steering:[],followUp:[]}),tC=(0,i.useRef)(null),tN=(0,i.useRef)(null),tE=(0,i.useRef)(0),tI=(0,i.useRef)(!1),t$=(0,i.useRef)(!1),[tT,tM]=(0,i.useState)(0),tR=(0,i.useRef)(null),tA=(0,i.useRef)(()=>{}),tL=(0,i.useRef)({renewStartedAt:null,inFlightSince:null,requests:0,unanswered:0,errors:0,last:null}),tz=(0,i.useRef)({count:0,lastAt:null}),tP=(0,i.useRef)({count:0,lastAt:null,lastReason:null}),tW=(0,i.useRef)(null),tO=(0,i.useRef)(null),tF=(0,i.useRef)(!1),tD=(0,i.useRef)(0),tB=(0,i.useRef)(t?.id??null),tH=(0,i.useRef)(t?.id??null),t_=(0,i.useRef)(!1),tU=(0,i.useRef)(!1),tK=(0,i.useRef)(!1),tq=(0,i.useRef)(!1),tV=(0,i.useRef)(-1),tZ=(0,i.useRef)(!1),tJ=(0,i.useRef)(0),tG=(0,i.useRef)(null),tY=(0,i.useRef)(!!e.deferInitialScroll),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(!1),t0=(0,i.useRef)(!0),t1=(0,i.useRef)(0),t2=(0,i.useRef)(null),t4=(0,i.useRef)(void 0),t8=(0,i.useRef)(void 0),t3=(0,i.useRef)(null),t5=(0,i.useRef)(null),t6=(0,i.useRef)([]),t9=(0,i.useRef)(null),t7=(0,i.useRef)(0),ne=(0,i.useRef)(!1),nt=(0,i.useRef)(C?.model??null),nn=(0,i.useRef)(C?.thinkingLevel??null),nr=(0,i.useRef)({}),ni=(0,i.useRef)(null),ns=(0,i.useRef)(null),no=(0,i.useRef)(null),nl=(0,i.useRef)(0),na=(0,i.useRef)(null),nd=(0,i.useRef)(null),nc=(0,i.useRef)(null),nu=(0,i.useRef)(0),np=(0,i.useRef)(null),nh=(0,i.useCallback)(()=>{nd.current=nl.current,nc.current?.runId===nl.current&&(nc.current=null)},[]),nm=(0,i.useRef)(!1),nf=(0,i.useRef)(new Map),ng=(0,i.useRef)(!0),nx=(0,i.useRef)(new Map),nv=(0,i.useRef)(null),nb=(0,i.useRef)([]),ny=(0,i.useRef)([]),nj=(0,i.useRef)(null),nk=(0,i.useRef)(null),nw=(0,i.useRef)(!1),nS=(0,i.useRef)(0);tH.current=t?.id??null,nv.current=N,nb.current=L,ny.current=O,nj.current=R,nk.current=H,nw.current=U,nS.current=q,tF.current=e4,tD.current=tf.length+tx.length;let nC=(0,i.useCallback)(e=>ng.current&&tB.current===e&&(tU.current||tI.current||tH.current===e&&!t$.current),[]);tC.current||(tC.current=new lX({createSource:e=>eV("agent",new EventSource(`/api/agent/${encodeURIComponent(e)}/events?holder=${encodeURIComponent(e_())}`),e),onEvent:e=>tG.current?.(e),shouldMaintain:nC,readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let nN=e.setToolPreset??eC,nE=t?.id;(0,i.useLayoutEffect)(()=>{(nE||S&&!tB.current)&&nN(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:lL();if(!e)return lR.Q8;try{let t=e.getItem(lA);return(0,lR.sn)(t)?t:lR.Q8}catch{return lR.Q8}}())},[nE,S,nN]);let nI=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{S&&nI?.({model:ey,thinkingLevel:eN})},[S,ey,eN,nI]);let n$=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=t3.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),t1.current=t.scrollTop)},[]),nT=eJ??eY??N?.context.model??eQ??null,nM=S?ey??ek:nT??(N?.context.messages.length===0?ek:null),nR=ar(N?.context.thinkingLevel&&"off"!==N.context.thinkingLevel?N.context.thinkingLevel:null),nA=S?eN??eI:eT??eR??nR??(N?.context.messages.length===0?eI:null),nL=t?.id??s??void 0,nz=(0,i.useCallback)(e=>{eX(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eA(ar(e.thinkingLevel))},[]),nP=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=nf.current.get(t);if(!e)break;t=e}return t},[]),nW=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),o=nP(r);if(!ng.current&&!ne.current&&r===s)return;let l=e.chatInputRef?.current;l?l.restoreSubmission(t,i,o):o&&sM(o,t,i)},[s,e.chatInputRef,nP]),[nO,nF]=(0,i.useState)(()=>{let e=t?.id;return e&&!sN(e)&&ai.delete(e),e&&ai.get(e)||null}),nD=(0,i.useCallback)(e=>{t?.id&&(e?ai.set(t.id,e):ai.delete(t.id),nF(e))},[t?.id]),nB=(0,i.useCallback)((n,r)=>{t?.id&&(e.chatInputRef?.current?.replaceMessage(n),nD(r))},[e.chatInputRef,t?.id,nD]),nH=(0,i.useCallback)(()=>nD(null),[nD]),n_=(0,i.useMemo)(()=>{let e=N?.totalActiveMs,n=eO&&eO.sessionId===N?.sessionId?eO.value:void 0,r=void 0===e&&void 0===n?void 0:Math.max(e??0,n??0);if(th)return{...th,totalActiveMs:r,...eP?{contextUsage:eP}:{}};let i=N?.stats,s=function(e,t,n){let r=l_(n);if(!e)return r;let i=l_(t),s=(e,t)=>Math.max(0,e-t),o={input:e.tokens.input+s(r.tokens.input,i.tokens.input),output:e.tokens.output+s(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+s(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+s(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return o.total=o.input+o.output+o.cacheRead+o.cacheWrite,{userMessages:e.userMessages+s(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+s(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+s(r.toolCalls,i.toolCalls),toolResults:e.toolResults+s(r.toolResults,i.toolResults),totalMessages:e.totalMessages+s(r.totalMessages,i.totalMessages),tokens:o,cost:e.cost+s(r.cost,i.cost)}}(i,N?.context.messages??[],L);return 0!==s.tokens.total||0!==L.length||i?{sessionFile:N?.filePath||void 0,sessionId:tB.current??t?.id??"",sessionName:t?.name,...s,totalActiveMs:r,...eP?{contextUsage:eP}:{}}:null},[L,th,eP,eO,N?.sessionId,N?.context.messages,N?.filePath,N?.totalActiveMs,N?.stats,t?.id,t?.name]),nU=(0,i.useCallback)((e,t,n,r)=>{ng.current&&tB.current===t&&nl.current===n&&!(r<=eB.current)&&(eB.current=r,e?.contextUsage!==void 0&&eW(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&eF({sessionId:t,value:e.totalActiveMs}))},[]),nK=(0,i.useCallback)(async e=>{let t=nl.current,n=++eD.current;try{let r=await fetch(lk(e));if(!r.ok)return;let i=await r.json();nU(i.state,e,t,n)}catch{}},[nU]),nq=(0,i.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,i=r?.force?`force:${e}`:e,s=r?.force?void 0:nx.current.get(i);if(s)return await s;let o=(async()=>{let i=!1,s=++nu.current;try{t&&$(!0);let o=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&o.set("force","1");let l=await fetch(`/api/sessions/${encodeURIComponent(e)}?${o}`);if(404===l.status)return t&&(E(null),A(null),z([]),F([]),_(null),K(!1),V(0),M(null)),lM(e),null;if(!l.ok)throw Error(`HTTP ${l.status}`);let a=await l.json();if(tB.current!==e)return null;(np.current?.seq??0)<s&&(np.current={sid:e,seq:s,messages:a.context.messages,entryIds:a.context.entryIds??[]});let d=l$(e),c=!!(a.snapshotRevision&&d?.revision===a.snapshotRevision&&d.entryIds.length>=(a.context.entryIds??[]).length),u=c?nb.current:a.context.messages;if(E(c?{...a,context:{...a.context,messages:nb.current,entryIds:ny.current,oldestEntryId:nk.current,hasMore:nw.current,turnsBefore:nS.current}}:a),A(a.leafId),c)lT({sessionId:e,revision:a.snapshotRevision,messages:nb.current,entryIds:ny.current,leafId:a.leafId,oldestEntryId:nk.current,hasMore:nw.current,turnsBefore:nS.current,summaryTree:a.tree,thinkingLevel:a.context.thinkingLevel,model:a.context.model,stats:a.stats,totalActiveMs:a.totalActiveMs,loadedEntryIds:ny.current});else{let e={messages:nb.current,entryIds:ny.current},t={messages:u,entryIds:a.context.entryIds??[]};B(n=>(function(e,t){let n=new Set(t.entryIds),r=new Map([...e.aliases].filter(e=>{let[t]=e;return n.has(t)})),i=e.entryIds.length,s=e.entryIds[i-1],o=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===o&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var l,a;let d=t.entryIds[o+n];if(void 0===d||(l=e.messages[i+n],a=t.messages[o+n],l.role!==a.role||("user"===l.role?lJ(l)!==lJ(a):"custom"===l.role?l.customType!==a.customType:l.timestamp!==a.timestamp)))break;r.set(d,lG(s,n))}return r})({...e,aliases:n},t)),z(t.messages),F(t.entryIds),_(a.context.oldestEntryId),K(a.context.hasMore),V(a.context.turnsBefore??0)}if(t_.current=void 0!==a.toolNames,nN(void 0!==a.toolNames?(0,lR.YO)(a.toolNames):lR.Q8),eG(e=>nm.current?e:null),eM(null),M(null),"summary"===a.treeFormat&&a.snapshotRevision&&lT({sessionId:e,revision:a.snapshotRevision,messages:u,entryIds:a.context.entryIds??[],leafId:a.leafId,oldestEntryId:a.context.oldestEntryId,hasMore:a.context.hasMore,turnsBefore:a.context.turnsBefore??0,summaryTree:a.tree,thinkingLevel:a.context.thinkingLevel,model:a.context.model,stats:a.stats,totalActiveMs:a.totalActiveMs,loadedEntryIds:a.context.entryIds??[]}),a.wrapperRebuilt&&(tC.current?.close("rebuilt"),tC.current?.maintain(e)),!n&&a.context.thinkingLevel&&"off"!==a.context.thinkingLevel&&eA(ar(a.context.thinkingLevel)),i=!0,t&&$(!1),!n)return null;try{let t=nl.current,n=++eD.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tB.current!==e)return null;let s=i.state;return nz(s),s?(nU(s,e,t,n),void 0!==s.systemPrompt&&eK(s.systemPrompt??null),void 0!==s.extensionStatuses&&ty(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tk(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tS(an(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&e5(s.autoCompactionEnabled??!0)):i.running||tS({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return M(String(e)),"error"}finally{t&&!i&&$(!1)}})();return r?.force||nx.current.set(i,o),o.finally(()=>{nx.current.get(i)===o&&nx.current.delete(i)}),await o},[nU,nN,nz]),nV=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let s=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,o=await fetch(s,{signal:r?.signal});if(!o.ok)throw Error(`HTTP ${o.status}`);let l=await o.json();if(tB.current!==e||r?.signal?.aborted||!ng.current)return;return _(l.context.oldestEntryId),K(l.context.hasMore),V(l.context.turnsBefore??0),E(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...l.context.messages,...t.context.messages],entryIds:[...l.context.entryIds,...t.context.entryIds],oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore,turnsBefore:l.context.turnsBefore}:l.context;return{...t,context:r}}),n?(z(e=>[...l.context.messages,...e]),F(e=>[...l.context.entryIds,...e])):(z(l.context.messages),F(l.context.entryIds??[])),l.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),nZ=(0,i.useCallback)(async e=>{try{let t=await lw(e,{type:"get_tools"});if(!t||!ng.current||tB.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return nN(t_.current?r(t):lR.Q8),f?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[f,nN]),nJ=(0,i.useCallback)(function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"(no messages)",i=tB.current;if(S&&r&&i&&!ne.current&&(ne.current=!0,s)){if(s!==i){nf.current.set(s,i);let t=e.chatInputRef?.current;t?t.rekeyDraft(s,i):sR(s,i)}d?.({id:i,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},s)}},[S,r,s,d,e.chatInputRef]),nG=(0,i.useCallback)(async()=>{if(tB.current||!S||!r)return tB.current;if(t5.current)return t5.current;let e=(async()=>{let e=nt.current,t=nn.current,n=ns.current,i=e??(n?{provider:n.provider,modelId:n.modelId}:null),s=t??ar(lB(n,i));i&&e0(i);let o=(0,lR.xG)(eS);t_.current=void 0!==o;let l=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",...void 0!==o?{toolNames:o}:{},...i?{provider:i.provider,modelId:i.modelId}:{},...s?{thinkingLevel:s}:{}})});if(!l.ok){let e=await l.json().catch(()=>null),t="string"==typeof e?.error?e.error:`HTTP ${l.status}`,n=lb(e);throw n?new ly(t,l.status,void 0,void 0,n):Error(t)}let a=await l.json(),d=a.sessionId;return tB.current=d,no.current={model:a.model??null,thinkingLevel:ar(a.thinkingLevel)},a.model&&nt.current===e&&(e0(a.model),e||ew(a.model)),a.thinkingLevel&&nn.current===t&&(eA(ar(a.thinkingLevel)),t||e$(ar(a.thinkingLevel))),d})();t5.current=e;try{return await e}finally{t5.current=null}},[S,r,eS]),nY=(0,i.useCallback)(async()=>{let e=tB.current??await nG();if(!e)return;let[t]=await Promise.all([lw(e,{type:"get_state"}),nZ(e)]);ng.current&&tB.current===e&&(nz(t),eK(t.systemPrompt??""))},[nG,nZ,nz]),nX=(0,i.useCallback)(e=>{t6.current=e,ta(e)},[]),nQ=(0,i.useCallback)(()=>{t7.current+=1,t9.current=null,nX([])},[nX]),n0=(0,i.useCallback)(()=>{let e=++t7.current,t=(async()=>{let t=tB.current??await nG();if(!t)return t7.current===e&&nX([]),[];tc(!0);try{let n=await lw(t,{type:"get_commands"}),r=n?.commands??[];return t7.current===e&&nX(r),r}catch(t){return console.error("Failed to load slash commands:",t),t7.current===e&&nX([]),null}finally{t7.current!==e&&t9.current||tc(!1)}})();t9.current=t;let n=()=>{t9.current===t&&(t9.current=null)};return t.then(n,n),t},[nG,nX]),n1=(0,i.useCallback)(async()=>await n0()??[],[n0]),n2=(0,i.useCallback)(async()=>{let e=t9.current,t=t6.current;return!e&&t.length>0?t:await (e??n0()).catch(()=>null)??(t.length>0?t:null)},[n0]),n4=(0,i.useCallback)(()=>{tE.current+=1,tI.current=!1,tO.current=null,tN.current&&(clearTimeout(tN.current),tN.current=null)},[]),n8=(0,i.useCallback)(e=>{tC.current?.close(e)},[]),n3=(0,i.useCallback)(e=>tC.current.ensureConnected(e),[]),n5=(0,i.useCallback)(e=>{tC.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=t?.id;if(e)return ng.current=!0,t$.current=!1,n5(e),()=>{tB.current===e&&tC.current?.close("deselected")}},[n5,t?.id]);let n6=(0,i.useCallback)(e=>{let t=tR.current;if(t?.sid===e)return t.promise;let n=new AbortController,r=setTimeout(()=>n.abort(),5e3),i={sid:e,promise:Promise.resolve(null)};return i.promise=(async()=>{let t=null,s=null,o=Date.now();tL.current.inFlightSince=o,tL.current.requests+=1;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}/lease`,{method:"POST",cache:"no-store",signal:n.signal});return t=r.status,s=r.ok?await r.json():null}catch(e){return s=n.signal.aborted||e instanceof TypeError?"unanswered":null}finally{clearTimeout(r),tR.current===i&&(tR.current=null);try{let e=tL.current,n=Date.now(),r="unanswered"===s?"unanswered":null===s?"error":"reply";"unanswered"===r&&(e.unanswered+=1),"error"===r&&(e.errors+=1);let i="object"==typeof s&&null!==s?s:null;e.inFlightSince=null,e.last={at:n,durationMs:Math.max(0,n-o),outcome:r,httpStatus:t,reply:i&&{running:!0===i.running,awaitingInput:!0===i.awaitingInput,subagentsActive:!0===i.subagentsActive}}}catch{}}})(),tR.current=i,i.promise},[]),n9=!G&&!X&&!e4&&0===tf.length&&0===tx.length;(0,i.useEffect)(()=>{let e=t?.id;if(!e||!n9)return;let n=!1,r=null,i=()=>!n&&"hidden"===document.visibilityState&&!t$.current&&tB.current===e&&tH.current===e&&!tU.current&&!tZ.current,s=async()=>{if(r=null,tW.current=null,!i())return;let t=await n6(e);if(i()){if(!("unanswered"===t||t&&!lQ(t)))return void o();t$.current=!0,tz.current={count:tz.current.count+1,lastAt:Date.now()},n8("released")}},o=()=>{null===r&&(r=setTimeout(()=>void s(),3e4),tW.current=Date.now()+3e4)},l=()=>{"hidden"===document.visibilityState?o():r&&(clearTimeout(r),r=null,tW.current=null)};return"hidden"===document.visibilityState&&o(),document.addEventListener("visibilitychange",l),()=>{n=!0,r&&clearTimeout(r),tW.current=null,document.removeEventListener("visibilitychange",l)}},[n8,n9,tT,n6,t?.id]);let n7=(0,i.useCallback)(async(e,t)=>{let n=tB.current;if(tg(t=>lg(t,e.id)),n)try{await lw(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),re=(0,i.useCallback)(async(e,t)=>{let n=tB.current;if(n)try{await lw(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),rt=(0,i.useCallback)(e=>{let t=e.message.trim();t&&tp({type:"add",notice:{id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info"}})},[]),rn=(0,i.useRef)(e.t);rn.current=e.t;let rr=(0,i.useCallback)((e,t)=>rn.current(e,t),[]),ri=(0,i.useCallback)(()=>{rt({type:"warning",message:rr("chat.sendUnconfirmed")})},[rt,rr]),rs=(0,i.useCallback)(e=>{ng.current&&z(t=>ae(t,e.bubble));let t=l$(e.sid);t?.messages.includes(e.bubble)&&lT({...t,messages:ae(t.messages,e.bubble)})},[]),ro=(0,i.useCallback)((e,t,n)=>{let r=nc.current;if(!r||r.runId!==t||r.sid!==e)return;nc.current=null;let i=np.current,s=i?.sid===e&&i.seq>n?i:null,o=s?null===r.lastEntryIdAtSend?0:s.entryIds.indexOf(r.lastEntryIdAtSend)+1||-1:-1;s&&o>=0&&at(s.messages.slice(o),r.key)>r.sameTextAfterSend||(nW(r.message,r.images,r.draftKey),s&&rs(r),rt(s&&!r.command&&o===s.entryIds.length?{type:"error",message:rr("chat.sendNotReceived")}:{type:"warning",message:rr("chat.sendUnconfirmed")}))},[rt,rs,nW,rr]),rl=(0,i.useCallback)(()=>{let e=nc.current;if(nc.current=null,e){if(e.parkedDraftKey){let t=e.images?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});sM(e.parkedDraftKey,e.message,t)}else nW(e.message,e.images,e.draftKey);rs(e)}},[rs,nW]),ra=(0,i.useRef)(rl);ra.current=rl;let rd=(0,i.useCallback)(t=>{switch(lm(t)&&a?.(t),t.method){case"select":case"confirm":case"input":case"editor":tg(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":rt({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":ty(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":tk(e=>(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"aboveEditor";if(void 0===n)return e.filter(e=>e.key!==t);let i={key:t,lines:n,placement:r},s=e.findIndex(e=>e.key===t);return -1===s?[...e,i]:e.map((e,t)=>t===s?i:e)})(e,t.widgetKey,t.widgetLines,t.widgetPlacement));break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":tv(e=>{let n;return t.closed?lg(e,t.id):-1===(n=e.findIndex(e=>e.id===t.id))?[...e,t]:e[n]===t?e:e.map((e,r)=>r===n?t:e)})}},[rt,a,e.chatInputRef]),rc=(0,i.useCallback)(()=>{let e=tU.current;return tU.current=!1,Y(!1),tn(null),ez(null),W(new Map),J({type:"end"}),e},[J]),ru=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return tV.current!==e&&(tV.current=e,o?.({aborted:t,...n?{subagentsActive:n}:{}}),!0)},[o]),rp=(0,i.useCallback)(e=>{if(tH.current===e)return void n4();n4(),tI.current=!0;let t=tE.current,n=async()=>{if(t===tE.current&&tB.current===e&&tI.current)try{let r=await fetch(lk(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==tE.current||tB.current!==e||!tI.current)return;let s=i.state;if(nz(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){tI.current=!1,tN.current=null,tO.current=null,tK.current=!!s?.isStreaming,tq.current=!!s?.isPromptRunning,tU.current=!0,Y(!0),tn(e=>lh(e,!!s?.isStreaming));return}if(i.running&&s?.isCompacting){e8(!0),tN.current=setTimeout(()=>void n(),600),tO.current=Date.now()+600;return}tI.current=!1,tN.current=null,tO.current=null,n8("grace_end")}catch{if(t!==tE.current||tB.current!==e||!tI.current)return;tN.current=setTimeout(()=>void n(),600),tO.current=Date.now()+600}};tN.current=setTimeout(()=>void n(),3e4),tO.current=Date.now()+3e4},[n4,n8,nz]),rh=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tB.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nl.current;if(nl.current!==t)return;let n=nu.current;try{e&&await nq(e)}finally{if(nl.current!==t)return;e&&ro(e,t,n);let r=tq.current,i=tK.current;tq.current=!1,tK.current=!1,na.current=null;let s=rc();r?ru(t):i&&s&&o?.({aborted:!1}),e&&rp(e)}},[nq,ru,o,rp,rc,ro]),rm=(0,i.useCallback)(async(e,t)=>{await ao(800);let n=Date.now();for(;tU.current&&Date.now()-n<2e4;){if(void 0!==t&&nl.current!==t)return;try{let n=await fetch(lk(e));if(n.ok){let r=await n.json(),i=r.state;if(nz(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await rh(e,t)}}catch{}await ao(600)}},[rh,nz]),rf=(0,i.useCallback)(async e=>{let t=tJ.current+1;for(tJ.current=t;tZ.current&&tJ.current===t&&tB.current===e;){await ao(1e3);try{let n=await fetch(lk(e));if(!n.ok)continue;let r=await n.json();if(nz(r.state),r.state?.isBashRunning)continue;if(await nq(e),tJ.current!==t||tB.current!==e)return;tZ.current=!1,Q(!1),et(null);return}catch{}}},[nq,nz]),rg=(0,i.useCallback)(async e=>{if(!tU.current||tB.current!==e)return;let t=nl.current,n=++eD.current;try{let r=await fetch(lk(e));if(!r.ok)return;let i=await r.json();if(tB.current!==e||nl.current!==t)return;let s=i.state;if(nU(s,e,t,n),nz(s),e8(s?.isCompacting??!1),e5(s?.autoCompactionEnabled??!0),tS(an(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){tK.current=!!s.isStreaming,tq.current=!!s.isPromptRunning;return}if(!tU.current)return;s&&(void 0!==s.extensionStatuses&&ty(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tk(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&ng.current&&tB.current===e&&t.state?.systemPrompt!==void 0&&eK(t.state.systemPrompt??null)}).catch(()=>{})),await rh(e,t)}catch{}},[nU,rh,nz]);(0,i.useEffect)(()=>{if(!G)return;let e=()=>{let e=tB.current;e&&rg(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[G,rg]),(0,i.useEffect)(()=>{tU.current=G},[G]),tG.current=(0,i.useCallback)(e=>{switch(e.type){case"connected":if(J({type:"end"}),Array.isArray(e.pendingExtensionUiIds)){let t=new Set(e.pendingExtensionUiIds);tg(e=>lf(e,t)),tv(e=>lf(e,t))}!0===e.isStreaming&&(n4(),tK.current=!0,tU.current=!0,Y(!0),tn({kind:"waiting_model"})),tB.current&&nK(tB.current);break;case"agent_start":nh(),n4(),tK.current=!0,tU.current=!0,Y(!0),tn({kind:"waiting_model"}),ez(null),J({type:"start"});break;case"agent_end":if(!tU.current)break;if(tn(null),ez(null),J({type:"end"}),tB.current){let e=tB.current,t=nl.current,n=++eD.current;nq(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&ng.current&&tB.current===e&&nl.current===t&&(nz(r.state),nU(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eK(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&ty(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tk(r.state.extensionWidgets??[]),tS(an(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let t=tK.current;if(tK.current=!1,!t||tq.current)break;let n=tB.current,r=rc();e8(!1),n&&(nq(n),rp(n)),r&&o?.({aborted:!0===e.aborted,...!0===e.subagentsActive?{subagentsActive:!0}:{}});break}case"prompt_done":{nh();let t=nl.current,n=tq.current;tq.current=!1,na.current=null;let r=ru(t,!0===e.aborted,!0===e.subagentsActive);if(!n&&!r)break;let i=tB.current;i&&nq(i),!tK.current&&(rc(),i&&rp(i))}break;case"prompt_error":rt({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":rt({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!tU.current||l8(e))break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(J({type:"snapshot",message:t}),t.content.length>0&&tn(null)):t&&tn(null)}else{let t=e.assistantMessageEvent;t&&(J({type:"delta",event:t}),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&tn(null))}!tQ.current&&t0.current&&null===t2.current&&(t2.current=requestAnimationFrame(()=>{t2.current=null,t0.current&&n$("auto")}));break;case"message_end":{if(!tU.current||l8(e))break;let t=e.message;if(t&&"user"===t.role){let e=lv(t),n=lJ(e),r=na.current;na.current=null,r&&nh(),z(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&lJ(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t){let n=Array.isArray(e.transcriptNotices)?e.transcriptNotices:void 0;if(z(e=>{var r;return[...e,(r=lv(t),n&&0!==n.length?{...r,[iA]:[...n]}:r)]}),"assistant"===t.role){let e=tB.current;e&&nK(e)}}J({type:"end"}),tn({kind:"waiting_model"});break}case"tool_execution_start":{if(l4(e))break;let t=e.toolCallId,n=e.toolName;tn(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(l4(e))break;let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;("bash"===n||"powershell"===n||n===ij)&&Array.isArray(i)&&W(e=>{let s=new Map(e);return s.set(t,{role:"toolResult",toolCallId:t,toolName:n,content:i,isError:r?.isError,details:r?.details}),s});let s=n===ij?function(e){if(!iw(e))return null;let{calls:t}=iC(e.details),n=t.findLast(e=>"running"===e.status)??t.at(-1);if(!n)return null;let r=n.args.length>120?`${n.args.slice(0,117)}...`:n.args;return r?`${n.name} ${r}`:n.name}(e.partialResult):function(e){if(!l3(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>l3(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(e.partialResult);tn(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[],i=r.find(e=>e.id===t),o={id:t,name:n||i?.name||"tool",progress:s??i?.progress};return{kind:"running_tools",tools:[...r.filter(e=>e.id!==t),o]}});break}case"tool_execution_end":{if(l4(e))break;let t=e.toolCallId;l?.(e.toolName),W(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}),tn(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":nh(),tS({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ez({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ez(null);break;case"auto_compaction_start":case"compaction_start":e8(!0),e9(null),te(null);break;case"auto_compaction_end":case"compaction_end":e8(!1),e.errorMessage?(e9(e.errorMessage),te(null)):!e.aborted&&(te(ad(e.result,e.reason??"auto")),tB.current&&nq(tB.current));break;case"extension_ui_request":rd(e);break;case"extension_ui_closed":tg(t=>lg(t,e.id))}},[rt,nU,n4,J,rd,nq,nh,ru,o,l,nK,rp,n$,rc,nz]);let rx=(0,i.useCallback)(async(e,n)=>{let i=e.trim();if(!i&&!n?.length)return;if(tU.current||tZ.current)return void nW(e,n,nL);if(nO&&(nD(null),!await t8.current?.(nO))){nD(nO),nW(e,n,nL);return}let s=!n?.length&&i.startsWith("/");if(!n?.length&&i.startsWith("!")){let t=i.startsWith("!!"),r=(t?i.slice(2):i.slice(1)).trim();return r?void await t4.current?.(r,t):void nW(e,n,nL)}let o=nl.current+1;n4(),tq.current=!0;let l=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),a={role:"user",content:l?.length?[...e.trim()?[{type:"text",text:e}]:[],...l]:e,timestamp:Date.now()},d=lJ(a),c=ny.current,u=c.at(-1)??null,p=at(nb.current.slice(c.length),d);z(e=>[...e,a]),na.current=d,nl.current=o,tU.current=!0,Y(!0),tn(s?{kind:"running_command"}:{kind:"waiting_model"}),J({type:"start"}),tQ.current=!0,ti(!0);let h=()=>{z(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),na.current=null},m=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),f=null,g=!1;try{if(S&&r){let t=tB.current??await t5.current,n=t??await nG();if(!n)throw Error("Unable to create a session for the prompt");f=n,ey&&(e0(ey),t&&await lw(n,{type:"set_model",provider:ey.provider,modelId:ey.modelId})),ng.current&&await n3(n).catch(e=>{if(ng.current)throw e}),g=!0;let r=await lw(n,{type:"prompt",message:e,...m?.length?{images:m}:{}});r?.queued&&h(),nJ(1,e)}else if(t){f=t.id,await n3(t.id),g=!0;let n=await lw(t.id,{type:"prompt",message:e,...m?.length?{images:m}:{}});n?.queued&&h()}else throw Error("No active session for the prompt");eh(null);let n=S?no.current:null,i=nM??n?.model??null;i&&el(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:lP(),n=lO(t).filter(t=>t.provider!==e.provider||t.modelId!==e.modelId||t.thinkingLevel!==e.thinkingLevel),r=[e,...n].slice(0,5);if(!t)return r;try{t.setItem(lz,JSON.stringify(r))}catch{}return r}({provider:i.provider,modelId:i.modelId,thinkingLevel:nA??n?.thinkingLevel??null})),s&&f&&rm(f,o)}catch(t){if(console.error("Failed to send message:",t),!(!g||lj(t))&&f){nd.current!==o&&(nc.current={runId:o,sid:f,message:e,images:n,draftKey:nL,parkedDraftKey:S&&r?sw(r):null,lastEntryIdAtSend:u,sameTextAfterSend:p,bubble:a,key:d,command:s},ng.current||rl()),rm(f,o);return}if(tq.current=!1,z(e=>ae(e,a)),t instanceof ly&&t.missingCwd?eh(t.missingCwd):rt({type:"error",message:t instanceof Error?t.message:String(t)}),nW(e,n,nL),na.current=null,f)return void rg(f);tU.current=!1,n8("send_failed"),Y(!1),tn(null),J({type:"end"})}},[S,r,ey,nM,nA,t,nG,n3,nJ,rm,rt,rl,n4,n8,nL,J,rg,nW,nO,nD]);t4.current=(0,i.useCallback)(async(e,n)=>{if(tU.current||tZ.current)return;let r=`${n?"!!":"!"}${e}`;tZ.current=!0,et({command:e,excludeFromContext:n}),Q(!0);try{let i=tB.current??t?.id??await nG();if(!i)throw Error("Unable to create a session for the shell command");await lw(i,{type:"bash",command:e,excludeFromContext:n}),await nq(i),nJ(1,r)}catch(e){console.error("Failed to execute shell command:",e),rt({type:"error",message:e instanceof Error?e.message:String(e)}),nW(r,void 0,nL)}finally{tZ.current=!1,et(null),Q(!1)}},[rt,nL,nG,nq,nJ,nW,t]);let rv=(0,i.useCallback)(t=>{let n=[...t?.steering??[],...t?.followUp??[]].join("\n\n");t?.images?.length?nW(n,t.images,nL):n&&e.chatInputRef?.current?.prependText(n)},[nL,e.chatInputRef,nW]),rb=(0,i.useCallback)(async()=>{let e=tB.current;if(e){if(tZ.current){try{await lw(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{rv(await lw(e,{type:"abort"}))}catch(e){console.error("Failed to abort:",e)}}},[rv]),ry=(0,i.useCallback)(async e=>{if(tZ.current)return;let t=tB.current;if(t){eZ(e);try{let{cancelled:n,newSessionId:r}=await lw(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e),rt({type:"error",message:e instanceof Error?e.message:String(e)})}finally{eZ(null)}}},[rt,c]),rj=(0,i.useCallback)(async e=>{if(tZ.current)return!1;let t=tB.current;if(!t)return!1;try{let n=await lw(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tB.current!==t)return!1;return await nq(t),tB.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[nq]);t8.current=rj;let rk=(0,i.useCallback)(async e=>{if(tZ.current||tU.current||e4)return;A(e);let t=tB.current;t&&(await nV(t,e),e&&lw(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[e4,nV]),rw=(0,i.useCallback)(async(e,t)=>{if(S){let n={provider:e,modelId:t};nt.current=n,ej(n),e0(n);let r=nr.current[`${e}/${t}`];e$(ar(lB(ns.current,n))??ar(r)??ni.current);let i=tB.current??await t5.current;if(!i)return!0;try{await lw(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return!0}let n=tB.current;if(!n||nm.current)return!1;nm.current=!0,eG({provider:e,modelId:t}),e2(!0);try{let r=await lw(n,{type:"set_model",provider:e,modelId:t});return eX({provider:r.provider,modelId:r.id}),nm.current=!1,await nq(n),!0}catch(e){return console.error("Failed to set model:",e),nm.current=!1,eG(eJ),rt({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nq(n,!1,!0),!1}finally{nm.current=!1,e2(!1)}},[rt,eJ,S,nq,ej]),rS=(0,i.useCallback)(async e=>{let t=tB.current;if(!t||e4)return!0;e8(!0),e9(null),te(null);try{let n=await lw(t,{type:"compact",...e?{customInstructions:e}:{}});return te(ad(n,"manual")),await nq(t,!0)&&nJ(),!0}catch(e){return e9(e instanceof Error?e.message:String(e)),te(null),!1}finally{e8(!1)}},[e4,nq,nJ]),rC=(0,i.useCallback)(()=>e9(null),[]),rN=(0,i.useCallback)(async e=>{let n,i=r??t?.cwd??"",s=i?`/api/models?cwd=${encodeURIComponent(i)}`:"/api/models",o=null;try{let t=await fetch(s,e?{signal:e}:void 0);if(!t.ok){let e="";try{let n=await t.json();n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error&&(e=n.error),o=lb(n)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${t.status})`)}n=await t.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||(eu(o),ed(o?null:t instanceof Error?t.message:String(t))),t}eu(null),er(n.models),ed(n.modelError??null),ef(n.modelScopeWarnings??[]),ex(n.thinkingLevels??{}),eb(n.thinkingLevelMaps??{});let l=n.modelList??[];es(l);let a=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:lP(),r=lO(n),i=lF(r,e)[0];return{recent:r,start:i?{...i,thinkingLevel:lD(i,t)}:null}}(l,n.thinkingLevels);el(a.recent);let d=S&&!tB.current,c=d?a.start:null;ns.current=c;let u=n.defaultModel?l.find(e=>e.id===n.defaultModel?.modelId&&e.provider===n.defaultModel?.provider):void 0,p=c?{provider:c.provider,modelId:c.modelId}:u?{provider:u.provider,modelId:u.id}:null;if(S&&tB.current||ew(p),nr.current=n.thinkingLevelPins??{},ni.current=ar(n.defaultThinkingLevel),d){let e=nt.current,t=e&&(0===l.length||l.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!t&&(nt.current=null,ej(null));let r=t?e:p,i=r&&n.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];e$(ar(lB(c,r))??ar(i)??ni.current)}},[S,r,t?.cwd]),rE=(0,i.useCallback)(async(t,n)=>{let r=e.session?.relation?.kind;if("side"===r||"subagent"===r)return rr(lS[r]);let i=tB.current;if(!i)return rr("sideChat.error.noSession");let s=await lC(i,rr,n);return"error"in s?s.error:(u?.(s.session,t),null)},[u,e.session?.relation?.kind,rr]),rI=(0,i.useCallback)(async t=>{if(!t.startsWith("/"))return{handled:!1};let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!n)return{handled:!1};let[,r,i=""]=n,s=i.trim(),o=tB.current??("hotkeys"===r||"import"===r||"share"===r||"export"===r||"context"===r?null:await nG()),l=e=>(e.handled&&(e.error?rt({type:"error",message:e.error}):e.action||rt({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":if(!o||e4)return l({handled:!0,error:"No active session to compact"});return rS(s||void 0).then(t=>{!t&&s&&e.chatInputRef?.current?.prependText(`/compact ${s}`)}),l({handled:!0,action:"compact"});case"auto-compact":{if(!o)return l({handled:!0,error:"No active session"});let e=await lw(o,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await lw(o,{type:"set_auto_compaction",enabled:t}),e5(t),l({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!o)return l({handled:!0,error:"No active session to reload"});return await lw(o,{type:"reload"}),await Promise.all([nq(o,!1,!0),nZ(o),n1(),rN()]),l({handled:!0,message:"Reloaded session resources"});case"name":if(!o)return l({handled:!0,error:"No active session to name"});if(!s)return l({handled:!0,error:"Usage: /name <name>"});return await lw(o,{type:"set_session_name",name:s}),await nq(o)&&nJ(),l({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!o)return l({handled:!0,error:"No active session"});if(!x)return l({handled:!0,message:function(e){if(!e)return"No usage yet";let t=lK(e.cost);return[`${e.totalMessages} messages`,`${lU(e.tokens.total)} tokens`,...t?[t]:[]].join(" \xb7 ")}(n_)});let e=await lw(o,{type:"get_session_stats"});return e&&tm(e),x?.("overview"),l({handled:!0,action:"openSessionStats"})}case"context":return x?.("context"),l({handled:!0,action:"openSessionStats"});case"mcp":{if(s||!v)return{handled:!1};let e=await n2();if(!e||!(e.some(sO)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return v("mcp"),l({handled:!0,action:"openSettings"})}case"copy":{if(!o)return l({handled:!0,error:"No active session"});let e=await lw(o,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return l({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),l({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!o)return l({handled:!0,error:"No active session to clone"});if(tU.current||tZ.current)return l({handled:!0,error:"Cannot clone while the session is running"});let e=await lw(o,{type:"clone",leafId:R});if(e?.cancelled||!e?.newSessionId)return l({handled:!0,error:"Cannot clone an empty or unsaved session"});let t=l({handled:!0,message:"Cloned current session branch"});return c?.(e.newSessionId),t}case"share":if(!o||nb?.current&&0===nb.current.length)return l({handled:!0,error:"No active session to share"});return y?.(o),l({handled:!0,action:"openShare"});case"export":if(!o||nb?.current&&0===nb.current.length)return l({handled:!0,error:"No active session to export"});return j?.(o),l({handled:!0,action:"openExport"});case"import":{let e;if(tU?.current||tZ?.current)return l({handled:!0,error:"Cannot import while the session is running"});if(s){let t=s[0];if('"'===t||"'"===t){let n=s.indexOf(t,1);if(n<0||!(e=s.slice(1,n).trim()))return l({handled:!0,error:"Usage: /import <path.jsonl>"})}else{let t=s.search(/\s/);e=t<0?s:s.slice(0,t)}}return k?.(e),l({handled:!0,action:"openImport"})}case"hotkeys":return b?.(),l({handled:!0,action:"openHotkeys"});case"side":{let e=await rE(s||null);return l(e?{handled:!0,error:e}:{handled:!0,action:"openSideChat"})}default:return{handled:!1}}}catch(e){return l({handled:!0,error:e instanceof Error?e.message:String(e)})}},[R,rt,nG,rS,e4,rN,nq,n1,nZ,nJ,j,b,k,v,c,x,y,e.chatInputRef,n_,n2,rE]),r$=(0,i.useCallback)(async(e,t,n)=>{let r=tB.current;if(nO)return void nW(e,n,nL);if(!r){nW(e,n,nL),rt({type:"error",message:"No active session for the queued message"});return}let i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await lw(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){if(console.error("Failed to submit streaming prompt:",t),nW(e,n,nL),t instanceof ly&&t.missingCwd)return void eh(t.missingCwd);lj(t)?rt({type:"error",message:t.message}):ri()}},[rt,ri,nL,nO,nW]),rT=(0,i.useCallback)(async(e,t)=>{await r$(e,"steer",t)},[r$]),rM=(0,i.useCallback)(async(e,t,n)=>{await r$(e,t,n)},[r$]),rR=(0,i.useCallback)(async(e,t)=>{await r$(e,"followUp",t)},[r$]),rA=(0,i.useCallback)(async()=>{let e=tB.current;if(e)try{await lw(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),rL=(0,i.useCallback)(async()=>{let e=tB.current;if(e)try{let t=await lw(e,{type:"clear_queue"});tS({steering:[],followUp:[]}),rv(t)}catch(e){console.error("Failed to recall queued messages:",e),rt({type:"error",message:"Failed to recall queued messages"})}},[rt,rv]),rz=(0,i.useCallback)(async e=>{if("auto"===e){nn.current=null,eE(null),eM(null);return}S?(nn.current=e,eE(e)):eM(e);let t=tB.current??await t5.current;if(t)try{await lw(t,{type:"set_thinking_level",level:e}),ng.current&&tB.current===t&&(eA(e),eM(null))}catch(e){console.error("Failed to set thinking level:",e),eM(null)}},[S]),rP=(0,i.useCallback)(async e=>{(nM?.provider===e.provider&&nM.modelId===e.modelId||await rw(e.provider,e.modelId))&&await rz(ar(lD(e,eg))??"auto")},[nM,rw,rz,eg]),rW=(0,i.useCallback)(async e=>{let t=(0,lR.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:lL();if(t)try{t.setItem(lA,e)}catch{}}(e),nN(e);let n=tB.current??await t5.current;if(!n){t_.current=void 0!==t;return}try{let e=await lw(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});t_.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(n4(),n8("set_tools"),tg([]),tv([]),tB.current=r,e?.recreated&&tH.current===r&&n5(r)),nQ(),ty([]),tk([]);let[i]=await Promise.all([lw(r,{type:"get_state"}),nZ(r)]);ng.current&&tB.current===r&&(eK(i.systemPrompt??""),nz(i))}catch(e){console.error("Failed to set tools:",e)}},[n4,nQ,n8,nZ,n5,nN,nz]),rO=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=t3.current;n&&(null!==t2.current&&(cancelAnimationFrame(t2.current),t2.current=null),tY.current=!0,tQ.current=!1,t0.current=!1,ti(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),t1.current=n.scrollTop)},[]),rF=(0,i.useCallback)(()=>{let e=t3.current,t=tX.current;if(!e||!t)return;let n=Math.min(Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-16),Math.max(0,e.scrollHeight-e.clientHeight));null!==t2.current&&(cancelAnimationFrame(t2.current),t2.current=null),t0.current=!0,t1.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),rD=(0,i.useCallback)(()=>{let e=t3.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tU.current,s=t0.current,o=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!l5(n,r,i)||!(n<t)&&(!!(!e&&n>t&&l5(n,r,i,s))||e)}(s,t1.current,t,n,r,i?96:8);t0.current=o,t1.current=t;let l=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!l5(e,t,n,r)}(t,n,r);to(e=>e===l?e:l),!s&&o&&i?n$("auto"):o||null===t2.current||(cancelAnimationFrame(t2.current),t2.current=null)}},[n$]),rB=(0,i.useCallback)((e,t)=>{t?.running&&(nZ(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(tK.current=!!t.state.isStreaming,tq.current=!!t.state.isPromptRunning,tU.current=!0,Y(!0),tn(e=>lh(e,t.state?.isStreaming===!0)),J({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&rm(e)),t.state?.isBashRunning&&(tZ.current=!0,Q(!0),rf(e))),t?.state&&(void 0!==t.state.isCompacting&&e8(t.state.isCompacting),void 0!==t.state.systemPrompt&&eK(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&ty(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&tk(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tS(an(t.state.queuedMessages)))},[J,nZ,rf,rm]);tA.current=(e,t)=>{!t$.current||(t$.current=!1,tP.current={count:tP.current.count+1,lastAt:Date.now(),lastReason:t},tM(e=>e+1),ng.current&&tB.current===e&&tH.current===e&&(n5(e),nq(e,!1,!0).then(t=>{ng.current&&tB.current===e&&rB(e,t)})))},(0,i.useEffect)(()=>{let e=t?.id;if(!e)return;let n=!1,r=tL.current,i=async()=>{let t=await n6(e);!n&&"hidden"===document.visibilityState&&lQ(t)&&tA.current(e,"activity")};i();let s=setInterval(()=>void i(),3e4);r.renewStartedAt=Date.now();let o=()=>{"visible"===document.visibilityState&&(tA.current(e,"visible"),i())};return document.addEventListener("visibilitychange",o),()=>{n=!0,clearInterval(s),r.renewStartedAt=null,document.removeEventListener("visibilitychange",o)}},[n6,t?.id]),(0,i.useEffect)(()=>{if(ng.current=!0,eB.current=eD.current,t){tB.current=t.id;let e=l$(t.id);e&&(E({sessionId:t.id,filePath:"",totalActiveMs:e.totalActiveMs??0,tree:e.summaryTree,leafId:e.leafId,context:{messages:e.messages,entryIds:e.entryIds,oldestEntryId:e.oldestEntryId,hasMore:e.hasMore,turnsBefore:e.turnsBefore,thinkingLevel:e.thinkingLevel,model:e.model},stats:e.stats}),A(e.leafId),z(e.messages),F(e.entryIds),_(e.oldestEntryId),K(e.hasMore),V(e.turnsBefore),M(null),$(!1)),nq(t.id,!e,!0,{force:!0}).then(e=>{rB(t.id,e)})}return()=>{ng.current=!1;let e=S?s:null;e&&queueMicrotask(()=>{ng.current||ne.current||sI(e)});let t=tB.current,n=nv.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=l$(t),r=ny.current;!e||function(e,t){if(0===t.length)return!0;let n=new Set([...e.entryIds,...e.loadedEntryIds]);return t.every(e=>n.has(e))}(e,r)?lT({sessionId:t,revision:n.snapshotRevision,messages:nb.current,entryIds:ny.current,leafId:nj.current,oldestEntryId:nk.current,hasMore:nw.current,turnsBefore:nS.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:ny.current}):lM(t)}ra.current(),null!==t2.current&&(cancelAnimationFrame(t2.current),t2.current=null),tJ.current+=1,n4(),n8()}},[]),(0,i.useEffect)(()=>{m?.(eU)},[eU,m]),(0,i.useEffect)(()=>(g?.(nY),()=>g?.(null)),[nY,g]);let rH=(0,i.useCallback)(()=>{let e,t=null;try{t=tC.current?.snapshot?.()??null}catch{t=null}let n=tB.current,r=tL.current,i=tP.current;return{pageId:"string"==typeof(e=globalThis[eH])?e:null,sessionId:n,selectedSessionId:tH.current,mounted:ng.current,wantsStream:null!==n&&nC(n),connection:t,released:{active:t$.current,...tz.current},reattached:{...i},hiddenReleaseDueAt:tW.current,hiddenGraceMs:3e4,graceDueAt:tO.current,run:{agentRunning:tU.current,bashRunning:tZ.current,compacting:tF.current,dialogs:tD.current},lease:{renewIntervalMs:3e4,renewStartedAt:r.renewStartedAt,inFlightSince:r.inFlightSince,requests:r.requests,unanswered:r.unanswered,errors:r.errors,last:r.last&&{...r.last,reply:r.last.reply&&{...r.last.reply}}}}},[nC]);(0,i.useEffect)(()=>(w?.(rH),()=>w?.(null)),[rH,w]);let r_=G||X||e4;(0,i.useEffect)(()=>{h&&h(N?.tree??[],R,rk,r_)},[N?.tree,R,rk,r_,h]),(0,i.useEffect)(()=>{let e=t3.current;if(e)return t1.current=e.scrollTop,e.addEventListener("scroll",rD,{passive:!0}),()=>{e.removeEventListener("scroll",rD)}},[L.length,I,rD]),(0,i.useEffect)(()=>{G||ti(!1)},[G]),(0,i.useLayoutEffect)(()=>{L.length>0&&(tQ.current?(tQ.current=!1,tY.current=!0,rF()):tY.current?!tU.current&&t0.current&&n$("auto"):(tY.current=!0,n$("instant")))},[L.length,G,n$,rF]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await rN(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=as.length||(await ao(as[t]),e.signal.aborted))return}})(),()=>e.abort()},[rN,p]),(0,i.useEffect)(()=>{if(!e7)return;let e=setTimeout(()=>te(null),6e3);return()=>clearTimeout(e)},[e7]);let[rU,rK]=(0,i.useState)(null),rq=(0,i.useRef)(5e3),rV=(0,i.useRef)(null),rZ=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===tu.visible.length){rZ.current=null;return}let e=tu.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{tp({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=tu.visible[0];if(!t||(rZ.current!==t.id&&(rZ.current=t.id,rq.current=5e3),tu.visible.some(e=>e.id===rU)))return;rV.current=Date.now();let n=setTimeout(()=>{tp({type:"mark_oldest_exiting"})},rq.current);return()=>{clearTimeout(n),null!==rV.current&&(rq.current=Math.max(0,rq.current-(Date.now()-rV.current)),rV.current=null)}},[tu.visible,rU]),(0,i.useEffect)(()=>{tm(null)},[L.length,eP?.tokens,eP?.percent,eP?.contextWindow]);let rJ=nA??"auto",rG=tf[0]??null,rY=Math.max(0,tf.length-1),rX=tx[0]??null,rQ=Math.max(0,tx.length-1),r0=(0,i.useMemo)(()=>(function(e,t,n){let r=e[e.length-1],i=[];for(let s=0;s<t;s++){let t=e[s];i.push(void 0===t?lG(r,s-e.length):n.get(t)??t)}return i})(O,L.length,D),[O,L.length,D]),r1=(0,i.useMemo)(()=>lF(eo,ei),[eo,ei]);return{data:N,loading:I,error:T,activeLeafId:R,messages:L,activeToolResults:P,entryIds:O,messageKeys:r0,historyCursor:H,hasEarlierMessages:U,earlierTurnCount:q,streamingStore:Z,agentRunning:G,modelNames:en,modelList:ei,modelError:ea,missingCwd:ep??ec,modelScopeWarnings:em,modelThinkingLevels:eg,modelThinkingLevelMaps:ev,newSessionModel:ey,toolPreset:eS,thinkingLevel:rJ,retryInfo:eL,contextUsage:eP,systemPrompt:eU,forkingEntryId:eq,isCompacting:e4,compactError:e6,compactResult:e7,currentModel:nT,displayModel:nM,modelSwitching:e1,sessionStats:n_,autoCompactionEnabled:e3,slashCommands:tl,slashCommandsLoading:td,queuedMessages:tw,notices:tu.visible,extensionDialog:rG,waitingExtensionDialogCount:rY,extensionCustomUi:rX,waitingExtensionCustomUiCount:rQ,extensionStatuses:tb,extensionWidgets:tj,respondToExtensionUi:n7,sendExtensionCustomInput:re,isAutoModelSelection:S&&null===ey,isAutoThinkingSelection:S&&null===eN,recentModels:r1,agentPhase:tt,isNew:S,editEntryId:nO,promptAnchorActive:tr,showScrollToBottom:ts,sessionIdRef:tB,scrollContainerRef:t3,lastUserMsgRef:tX,pendingScrollToUserRef:tQ,initialScrollDoneRef:tY,handleSend:rx,handleAbort:rb,startSideChat:rE,handleFork:ry,handleNavigate:rj,handleModelChange:rw,handleCompact:rS,handleSteer:rT,handleFollowUp:rR,handlePromptWithStreamingBehavior:rM,handleAbortCompaction:rA,dismissCompactError:rC,handleRecallQueue:rL,handleBuiltinSlashCommand:rI,handleEditContent:nB,cancelEdit:nO?nH:void 0,addNotice:rt,setNoticePaused:rK,handleToolPresetChange:rW,handleThinkingLevelChange:rz,handleSelectRecentModel:rP,loadTools:nZ,loadSlashCommands:n1,setActiveLeafId:A,setData:E,setMessages:z,loadContext:nV,scrollToBottom:n$,scrollUserMsgToTop:rF,scrollToMessage:rO,dispatch:J,setAgentRunning:Y,setForkingEntryId:eZ,bashRunning:X,pendingBash:ee,handleAgentEventRef:tG}}({session:l,sessionRunning:h,newSessionCwd:m,newSessionDraftKey:f,initialNewSessionChoices:v,onNewSessionChoicesChange:b,onAgentEnd:en,onToolEnd:j,onAttentionNeeded:k,onSessionCreated:w,onSessionForked:S,onSideSession:N,modelsRefreshKey:E,chatInputRef:I,onBranchDataChange:$,onSystemPromptChange:T,onSystemToolsChange:M,onSystemInfoLoaderChange:R,onSessionStatsPanelOpen:z,onOpenSettings:W,onHotkeysOpen:(0,i.useCallback)(()=>ed(!0),[]),onShareSessionOpen:(0,i.useCallback)(e=>eu(e),[]),onExportSessionOpen:(0,i.useCallback)(e=>eh(e),[]),onImportSessionOpen:(0,i.useCallback)(e=>ef({open:!0,initialPath:e}),[]),onDebugSnapshotReaderChange:A,t:G,deferInitialScroll:!!ei}),tD=ac(eC,au),tB=ac(eC,ap),tH=(0,i.useCallback)(()=>eC.getState().streamingMessage,[eC]),t_=eN||eE;(0,i.useEffect)(()=>{if(eN&&J)return J()},[eN,J]);let[tU,tK]=(0,i.useState)(null),[tZ,tY]=(0,i.useState)(!1),[tX,tQ]=(0,i.useState)(!1),[t0,t1]=(0,i.useState)(null),t2=(0,i.useRef)(null),t4=(0,i.useRef)(null),[t8,t3]=(0,i.useState)(null),t5=(0,i.useCallback)(()=>{tK(null),tY(!1),t1(null)},[]);(0,i.useEffect)(()=>{H||t5()},[H,t5]);let t6=(0,i.useCallback)(()=>{if(!H||tZ)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=nl.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tK(null);let r=e.toString().trim();if(!r)return void tK(null);let i=t.getBoundingClientRect();tK({text:r,top:Math.min(window.innerHeight-44,i.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,i.left+i.width/2))})},[H,tZ]);(0,i.useEffect)(()=>{tZ&&tU&&t4.current?.insertIfEmpty(it(tU.text))},[tZ,tU]),(0,i.useLayoutEffect)(()=>{let e=t2.current;if(!e||!tU)return;let t=window.visualViewport,n=()=>{let n=e.getBoundingClientRect(),r=t?.offsetTop??0,i=t?.offsetLeft??0;e.style.top=`${Math.max(r+8,Math.min(tU.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tU.left-n.width/2,i+(t?.width??window.innerWidth)-n.width-8))}px`};n();let r=new ResizeObserver(n);return r.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[tU,tZ,t0]),(0,i.useEffect)(()=>{if(!tU)return;let e=e=>{tZ||t2.current?.contains(e.target)||t5()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tX||t5())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tU,tZ,tX,t5]);let t9=(0,i.useCallback)(()=>{tU&&(I?.current?.insertQuote(it(tU.text)),t5())},[I,tU,t5]),t7=(0,i.useCallback)(async e=>{if(!tX&&e.trim()&&tU){tQ(!0),t1(null);try{let t=await tf(e,tU.text);if(!t)return void t5();t4.current?.restoreSubmission(e),t1(t)}catch(t){t4.current?.restoreSubmission(e),t1(t instanceof Error?t.message:String(t))}finally{tQ(!1)}}},[tU,tX,t5,tf]),ne=(0,i.useCallback)(async e=>{let t;try{t=await tf(e)}catch(e){t=e instanceof Error?e.message:String(e)}t&&(I?.current?.restoreSubmission(e),e7({type:"error",message:t}))},[e7,I,tf]),nt=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eg||ex||!_||nt.current||(nt.current=!0,U?.(),th(_))},[_,eg,ex,th,U]),(0,i.useEffect)(()=>{let e=!!e0&&!et.current;et.current=!!e0,X&&e&&Q.current()},[X,e0]),(0,i.useEffect)(()=>{C||(o=t_?tm:null)},[C,t_,tm]);let[nn,nr]=(0,i.useState)(50),[ni,no]=(0,i.useState)(null),nl=(0,i.useRef)(null),na=(0,i.useRef)(null),nd=(0,i.useRef)(!1),nc=(0,i.useRef)(!1),nu=(0,i.useRef)(ei);nu.current=ei;let[np,nh]=(0,i.useState)(null),nm=ev[ey.indexOf(np?.entryId??"")],nf=nm?.role==="assistant"?np?.blockIndex===void 0?nm.content.find(e=>"text"===e.type):nm.content[np.blockIndex]:void 0,ng=(0,i.useRef)({entryIds:ey,historyCursor:ek,hasEarlierMessages:ew});ng.current={entryIds:ey,historyCursor:ek,hasEarlierMessages:ew};let nx=(0,i.useRef)(null),nv=(0,i.useCallback)(async(e,t,n)=>{nx.current=t;let r=await tP(e,tW,t,n);return r||nx.current!==t||(nx.current=null),r},[tW,tP]);(0,i.useEffect)(()=>{ek!==nx.current&&(nx.current=null)},[ek]),(0,i.useLayoutEffect)(()=>{let e=l?.id,t=td.current,n=nl.current;if(e&&p&&t&&n)return()=>{if(nu.current)return;if(l5(t.scrollTop,t.clientHeight,t.scrollHeight))return void p(e,{atBottom:!0});let r=t.getBoundingClientRect().top,i=function(e,t){let n=e[0];for(let r of e){if(r.top>t)break;n=r}return n?{anchorEntryId:n.entryId,anchorOffset:n.top-t}:null}(Array.from(n.children).flatMap(e=>{if(!(e instanceof HTMLElement)||!e.dataset.entryId)return[];let t=e.getBoundingClientRect();return[{entryId:e.dataset.entryId,top:t.top,bottom:t.bottom}]}),r);i&&p(e,{atBottom:!1,...i,oldestEntryId:ng.current.historyCursor})}},[eg,p,td,l?.id]),(0,i.useEffect)(()=>{d&&es(null)},[d]),(0,i.useEffect)(()=>{let e=l?.id;if(!ei||!e||eg||d||nc.current)return;nc.current=!0;let t=new AbortController;return(async()=>{let n=ng.current;if(n.entryIds.includes(ei.anchorEntryId)){nr(e=>Math.max(e,2*n.entryIds.length)),el(!0);return}nd.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await nv(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tO("instant"),es(null);return}if(nr(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(ei.anchorEntryId))return void el(!0);if(n.oldestEntryId===ei.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tO("instant"),es(null))}finally{nd.current=!1}})(),()=>{t.abort(),es(null)}},[tW,nv,eg,ei,tO,d,l?.id]),(0,i.useLayoutEffect)(()=>{let e=nl.current;if(!ei||!e||d)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===ei.anchorEntryId);if(t instanceof HTMLElement){tF(t,ei.anchorOffset),es(null);return}eo&&(tO("instant"),es(null))},[ey,ei,eo,tO,tF,d,nn]),(0,i.useEffect)(()=>{if(!d||eg)return;let e=new AbortController;return(async()=>{let t=ng.current,n=t.entryIds.includes(d.entryId);if(!n&&!t_&&t.hasEarlierMessages&&t.historyCursor&&!nd.current){nd.current=!0;let r=td.current;r&&(na.current=r.scrollHeight-r.scrollTop);let i=await nv(d.sessionId,t.historyCursor,{tail:200,signal:e.signal});nd.current=!1,n=!!i?.entryIds.includes(d.entryId)}e.signal.aborted||(n?(na.current=null,nr(e=>Math.max(e,(ng.current.entryIds.length+200)*2)),nh(d)):c?.(d))})(),()=>e.abort()},[d,eg,t_,nv,c,td]),(0,i.useLayoutEffect)(()=>{if(!np||np!==d)return;let e=`[data-entry-id="${CSS.escape(np.entryId)}"]`,t=td.current?.querySelector(nm?.role==="user"?e:`${e} [data-search-target]`);t&&(tF(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),nh(null),c?.(np)},[np,d,nm,td,tF,c]),(0,i.useEffect)(()=>{let e=td.current;if(!ni||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||nd.current)return;if(!ew){na.current=e.scrollHeight-e.scrollTop,nr(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!ek||ek===nx.current)return;let n=l?.id??ta.current;n&&(nd.current=!0,na.current=e.scrollHeight-e.scrollTop,nv(n,ek).finally(()=>{nd.current=!1}))},{root:e,threshold:0});return t.observe(ni),()=>t.disconnect()},[ni,nn,ek,ew,l,nv,ta,td]),(0,i.useEffect)(()=>{nr(e=>Math.max(e,ev.length))},[ev.length]),(0,i.useEffect)(()=>{if(null==na.current)return;let e=td.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-na.current),na.current=null}},[nn,td]);let nb=eJ?[eJ.sessionId,eJ.sessionFile??"",eJ.sessionName??"",eJ.userMessages,eJ.assistantMessages,eJ.toolCalls,eJ.toolResults,eJ.totalMessages,eJ.tokens.input,eJ.tokens.output,eJ.tokens.cacheRead,eJ.tokens.cacheWrite,eJ.tokens.total,eJ.cost??0,eJ.totalActiveMs??0].join("|"):null,ny=(0,i.useRef)(eJ);ny.current=eJ,(0,i.useEffect)(()=>{L?.(ny.current)},[nb,L]),(0,i.useEffect)(()=>()=>{L?.(null)},[L]);let nj=eF?`${eF.percent??"null"}|${eF.contextWindow}|${eF.tokens??"null"}`:null,nk=(0,i.useRef)(eF);nk.current=eF,(0,i.useEffect)(()=>{O?.(nk.current)},[nj,O]),(0,i.useEffect)(()=>()=>{O?.(null)},[O]);let nw=(0,i.useMemo)(()=>(function(e){if(!e||0===e.length)return af;let t=0,n=0,r=0,i=0,s=0,o=0,l=0,a=0,d=0,c=new Map,u=new Map,p=(e,t,n)=>{let r=e.trim()||"unknown",i=c.get(r)??{calls:0,chars:0};n&&(i.calls+=1),i.chars+=Math.max(0,t),c.set(r,i)};for(let c of e)if(c&&"object"==typeof c){if("compactionSummary"===c.role){let e=c.summary;"string"==typeof e&&(t+=e.length);continue}if("custom"===c.role){let e=am(c.content);"compaction"===c.customType?t+=e:n+=e;continue}if("user"===c.role){r+=1,n+=am(c.content);continue}if("assistant"===c.role){for(let e of(o+=1,c.content??[]))if(e&&"object"==typeof e){if("text"===e.type)i+=(e.text??"").length;else if("thinking"===e.type)s+=(e.thinking??"").length;else if("image"===e.type)i+=4800;else if("toolCall"===e.type){a+=1;let t=e.toolName||"unknown";e.toolCallId&&u.set(e.toolCallId,t);let n=t.length;if("string"==typeof e.rawInput)n+=e.rawInput.length;else if(void 0!==e.input)try{n+=JSON.stringify(e.input).length}catch{}l+=n,p(t,n,!0)}}continue}if("toolResult"===c.role){d+=1;let e=am(c.content);l+=e,p(c.toolName||(c.toolCallId?u.get(c.toolCallId):void 0)||"unknown",e,!1);continue}if("bashExecution"===c.role){if(!c.excludeFromContext){let e=(c.command?.length??0)+(c.output?.length??0);a+=1,d+=1,l+=e,p("bash",e,!0)}continue}}return{compactionTokens:Math.ceil(t/4),userTokens:Math.ceil(n/4),userCount:r,assistantTextTokens:Math.ceil(i/4),assistantThinkingTokens:Math.ceil(s/4),assistantCount:o,toolTrafficTokens:Math.ceil(l/4),toolCallCount:a,toolResultCount:d,toolTrafficByTool:Array.from(c.entries()).map(e=>{let[t,n]=e;return{name:t,calls:n.calls,tokens:Math.ceil(n.chars/4)}}).filter(e=>e.tokens>0||e.calls>0).sort((e,t)=>t.tokens-e.tokens||t.calls-e.calls||e.name.localeCompare(t.name))}})(ev),[ev]),nS=[nw.compactionTokens,nw.userTokens,nw.userCount,nw.assistantTextTokens,nw.assistantThinkingTokens,nw.assistantCount,nw.toolTrafficTokens,nw.toolCallCount,nw.toolResultCount,nw.toolTrafficByTool.length].join("|"),nC=(0,i.useRef)(nw);nC.current=nw,(0,i.useEffect)(()=>{P?.(nC.current)},[nS,P]),(0,i.useEffect)(()=>()=>{P?.(null)},[P]);let nN=(0,i.useCallback)(async e=>{let t=l?.cwd??m;if(!t)return void e7({type:"warning",message:G("chat.dropNeedsCwd")});try{var n;let r,{status:i,data:s}=await tV(t,e,"skip");if(200!==i&&207!==i)throw Error(s.error??`HTTP ${i}`);let o=s.uploaded??[],l=s.skipped??[],a=(n=[...o,...l],r=new Set(n),e.filter(e=>r.has(e.name)).map(e=>tq(e.name,!1)).join(""));for(let e of(a&&I?.current?.insertText(a),o.length>0&&(e7({type:"success",message:G("chat.dropUploaded",{count:o.length})}),D?.()),l.length>0&&e7({type:"warning",message:G("chat.dropAlreadyExists",{names:l.join(", ")})}),s.errors??[]))e7({type:"error",message:G("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){e7({type:"error",message:G("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[e7,I,m,D,l?.cwd,G]),nE=(0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=function(e){let t=[],n=[],r=[];for(let i of e)"folder"===i.kind?r.push(i.name):i.file.type.startsWith("image/")?t.push(i.file):n.push(i.file);return{images:t,files:n,folders:r}}(e);t.length>0&&I?.current?.addImages(t),r.length>0&&e7({type:"warning",message:G("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&nN(n)},[e7,I,G,nN]),nI=(0,i.useCallback)(e=>{nE(e.map(e=>({kind:"file",file:e})))},[nE]),{isDragOver:n$,handleDragEnter:nT,handleDragOver:nM,handleDragLeave:nR,handleDrop:nA}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{tJ(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),o=(0,i.useCallback)(e=>{tJ(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:o,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(tG(t.dataTransfer))},[e])}}(x?ay:nE),nL=ev.filter(e=>rU(e)||"assistant"===e.role),nz=(0,i.useMemo)(()=>{let e=new Map(eb);for(let t of ev)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[eb,ev]),nP=(0,i.useMemo)(()=>new WeakMap,[]),nW=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ev.length-1;n>=0;n-=1){let r=function(e){if("user"!==e.role)return null;if("string"==typeof e.content){let t=e.content.trim();return t.length>0?t:null}let t=e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim();return t.length>0?t:null}(ev[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ev]),nO=(t=nL.length,(s=(0,i.useRef)([])).current=Array(t).fill(null).map((e,t)=>s.current[t]??null),s),nF=(0,i.useCallback)(()=>{nr(e=>Math.max(e,2*ev.length))},[ev.length]),nD=ts&&0===ev.length&&!tD&&!t_;tg(td,!!l?.id||!nD);let nB=l?.cwd??m??void 0,nH=(0,i.useRef)(null),n_=(0,i.useRef)(0),nU=(0,i.useRef)(null),nK=(0,i.useRef)(!1),nq=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nH.current;if(!eN||!tu){nq.current=null,n_.current=0,nK.current=!1,e&&(e.style.height="");return}let t=td.current,n=nl.current,r=tc.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let o;if(i||td.current!==t||nl.current!==n||tc.current!==r||nH.current!==e)return;let l=t.getBoundingClientRect().top,a=Math.max(0,r.getBoundingClientRect().top-l+t.scrollTop-16),d=e.getBoundingClientRect().top-l+t.scrollTop,c=(s=t.clientHeight,0===(o=Math.max(0,a))?0:Math.max(0,Math.ceil(o+s-Math.max(0,d)))),u=!nK.current;u&&(nK.current=!0),c!==n_.current&&(n_.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&tL())};nq.current=s,s();let o="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==nU.current||(nU.current=requestAnimationFrame(()=>{nU.current=null,s()}))});return o?.observe(t),o?.observe(n),o?.observe(r),()=>{i=!0,nq.current===s&&(nq.current=null),o?.disconnect(),null!==nU.current&&(cancelAnimationFrame(nU.current),nU.current=null)}},[eN,tc,ev.length,tu,td,tL]);let nV=(0,i.useCallback)(()=>{nq.current?.()},[]);(0,i.useLayoutEffect)(nV,[tD,tB,nV]);let nZ=eq?eL[`${eq.provider}:${eq.modelId}`]??null:null,nJ=eq?ez[`${eq.provider}:${eq.modelId}`]??null:null,nG=(0,r.jsx)(oY,{ref:I,onSend:th,onAbort:tm,onSideChat:N&&!a(l?.relation)?ne:void 0,onSteer:eN?tw:void 0,onFollowUp:eN?tS:void 0,onPromptWithStreamingBehavior:eN?tC:void 0,isStreaming:t_,model:eq,isAutoModelSelection:te,modelNames:e$,modelList:eT,modelError:eM,missingCwd:eR,modelScopeWarnings:eA,onModelChange:ty,modelSwitching:eZ,recentModels:tr,onSelectRecentModel:tR,onCompact:l||ts?tj:void 0,onAbortCompaction:tN,isCompacting:eB,compactError:eU,onDismissCompactError:tE,compactResult:eK,toolPreset:eP,onToolPresetChange:l&&!a(l.relation)||ts?tT:void 0,thinkingLevel:eW,isAutoThinkingSelection:tt,onThinkingLevelChange:l||ts?tM:void 0,availableThinkingLevels:nZ,thinkingLevelMap:nJ,retryInfo:eO,queuedMessages:eX,inputHistory:nW,onRecallQueue:tI,slashCommands:eG,slashCommandsLoading:eY,onLoadSlashCommands:tA,onBuiltinCommand:t$,soundEnabled:K,onSoundToggle:q,onAudioUnlock:Z,draftKey:l?.id??f??void 0,cwd:l?.cwd??m,onAttachFiles:nI});return eg?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:G("chat.loadingSession")}):ex?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ex}):(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:nT,onDragOver:nM,onDragLeave:nR,onDrop:nA,children:[n$&&!x&&(0,r.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center bg-[rgba(37,99,235,0.06)] backdrop-blur-[1px]",children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,r.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[rgba(37,99,235,0.5)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,r.jsxs)("svg",{width:"280",height:"280",viewBox:"0 0 140 140",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"drop-shadow-[0_6px_18px_rgba(37,99,235,0.18)]",children:[(0,r.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"rgba(37,99,235,0.08)",stroke:"rgba(37,99,235,0.50)",strokeWidth:"1.8"}),(0,r.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"rgba(37,99,235,0.16)",stroke:"rgba(37,99,235,0.40)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"rgba(37,99,235,0.22)",stroke:"rgba(37,99,235,0.55)",strokeWidth:"1.6"}),(0,r.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,r.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,r.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,r.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,r.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,r.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,r.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,r.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:36*!Y,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(aS,{notices:eQ,floating:!0,onPauseChange:e9})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[e0&&(0,r.jsx)(aE,{request:e0,waitingCount:e1,onRespond:e5},e0.id),e2&&(0,r.jsx)(aI,{request:e2,waitingCount:e4,onInput:e6},e2.id),!nD&&(0,r.jsxs)("div",{className:"contents",style:{visibility:x?"hidden":void 0},children:[(0,r.jsx)("div",{ref:td,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:ei?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:nl,onPointerUp:t6,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var e;let t,n,s=-1;for(let e=ev.length-1;e>=0;e--)if("user"===ev[e].role){s=e;break}let o=-1;for(let e=ev.length-1;e>=0;e--)if(rU(ev[e])){o=e;break}let a=new Map,d=0;ev.forEach((e,t)=>{(rU(e)||"assistant"===e.role)&&a.set(t,d++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??ev[e];if("custom"===n.role&&"pi-web:side-boundary"===n.customType)return(0,r.jsx)(ak,{},"side-chat-divider");if(r_(n))return null;let o=!1===t.withNotices?[]:iL(ev[e]),d=rU(n)||"assistant"===n.role,c=a.get(e),u=t.keyPrefix??"message",p=ej[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<ev.length;t++){let e=ev[t].role;if("user"===e)break;if("assistant"===e){h=!1;break}}h&&tD&&e===ev.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let m=(0,r.jsx)(iK,{message:n,toolResults:nz,modelNames:e$,cwd:nB,onOpenFile:F,onOpenSubagent:B,entryId:ey[e],searchBlock:ey[e]===np?.entryId?nf:void 0,onFork:eE||ts?void 0:tx,forking:eD===ey[e],onEditContent:t_?void 0:tv,onCancelEdit:tb,isEditing:to===ey[e],showTimestamp:h,prevTimestamp:e>0?ev[e-1].timestamp:void 0,sessionId:l?.id??ta.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?tj:void 0,isCompacting:t.recoverTruncation?eB:void 0,compactError:t.recoverTruncation?eU:void 0},`${u}-view-${p}`),f=o.length>0?(0,r.jsx)(iF,{notices:o},`${u}-notices-${p}`):null;return d&&void 0!==c?(0,r.jsxs)("div",{"data-entry-id":ey[e],ref:!1===t.attachRef?void 0:t=>{nO.current[c]=t,e===s&&(tc.current=t)},children:[m,f]},`${u}-${p}`):(0,r.jsxs)(i.Fragment,{children:[m,f]},`${u}-${p}`)},u=[];for(let e=0;e<ev.length;){let t,n=rU(ev[e]);if(!n&&0!==e){u.push(c(e)),e+=1;continue}let i=n?e:-1,s=n?e:0,l=e+1;for(;l<ev.length&&!rU(ev[l]);)l+=1;let d=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&rG(r).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}(ev,i,l);if(-1===d||(t_||tD)&&l===ev.length&&i===o){for(let e=s;e<l;e++)u.push(c(e));e=l;continue}n&&u.push(c(i));let p=n&&ey[i]?function(e,t,n){let r,i,s,o=r7(e[t]?.timestamp);if(void 0===o)return;let l=!1,a=0;for(let o=t+1;o<n;o++){let t=e[o];if("assistant"===t.role){var d;void 0!==i&&void 0!==s&&(a+=Math.max(0,s-i)),i=s=void 0;let e=function(e){if("assistant"!==e.role)return;let t=r7(e.timestamp),n=r7(e.durationMs);return void 0!==t&&void 0!==n?t+n:void 0}(t);l=void 0!==e,void 0!==e&&(r=Math.max(r??e,e)),void 0!==e&&"assistant"===(d=t).role&&("stop"===d.stopReason||"length"===d.stopReason)&&(i=r)}else if("toolResult"===t.role){let e=r7(t.timestamp);void 0!==e&&(r=Math.max(r??e,e))}else if(void 0!==i){let e=r7(t.timestamp);void 0!==e&&(s=Math.max(s??e,e))}}if(l&&void 0!==r)return Math.max(0,r-o-a)}(ev,i,l):void 0,h=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=rG(t),i=r.length>0||rV(t)||rZ(t)?r9(t,r):null,s=t.content.indexOf(r[0]),o={answer:i,process:r9(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i})};return e.set(t,o),o}(nP,ev[d]),m=h.answer,f=[],g=0,x=0,v=!1;for(let e=i+1;e<=d;e++){let n=ev[e];if("custom"===n.role){if(r_(n))continue;v||=!!(np&&np.entryId===ey[e]),g+=1,f.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let i=e===d?h.process:n,s=e!==d||!m,o=rq(i);if(0===o.length){let t=s?iL(n):[];t.length>0&&f.push((0,r.jsx)(iF,{notices:t},`process-notices-${ej[e]}`));continue}t??=a.get(e),x+=o.filter(e=>"toolCall"===e.type).length,g+=1,v||=!!(np&&ey[e]===np.entryId&&(!nf||o.includes(nf))),f.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:i,showTimestamp:!1,withNotices:s}))}if(0===g)u.push(...f);else if(f.length>0){let e=(m?.content??[]).some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0),n=function(e){let t;for(let n of e)for(let e of iL(n))"cache_miss"===e.kind&&(t??={count:0,missedTokens:0,missedCost:0},t.count+=1,t.missedTokens+=e.missedTokens,t.missedCost+=e.missedCost);return t}(ev.slice(i+1,m?d:d+1));u.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nO.current[t]=e},children:(0,r.jsx)(ab,{messageCount:g,toolCallCount:x,durationMs:p,cacheMisses:n,defaultExpanded:!e,reveal:v,t:G,children:f},e?"answered":"unanswered")},`process-group-${ej[s]}`))}if(m){let e=[];for(let t=i+1;t<=d;t++){let n=ev[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=function(e,t){let n=e.writtenFiles;return n&&n.length===t.length&&n.every((e,n)=>e.filePath===t[n].filePath)?n:(e.writtenFiles=t,t)}(h,function(e,t,n){let r=new Set,i=[];for(let o of e){var s;if("toolCall"!==o.type||!(rX(s=o.toolName)||rQ(s))&&!r0(o.toolName))continue;let e=t?.get(o.toolCallId);if(e&&!e.isError)for(let t of r0(o.toolName)?function(e,t){let n=t?.details,r=function(e,t){let n=new Set;if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.preview;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.files;if(Array.isArray(t))for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&"delete"===e.operation&&"string"==typeof e.filePath&&e.filePath.length>0&&n.add(e.filePath)}}for(let t of r1(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!r2(e)||!r2(e.result))return null;let t=e.result.appliedFiles;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):null}(n);if(i)return i.filter(e=>!r.has(e));if(r4(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=r6(r5(n.preview));if(e.length>0)return e}return r6(r3(r1(e)))}(o.input,e):[function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(o.input)]){if(!t)continue;let e=(0,rY.XK)(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,nz,nB));u.push(c(d,{messageOverride:m,writtenFiles:t,turnDurationMs:0===f.length?p:void 0,recoverTruncation:l===ev.length&&!tD&&!rJ(m)}))}for(let e=d+1;e<l;e++)u.push(c(e));e=l}let{startIndex:p}=(t=Math.min(Math.max(nn,0),Math.max(e=u.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||ew;return(0,r.jsxs)(r.Fragment,{children:[h&&(0,r.jsx)("div",{ref:no,className:"py-3 text-center text-xs text-text-muted",children:G("chat.loadEarlier")}),u.slice(p)]})})(),tD&&tB&&(0,r.jsx)(aw,{store:eC,onCommit:nV,toolResults:nz,modelNames:e$,cwd:nB,onOpenFile:F,onOpenSubagent:B}),(eN||eB)&&!tB&&(ti||eB)&&(0,r.jsx)("div",{className:"break-words py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(n)return r>0?t("chat.compactingQueued",{count:r}):t("chat.compacting");if(e?.kind==="running_tools"){let n=e.tools[e.tools.length-1];if(n?.progress)return`${t("chat.runningNamedTool",{name:n.name})} ${n.progress}`;let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(ti,G,eB,(eX?.steering.length??0)+(eX?.followUp.length??0))})}),eE&&!eI&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:G("chat.runningCommand")})}),eI&&(0,r.jsx)(iK,{message:{role:"bashExecution",command:eI.command,output:"",excludeFromContext:eI.excludeFromContext},sessionId:l?.id??ta.current??void 0,onOpenSubagent:B}),(0,r.jsx)("div",{ref:nH,"aria-hidden":"true"})]})})}),Y||ei?null:(0,r.jsx)(le,{messages:ev,getStreamingMessage:tH,scrollContainer:td,messageRefs:nO,onRevealHistory:nF,turnsBefore:eS,railSlot:t8})]})]}),x&&(0,r.jsx)("div",{id:li,role:"tabpanel","aria-labelledby":lr,className:"absolute inset-0 z-10",style:{background:"var(--bg)",bottom:"env(safe-area-inset-bottom)"},children:x}),!Y&&(0,r.jsx)("div",{ref:t3,className:"absolute bottom-0 right-0 top-0 z-30 flex empty:pointer-events-none",style:{width:36,visibility:x?"hidden":void 0}}),H&&tU&&(0,tk.createPortal)((0,r.jsx)("div",{ref:t2,role:tZ?"dialog":"toolbar","aria-label":G(tZ?"chat.newQuoteChat":"chat.selectionActions"),style:{position:"fixed",top:tU.top,left:tU.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tZ?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tZ?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tZ?(0,r.jsxs)("fieldset",{disabled:tX,"aria-busy":tX,style:{width:"100%",minWidth:0,margin:0,padding:0,border:"none",display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:600},children:G("chat.askInSideChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:G("i18n.close"),"aria-label":G("i18n.close"),disabled:tX,onClick:t5,style:{border:"none"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,r.jsx)(oY,{ref:t4,compact:!0,onSend:t7,onAbort:t5,isStreaming:!1}),t0&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:t0})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:G("chat.quoteSelection"),"aria-label":G("chat.quoteSelection"),onPointerDown:e=>e.preventDefault(),onClick:t9,style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}),(0,r.jsx)("path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"})]}),(0,r.jsx)("span",{children:G("chat.quoteSelection")})]}),N&&!a(l?.relation)&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:G("chat.askInSideChat"),"aria-label":G("chat.askInSideChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tY(!0),window.getSelection()?.removeAllRanges()},style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"})}),(0,r.jsx)("span",{children:G("chat.askInSideChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative flex min-h-0 flex-col",style:{visibility:x?"hidden":void 0},children:[!nD&&!x&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!Y,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${tl&&!ei?" is-visible":""}`,title:G("chat.scrollToLatest"),"aria-label":G("chat.scrollToLatest"),onClick:()=>tO("smooth"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12l7 7 7-7"})})})}),nD&&(0,r.jsx)("div",{className:"new-session-hero",style:{paddingLeft:16,paddingRight:Y?16:52},children:(0,r.jsxs)("div",{className:"new-session-hero-inner",style:{maxWidth:"var(--chat-content-max-width, 820px)"},children:[(0,r.jsxs)("div",{className:"new-session-brand",children:[(0,r.jsx)(rR.A,{src:"/icons/apple-touch-icon.png",width:40,height:40,alt:"",priority:!0,className:"new-session-logo"}),(0,r.jsxs)("div",{className:"new-session-brand-text",children:[(0,r.jsx)("span",{className:"new-session-brand-name",children:"Pi Web"}),(0,r.jsxs)("span",{className:"new-session-meta",children:[(0,r.jsxs)("span",{children:["web v","1.6.1"]}),(0,r.jsx)(av,{label:e=>G("appUpdate.releaseNotes",{version:e})}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,r.jsxs)("span",{className:"new-session-meta-pi",children:["pi v","1.4.0"]})]})]})]}),g]})}),nG,(0,r.jsx)(lc,{statuses:e8,widgets:e3,onCommand:th,commandsDisabled:t_})]}),nD&&(0,r.jsx)("div",{className:"min-h-0 flex-1"}),ea&&(0,r.jsx)(lp,{onClose:()=>ed(!1)}),ec&&(0,r.jsx)(rf,{sessionId:ec,leafId:tW,onClose:()=>eu(null)}),ep&&(0,r.jsx)(tz,{sessionId:ep,leafId:tW,onExported:e=>{e7({type:"success",message:G("export.savedTo",{path:e})})},onClose:()=>eh(null)}),em.open&&(0,r.jsx)(ns,{initialPath:em.initialPath,cwd:l?.cwd??m,onClose:()=>ef({open:!1}),onImported:e=>{ef({open:!1}),e7({type:"success",message:G("import.importedNotice")}),S?.(e)}})]})}function ak(){let{t:e}=(0,tn.s)();return(0,r.jsxs)("div",{role:"separator",className:"my-4 flex items-center gap-3 text-xs",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}}),(0,r.jsx)("span",{children:e("sideChat.divider")}),(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}})]})}let aw=(0,i.memo)(function(e){let{store:t,onCommit:n,toolResults:s,modelNames:o,cwd:l,onOpenFile:a,onOpenSubagent:d}=e,c=ac(t,ah);return((0,i.useLayoutEffect)(n,[c,n]),c)?(0,r.jsx)(iK,{message:c,toolResults:s,isStreaming:!0,modelNames:o,cwd:l,onOpenFile:a,onOpenSubagent:d}):null});function aS(e){let{notices:t,floating:n=!1,onPauseChange:i}=e;return 0===t.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!n},children:t.map((e,s)=>{var o;let l,a,d,c="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>i?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||i?.(null)},onFocus:()=>i?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||i?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(s!==t.length-1),overflow:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:n?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:14,lineHeight:1.5,transformOrigin:"top right",animation:e.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:c,flexShrink:0,marginTop:25.5}}),(0,r.jsx)("span",{tabIndex:0,style:{padding:"18.5px 0",minWidth:0,maxWidth:"100%",maxHeight:498,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:(o=e.message,l=[],a=(e,t)=>{if(!t)return;let n=l[l.length-1];n?.kind===e?n.text+=t:l.push({kind:e,text:t})},d=!1,o.split("\n").forEach((e,t)=>{let n=rD.test(e);t>0&&a(n&&d?"art":"text","\n"),a(n?"art":"text",e),d=n}),l).map((e,t)=>"art"===e.kind?(0,r.jsx)("span",{style:{display:"inline-block",verticalAlign:"top",maxWidth:"100%",overflowX:"auto",whiteSpace:"pre",fontFamily:"Menlo, Consolas, 'DejaVu Sans Mono', monospace",lineHeight:1,color:"var(--text)"},children:e.text},t):e.text)})]},e.id)})})}function aC(e){let{count:t}=e,{t:n}=(0,tn.s)();return t<=0?null:(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionMoreWaiting",{count:t})})}function aN(e){let{expanded:t}=e;return(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t?(0,r.jsx)("path",{d:"M3.5 1v2.5H1M6.5 1v2.5H9M6.5 9v-2.5H9M3.5 9v-2.5H1"}):(0,r.jsx)("path",{d:"M1 3.5V1h2.5M6.5 1H9v2.5M9 6.5V9H6.5M3.5 9H1V6.5"})})}function aE(e){let{request:t,waitingCount:n,onRespond:s}=e,{t:o}=(0,tn.s)(),[l,a]=(0,i.useState)("editor"===t.method?t.prefill??"":""),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>g(e=>!e),[]),[v,b]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),j=function(e){if("select"===e.method&&e.options.length>0)return e.options[0];if("confirm"===e.method){let t=e.message.split("\n").find(e=>e.trim());return t?.trim()}}(t),k=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-v)/1e3));(0,i.useLayoutEffect)(()=>{if(d)return;let e=u.current,t=p.current;if(!e||!t)return;let n=!1,r=()=>{if(n)return;let r=t.querySelectorAll("pre, .markdown-table-wrap");if(0===r.length)return;t.classList.add("extension-dialog-measuring");let i=Array.from(r,e=>e.scrollWidth-e.clientWidth);t.classList.remove("extension-dialog-measuring");let s=function(e,t){let n=0;for(let e of t)e>1&&e>n&&(n=e);return 0===n?null:40*Math.ceil((e+n)/40)}(e.offsetWidth,i);null!==s&&m(e=>null!==e&&e>=s?e:s)};r();let i=new MutationObserver(r);return i.observe(t,{childList:!0,subtree:!0,characterData:!0}),document.fonts?.ready.then(r),()=>{n=!0,i.disconnect()}},[d]),(0,i.useEffect)(()=>{if(void 0===t.expiresAt)return;let e=setInterval(()=>b(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let w=null!==k&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:o("chat.extensionExpiresIn",{seconds:k})}),S=()=>{"confirm"===t.method?s(t,{confirmed:!0}):s(t,{value:l})};return(0,r.jsx)("div",{onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),e.stopPropagation(),s(t,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:o("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:t.title}),j&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:j}),(0,r.jsx)(aC,{count:n}),w,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:o("chat.extensionExpand")})]}):(0,r.jsxs)("div",{ref:u,role:"dialog","aria-label":t.title,style:{pointerEvents:"auto",width:f?"100%":`min(${h??560}px, 100%)`,maxHeight:f?"100%":"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{flexShrink:1,minHeight:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)",maxHeight:"50vh",overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.title}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:o("chat.extensionRequest")}),(0,r.jsx)(aC,{count:n}),w]})]}),(0,r.jsx)("button",{type:"button",onClick:x,title:o(f?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":o(f?"chat.extensionRestoreSize":"chat.extensionMaximize"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(aN,{expanded:f})}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:o("chat.extensionCollapse"),"aria-label":o("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})]}),(0,r.jsxs)("div",{ref:p,style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===t.method&&(0,r.jsx)(is.m,{children:t.message}),"select"===t.method&&(0,r.jsx)("div",{onKeyDown:e=>{if(!["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(e.key))return;let t=Array.from(e.currentTarget.querySelectorAll("[data-extension-option]")),n=t.indexOf(e.target);if(n<0)return;e.preventDefault();let r="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key||"ArrowRight"===e.key?1:-1)+t.length)%t.length;t[r].focus({preventScroll:!0}),t[r].scrollIntoView({block:"nearest"})},style:{display:"grid",gap:8},children:t.options.map((e,n)=>(0,r.jsx)("div",{role:"button",tabIndex:0,"data-extension-option":!0,"aria-label":e,ref:0===n?y:void 0,onClick:()=>s(t,{value:e}),onKeyDown:n=>{("Enter"===n.key||" "===n.key)&&(n.preventDefault(),s(t,{value:e}))},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:13,overflowWrap:"anywhere",scrollMargin:14},children:(0,r.jsx)("div",{inert:!0,children:(0,r.jsx)(is.m,{children:e})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:l,placeholder:t.placeholder,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||S()},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===t.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:l,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&S()},style:{width:"100%",minHeight:220,padding:10,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===t.method||"select"===t.method&&0===t.options.length,onClick:()=>s(t,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:o("chat.cancel")}),"confirm"===t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:o("chat.confirm")}):"select"!==t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:o("chat.submit")}):null]})]})})}function aI(e){let{request:t,waitingCount:n,onInput:s}=e,{t:o}=(0,tn.s)(),l=(0,i.useRef)(null),a=(0,i.useRef)(!1),[d,c]=(0,i.useState)(!1),u=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(rz,""),i=rP(e).trimEnd();if(t.test(i))continue;let s=e,o=rF(s);("│"===o||"┃"===o)&&" "===rF(s=rO(s,0))&&(s=rO(s,0));let l=function(e){let t=rW(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),a=l>=0?rW(s)[l]?.char:void 0;("│"===a||"┃"===a)&&(s=rO(s,l)),n.push(function(e){let t=e;for(;;){let e=rW(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(s))}for(;n.length>0&&""===rP(n[0]).trim();)n.shift();for(;n.length>0&&""===rP(n[n.length-1]).trim();)n.pop();return n.length?n:e}(t.lines),p=u.find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{d||l.current?.focus()},[d]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:o("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:o("chat.extensionPanel")}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:p}),(0,r.jsx)(aC,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:o("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||l.current?.focus()},style:{pointerEvents:"auto",position:"relative",width:"max-content",minWidth:"min(920px, 100%)",maxWidth:"100%",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:l,"aria-label":o("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(a.current||e.nativeEvent.isComposing)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=rH[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":rB[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),s(t,n))},onInput:e=>{if(a.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&s(t,n)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:e=>{a.current=!1;let n=e.currentTarget;queueMicrotask(()=>{let e=n.value;n.value="",e&&s(t,e)})},onPaste:e=>{e.preventDefault();let n=e.clipboardData.getData("text");n&&s(t,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:o("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(aC,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:o("chat.extensionCollapse"),"aria-label":o("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("button",{onClick:()=>s(t,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:o("chat.close")})]})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,minHeight:0,overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(0,r.jsx)(ll,{text:u.join("\n")})})]})})}let a$=null,aT=null;function aM(){return aT??=Promise.all([n.e(1650),n.e(7379)]).then(n.bind(n,7379)).then(e=>{a$=e.TrajectoryView},e=>{throw aT=null,e})}function aR(e){let[t,n]=(0,i.useState)(()=>a$);return(0,i.useEffect)(()=>{if(null!==t)return;let e=!1;return aM().then(()=>{e||n(()=>a$)},()=>{}),()=>{e=!0}},[t]),null===t?null:(0,r.jsx)(t,{...e})}let aA=null,aL="";function az(e){let{context:t,mobile:n,initialFocus:s,onInitialFocusDone:o,onPick:l,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u}=e,{t:p}=(0,tn.s)(),[h,m]=(0,i.useState)(()=>aL),f=(0,i.useRef)(null),g=(0,i.useRef)(s),x=(0,i.useRef)(o);return x.current=o,(0,i.useEffect)(()=>{if(aL)return;let e=!1;return(aA??=fetch("/api/home").then(e=>e.json()).then(e=>aL=e.home??"").catch(()=>(aA=null,""))).then(t=>{!e&&t&&m(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=g.current;if(!e)return;g.current=null,x.current();let t=f.current;eB(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(rh,{handleRef:f,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:l,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u})})}var aP=n(55961),aW=n(50640),aO=n(7644),aF=n(96793),aD=n(99220),aB=n(35754);function aH(e){return e&&"number"==typeof e.size&&"string"==typeof e.mtime?`${e.size}:${e.mtime}`:null}function a_(e,t){return null===e||null===t||e!==t}let aU=`<script data-pi-web-polyfill="storage">
9
+ (function() {
10
+ function createMemoryStorage() {
11
+ var store = Object.create(null);
12
+ function hasKey(key) { return Object.prototype.hasOwnProperty.call(store, key); }
13
+ var storage = Object.create({
14
+ getItem: function(key) {
15
+ if (arguments.length < 1) throw new TypeError("getItem requires a key");
16
+ key = String(key);
17
+ return hasKey(key) ? store[key] : null;
18
+ },
19
+ setItem: function(key, value) {
20
+ if (arguments.length < 2) throw new TypeError("setItem requires a key and value");
21
+ store[String(key)] = String(value);
22
+ },
23
+ removeItem: function(key) {
24
+ if (arguments.length < 1) throw new TypeError("removeItem requires a key");
25
+ delete store[String(key)];
26
+ },
27
+ clear: function() { store = Object.create(null); },
28
+ key: function(index) {
29
+ if (arguments.length < 1) throw new TypeError("key requires an index");
30
+ var key = Object.keys(store)[(+index) >>> 0];
31
+ return key === undefined ? null : key;
32
+ },
33
+ get length() { return Object.keys(store).length; }
34
+ });
35
+ // Storage also exposes its keys as named properties, apart from the API's
36
+ // own names (which remain callable even if a key has the same name).
37
+ return new Proxy(storage, {
38
+ get: function(target, key, receiver) {
39
+ if (typeof key === "string" && !(key in target)) return store[key];
40
+ return Reflect.get(target, key, receiver);
41
+ },
42
+ set: function(target, key, value, receiver) {
43
+ if (typeof key !== "string") return Reflect.set(target, key, value, receiver);
44
+ target.setItem(key, value);
45
+ return true;
46
+ },
47
+ deleteProperty: function(target, key) {
48
+ if (typeof key !== "string") return Reflect.deleteProperty(target, key);
49
+ target.removeItem(key);
50
+ return true;
51
+ },
52
+ has: function(target, key) {
53
+ return key in target || (typeof key === "string" && hasKey(key));
54
+ },
55
+ ownKeys: function(target) {
56
+ var own = Reflect.ownKeys(target);
57
+ return own.concat(Object.keys(store).filter(function(key) { return own.indexOf(key) === -1; }));
58
+ },
59
+ getOwnPropertyDescriptor: function(target, key) {
60
+ var own = Reflect.getOwnPropertyDescriptor(target, key);
61
+ if (own || typeof key !== "string" || !hasKey(key)) return own;
62
+ return { value: store[key], writable: true, enumerable: true, configurable: true };
63
+ }
64
+ });
65
+ }
66
+
67
+ function polyfillStorage(type) {
68
+ try {
69
+ window[type].getItem("__pi_web_storage_probe__");
70
+ } catch (error) {
71
+ if (error && error.name === "SecurityError") {
72
+ Object.defineProperty(window, type, {
73
+ value: createMemoryStorage(), configurable: true, enumerable: true
74
+ });
75
+ }
76
+ }
77
+ }
78
+ polyfillStorage("localStorage");
79
+ polyfillStorage("sessionStorage");
80
+ })();
81
+ <\/script>`,aK=/\uFEFF?(?:\s|<!--[\s\S]*?-->|<!doctype\b[^>]*>|<\?[^>]*>)*/iy,aq=/<html(?=[\s/>])(?:[^>"']|"[^"]*"|'[^']*')*>(?:\s|<!--[\s\S]*?-->)*/iy,aV=/<head(?=[\s/>])(?:[^>"']|"[^"]*"|'[^']*')*>/iy;function aZ(e,t,n){return e.lastIndex=n,e.exec(t)?e.lastIndex:n}var aJ=n(73620);let aG=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function aY(e){let t=function(e){let t=aG.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,aJ.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}function aX(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}var aQ=n(22408);let a0=[",",";"," ","|"];function a1(e){let t=/\.(csv|tsv)$/i.exec(e);return t?"tsv"===t[1].toLowerCase()?" ":",":null}function a2(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.complete??!0,i=n.maxRecords??1/0,s=[],o=[],l=e.length,a=t.charCodeAt(0),d=+(65279===e.charCodeAt(0)),c=1,u=[],p=1,h=()=>{(1!==u.length||""!==u[0])&&(s.push(u),o.push(p)),u=[]};for(;d<l&&s.length<i;){let t="",n=!1;if(34===e.charCodeAt(d)){n=!0;let r=d+=1;for(;d<l;){let i=e.indexOf('"',d);if(-1===i)break;if(34===e.charCodeAt(i+1)){t+=e.slice(r,i+1),r=d=i+2;continue}t+=e.slice(r,i),d=i+1,n=!1;break}n&&(t+=e.slice(r),d=l),c+=function(e){let t=0,n=e.indexOf("\n");for(;-1!==n;)t+=1,n=e.indexOf("\n",n+1);return t}(t)}let i=d;for(;i<l;){let t=e.charCodeAt(i);if(t===a||10===t)break;i+=1}let s=i<l?e.charCodeAt(i):-1,o=s!==a&&i>d&&13===e.charCodeAt(i-1)?i-1:i;t+=e.slice(d,o),u.push(t),d=i,s===a?(d+=1)===l&&(u.push(""),r&&h()):10===s?(d+=1,c+=1,h(),p=c):r&&h()}return{records:s,lines:o}}function a4(e){let t=e.indexOf("\n"),n=-1===t?e:e.slice(0,t),r=0;for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);t>=56320&&t<=57343||(r+=t>=11904?2:1)}return r}let a8={display:"flex",height:26,boxSizing:"border-box",borderBottom:"1px solid var(--border)"},a3={position:"sticky",left:0,zIndex:1,boxSizing:"border-box",width:56,flexShrink:0,padding:"0 10px",display:"flex",alignItems:"center",justifyContent:"flex-end",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontSize:11,fontVariantNumeric:"tabular-nums",userSelect:"none"},a5={boxSizing:"border-box",flexShrink:0,padding:"0 10px",lineHeight:"25px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderRight:"1px solid var(--border)"};function a6(e){let{content:t,filePath:n,complete:s,scrollRef:o}=e,l=(0,i.useMemo)(()=>(function(e,t){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2],r=a1(t)??",",i=","===r?function(e){let t=e.slice(0,65536),n=t.length===e.length,r=",",i=0;for(let e of a0){let{records:s}=a2(t,e,{complete:n,maxRecords:20}),o=s[0]?.length??0;if(o<2)continue;let l=1e3*s.filter(e=>e.length===o).length+Math.min(o,999);l>i&&(r=e,i=l)}return r}(e):r,{records:s,lines:o}=a2(e,i,{complete:n});if(0===s.length)return{columns:[],headerLine:0,rows:[],rowLines:[]};let l=0;for(let e of s)e.length>l&&(l=e.length);let a=s[0];return{columns:a.length===l?a:[...a,...Array.from({length:l-a.length},()=>"")],headerLine:o[0],rows:s.slice(1),rowLines:o.slice(1)}})(t,n,s),[s,t,n]),a=(0,i.useMemo)(()=>{var e,t;let n;return e=l.columns,n=Math.max(1,Math.ceil((t=l.rows).length/500)),e.map((e,r)=>{let i=a4(e);for(let e=0;e<t.length;e+=n){let n=t[e][r];if(n){let e=a4(n);e>i&&(i=e)}}return Math.min(Math.max(Math.ceil(7.4*i+22),64),420)})},[l]),d=(0,i.useMemo)(()=>a.reduce((e,t)=>e+t,56),[a]),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(0);if((0,i.useEffect)(()=>{let e=o.current;if(!e)return;let t=null,n=()=>{u(e.scrollTop),h(e.clientHeight)},r=()=>{null===t&&(t=requestAnimationFrame(()=>{t=null,n()}))};n(),e.addEventListener("scroll",r,{passive:!0});let i="u"<typeof ResizeObserver?null:new ResizeObserver(n);return i?.observe(e),()=>{e.removeEventListener("scroll",r),i?.disconnect(),null!==t&&cancelAnimationFrame(t)}},[o]),0===l.columns.length)return null;let{start:m,end:f}=function(e,t,n){if(e<=0)return{start:0,end:0};let r=Number.isFinite(t)?Math.max(0,t):0,i=Number.isFinite(n)&&n>0?n:800,s=Math.max(0,Math.floor(r/26)-20),o=Math.min(e,Math.ceil((r+i)/26)+20);return{start:Math.min(s,o),end:o}}(l.rows.length,c-26,p),g=[];for(let e=m;e<f;e+=1){let t=l.rows[e];g.push((0,r.jsxs)("div",{role:"row","aria-rowindex":e+2,style:{...a8,position:"absolute",top:26*e,left:0,width:d},children:[(0,r.jsx)("div",{role:"rowheader",style:a3,children:l.rowLines[e]}),a.map((e,n)=>{let i=t[n]??"";return(0,r.jsx)("div",{role:"cell",style:{...a5,width:e},title:i||void 0,children:i},n)})]},e))}return(0,r.jsxs)("div",{role:"table","aria-rowcount":l.rows.length+1,"aria-colcount":l.columns.length,style:{width:d,minWidth:"100%",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:12,color:"var(--text-muted)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{role:"row","aria-rowindex":1,style:{...a8,position:"sticky",top:0,zIndex:2,width:d,background:"var(--bg-panel)",color:"var(--text)",fontWeight:600},children:[(0,r.jsx)("div",{role:"rowheader",style:a3,children:l.headerLine}),l.columns.map((e,t)=>(0,r.jsx)("div",{role:"columnheader",style:{...a5,width:a[t]},title:e||void 0,children:e},t))]}),(0,r.jsx)("div",{style:{position:"relative",height:26*l.rows.length},children:g})]})}let a9=["tags","categories","keywords","tag","category"];function a7(e){var t;let{data:n}=e;if(!n)return null;let i=Object.entries(n);if(0===i.length)return null;let s="string"==typeof(t=n.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,o=a9.find(e=>Array.isArray(n[e])),l=o?n[o].map(aX).filter(Boolean):[],a=i.filter(e=>{let[t]=e;return t!==o&&("title"!==t||!s)});return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[s&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:s}),l.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:l.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),a.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:a.map(e=>{let[t,n]=e;return(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:t}),(0,r.jsx)("dd",{children:function(e){let t=aX(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(n)})]},t)})})]})}let de=new Set(["md","markdown","mdx","mdown","mkd","rst","adoc","txt"]),dt={source:"Source",preview:"Preview",diff:"Diff"},dn={fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:13,lineHeight:1.6},dr={...aO.xJ,'pre[class*="language-"]':{...aO.xJ['pre[class*="language-"]']}};delete dr['pre[class*="language-"]'].background;let di={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"},ds={...di,position:"sticky",left:0,zIndex:1};function dl(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function da(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function dd(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=da(n.startContainer),i=da(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),o=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(o))return null;if(s<o){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(o=Number((i=e).dataset.lineNumber))}}}return s>o?null:{startLine:s,endLine:o}}function dc(e){let{rows:t,stylesheet:n,useInlineStyles:i,wrapLines:s}=e;return t.map((e,t)=>{let o=e.children??[],l=o[0]?.properties?.className,a=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=a?o[0]:null,c=a?o.slice(1):o;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,aW.Ay)({node:d,stylesheet:n,useInlineStyles:i,key:`source-line-number-${t}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:s?"anywhere":"normal",whiteSpace:s?"pre-wrap":"pre"},children:c.map((e,r)=>(0,aW.Ay)({node:e,stylesheet:n,useInlineStyles:i,key:`source-token-${t}-${r}`}))})]},`source-line-${t}`)})}function du(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=(0,tH.HG)(e),s=new URLSearchParams({type:t});for(let[e,i]of(n&&s.set("sessionId",n),"watch"===t&&s.set("holder",e_()),Object.entries(r)))void 0!==i&&s.set(e,String(i));return`/api/files/${i}?${s.toString()}`}function dp(e){let{filePath:t,sourceSessionId:n}=e,{t:i}=(0,tn.s)();return(0,r.jsx)("a",{href:du(t,"download",n),download:(0,tH.WP)(t),title:i("i18n.downloadFile"),"aria-label":i("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function dh(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function dm(e){let t,{patch:n,wrapLines:i}=e,{t:s}=(0,tn.s)(),o=(t=iu(n))?t.flatMap(ip):[],l=e=>"added"===e.type||"removed"===e.type;if(!o.some(l))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:s("i18n.noChanges")});let a=new Set(o.flatMap((e,t)=>l(e)?[t]:[])),d=new Set;for(let e of a)for(let t=Math.max(0,e-3);t<=Math.min(o.length-1,e+3);t++)d.add(t);let c=d.size<=1e3?ds:di,u=e=>"gap"!==o[e].type&&d.has(e),p=[],h=0;for(;h<o.length;)if(u(h)){let e=[];for(;h<o.length&&u(h);){let t=o[h];"gap"!==t.type&&e.push(t),h++}p.push({hidden:!1,lines:e})}else{let e=0;for(;h<o.length&&!u(h);){let t=o[h],n="gap"===t.type?t.count:1;e=null===e||null===n?null:e+n,h++}p.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:i?"100%":"max-content",minWidth:"100%",...dn},children:p.map((e,t)=>{if(e.hidden)return(0,r.jsx)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:null===e.count?"⋯":`⋯ ${ih(e.count,s)}`},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",s="added"===e.type?"+":"removed"===e.type?"-":" ",o="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:c,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:o,userSelect:"none",flexShrink:0,fontWeight:600},children:s}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:+!!i,minWidth:0,padding:"0 8px 0 0",whiteSpace:i?"pre-wrap":"pre",overflowWrap:i?"anywhere":"normal",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function df(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:o=!0}=e,{t:l}=(0,tn.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),j=(0,tH.WP)(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),f(null),x(null),d(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!o)return;let e=!0,n=eV("file-watch",new EventSource(du(t,"watch",s)),t);v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(du(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=aH(t);a_(y.current,r)&&(y.current=r,f(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=aH(t),"number"==typeof t.size&&h(t.size)}catch{}f(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,o]);let k=du(t,"read",s,c?{v:c}:void 0),w=null!=p?dh(p):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:(0,tH.qP)(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:j||"image"}),m&&(0,r.jsxs)("span",{children:[m.w," \xd7 ",m.h]}),w&&(0,r.jsx)("span",{children:w}),(0,r.jsxs)("span",{title:a?l("i18n.liveSync"):l("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(dp,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:g?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:g}):(0,r.jsx)("img",{src:k,alt:t,onLoad:e=>{let t=e.currentTarget;f({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>x(l("files.imageLoadFailed")),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function dg(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}function dx(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:o=!0}=e,{t:l}=(0,tn.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),j=(0,tH.WP)(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),f(null),x(null),d(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!o)return;let e=!0,n=eV("file-watch",new EventSource(du(t,"watch",s)),t);v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(du(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=aH(t);a_(y.current,r)&&(y.current=r,f(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=aH(t),"number"==typeof t.size&&h(t.size)}catch{}f(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,o]);let k=du(t,"read",s,c?{v:c}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:(0,tH.qP)(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:j||"audio"}),null!=m&&(0,r.jsx)("span",{children:dg(m)}),null!=p&&(0,r.jsx)("span",{children:dh(p)}),(0,r.jsxs)("span",{title:a?l("i18n.liveSync"):l("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(dp,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:k,onLoadedMetadata:e=>f(e.currentTarget.duration),onError:()=>x(l("files.audioLoadFailed")),style:{width:"100%"}},k)]})})]})}function dv(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:o=!0}=e,{t:l}=(0,tn.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),j=(0,tH.WP)(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),f(null),x(null),d(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!o)return;let e=!0,n=eV("file-watch",new EventSource(du(t,"watch",s)),t);v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(du(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=aH(t);a_(y.current,r)&&(y.current=r,f(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=aH(t),"number"==typeof t.size&&h(t.size)}catch{}f(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,o]);let k=du(t,"read",s,c?{v:c}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:(0,tH.qP)(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:j||"video"}),null!=m&&(0,r.jsx)("span",{children:dg(m)}),null!=p&&(0,r.jsx)("span",{children:dh(p)}),(0,r.jsxs)("span",{title:a?l("i18n.liveSync"):l("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(dp,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)",minHeight:0},children:(0,r.jsxs)("div",{style:{width:"min(960px, 100%)",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:0},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:k,onLoadedMetadata:e=>f(e.currentTarget.duration),onError:()=>x(l("files.videoLoadFailed")),style:{maxWidth:"100%",maxHeight:"100%"}},k)]})})]})}function db(e){let{filePath:t,cwd:n,sourceSessionId:s,initialPage:o,watchEnabled:l=!0}=e,{t:a}=(0,tn.s)(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(0),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),b=(0,i.useRef)(null),y=(0,aB.GO)(t),j="pdf"===y,k=j&&o&&o>0?`#page=${o}`:"",w=j?`${du(t,"read",s,u?{v:u}:void 0)}${k}`:du(t,"preview",s,u?{v:u}:void 0);return(0,i.useEffect)(()=>{p(0),m(null),g(null),c(!1),b.current=null;let e=!0,n=++v.current;return fetch(du(t,"meta",s)).then(e=>e.json()).then(t=>{e&&n===v.current&&(t.error&&g(t.error),"number"==typeof t.size&&(m(t.size),!j&&t.size>aB.jL&&g("DOCX too large for preview (>10MB)")))}).catch(t=>{e&&n===v.current&&g(String(t))}),()=>{e=!1}},[t,j,s]),(0,i.useEffect)(()=>{if(c(!1),x.current&&(x.current.close(),x.current=null),!l)return;let e=!0,n=eV("file-watch",new EventSource(du(t,"watch",s)),t);x.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++v.current,fetch(du(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==v.current)return;if(t.error)return void g(t.error);if("number"==typeof t.size&&(m(t.size),!j&&t.size>aB.jL))return void g("DOCX too large for preview (>10MB)");g(null);let r=aH(t);a_(b.current,r)&&(b.current=r,p(e=>e+1))}).catch(t=>{e&&n===v.current&&g(String(t))})}),n.addEventListener("change",e=>{v.current+=1,b.current=null;try{let t=JSON.parse(e.data);if(b.current=aH(t),"number"==typeof t.size&&(m(t.size),!j&&t.size>aB.jL))return void g("DOCX too large for preview (>10MB)")}catch{}g(null),p(e=>e+1)});let r=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),x.current===n&&(x.current=null)}},[t,j,s,l]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:(0,tH.qP)(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===y?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:dh(h)}),(0,r.jsx)(dp,{filePath:t,sourceSessionId:s}),(0,r.jsxs)("span",{title:a(d?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:d?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:d?"#4ade80":"var(--border)",display:"inline-block",boxShadow:d?"0 0 4px #4ade80":"none"}}),d?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:f?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:f}):(0,r.jsx)("iframe",{src:w,sandbox:j?void 0:"allow-same-origin",title:a("i18n.previewFile",{file:(0,tH.WP)(t)}),style:{width:"100%",height:"100%",border:"none",background:j?"var(--bg)":"#eef1f5"}},w)})]})}function dy(e){let{filePath:t,cwd:n,sourceSessionId:s,onOpenFile:o,onMentionLines:l,onAtMention:a,gitRefreshKey:d,initialDisplayMode:c,initialState:u,initialPage:p,onStateChange:h,watchEnabled:m=!0}=e,f=function(){let e=(0,i.useSyncExternalStore)(l0,l1,l2),[t,n]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{if(!e)return void n(!1);let t=setTimeout(()=>n(!0),3e4);return()=>clearTimeout(t)},[3e4,e]),e&&t}(),g=m&&!f;return(0,aB.RW)(t)?(0,r.jsx)(df,{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:g}):(0,aB.EC)(t)?(0,r.jsx)(dx,{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:g}):(0,aB.t9)(t)?(0,r.jsx)(dv,{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:g}):(0,aB.lF)(t)?(0,r.jsx)(db,{filePath:t,cwd:n,sourceSessionId:s,initialPage:p,watchEnabled:g}):(0,r.jsx)(dj,{filePath:t,cwd:n,sourceSessionId:s,onOpenFile:o,onMentionLines:l,onAtMention:a,gitRefreshKey:d,initialDisplayMode:c,initialState:u,onStateChange:h,watchEnabled:g})}function dj(e){let{filePath:t,cwd:n,sourceSessionId:s,onOpenFile:o,onMentionLines:l,onAtMention:a,gitRefreshKey:d,initialDisplayMode:c,initialState:u,onStateChange:p,watchEnabled:h=!0}=e,{isDark:m}=(0,aF.D)(),{t:f}=(0,tn.s)(),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[y,j]=(0,i.useState)(!1),[k,w]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!0),[N,E]=(0,i.useState)(!1),[I,$]=(0,i.useState)(null),T=u?.displayMode??c??"source",M=u?.wrapLines??function(e){if(!e)return!1;let t=(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??"";return de.has(t)}(t),R=u?.scrollTop??0,A=u?.scrollLeft??0,[L,z]=(0,i.useState)(T),[P,W]=(0,i.useState)(M),[O,F]=(0,i.useState)(!1),D=(0,i.useRef)(null),B=(0,i.useRef)(0),H=(0,i.useRef)(null),_=(0,i.useRef)(0),U=(0,i.useRef)(null),K=(0,i.useRef)(!1),q=(0,i.useRef)(void 0===u&&void 0===c),V=(0,i.useRef)(!0),Z=(0,i.useRef)({displayMode:T,wrapLines:M,scrollTop:R,scrollLeft:A}),J=(0,i.useRef)(p),[G,Y]=(0,i.useState)(null),[X,Q]=(0,i.useState)(null);J.current=p;let ee=(0,i.useCallback)(e=>{Z.current.displayMode=e,z(e)},[]),et=(0,i.useCallback)(()=>{W(e=>{let t=!e;return Z.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>(Z.current={displayMode:T,wrapLines:M,scrollTop:R,scrollLeft:A},V.current=!0,K.current=!1,z(T),W(M),()=>{J.current?.({...Z.current})}),[t,s,T,M,R,A]);let en=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=++B.current;return fetch(du(e,"read",s,{offset:t||void 0})).then(e=>e.json()).then(e=>n!==B.current?null:e.error?($(e.error),null):(H.current=aH(e),$(null),x(n=>t&&n?{...e,content:n.content+e.content}:e),e)).catch(e=>(n!==B.current||$(String(e)),null))},[s]),er=(0,i.useCallback)(async e=>{let t=++_.current;if(j(!0),!n){b(null),j(!1),w(!0);return}try{let r=new URLSearchParams({cwd:n,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(t!==_.current)return;b(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch{t===_.current&&b(null)}finally{t===_.current&&(j(!1),w(!0))}},[n]);(0,i.useEffect)(()=>{let e=!0;return C(!0),$(null),x(null),b(null),w(!1),F(!1),H.current=null,en(t).finally(()=>{e&&C(!1)}),()=>{e=!1}},[t,en,s]),(0,i.useEffect)(()=>{if(F(!1),D.current&&(D.current.close(),D.current=null),!h)return;let e=!0,n=()=>{en(t),er(t)},r=eV("file-watch",new EventSource(du(t,"watch",s)),t);D.current=r,r.addEventListener("connected",()=>{(F(!0),null===H.current)?n():fetch(du(t,"meta",s)).then(e=>e.json()).then(r=>{e&&(a_(H.current,aH(r))?n():er(t))}).catch(()=>{e&&n()})}),r.addEventListener("change",n);let i=()=>{F(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{e=!1,r.close(),D.current===r&&(D.current=null)}},[t,en,er,s,h]),(0,i.useEffect)(()=>{er(t)},[er,t,d]);let ei=g?.binary===!0,es=!ei&&null!==a1(t);(0,i.useEffect)(()=>{q.current&&g&&!g.binary&&(es||"markdown"===g.language&&!g.truncated||"html"===g.language&&(!g.truncated||g.size<=aB.en))&&(q.current=!1,ee("preview"))},[g,es,ee]);let eo="preview"===L&&g?.language==="html"&&g.truncated&&g.size<=aB.en;(0,i.useEffect)(()=>{if(!eo)return void Q(null);let e=new AbortController;return fetch(du(t,"download",s),{signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);Q({text:await e.text()})}).catch(t=>{e.signal.aborted||Q({error:String(t)})}),()=>e.abort()},[eo,g,t,s]);let el=v?.supported===!0&&"string"==typeof v.patch,ea=el&&"deleted"===v.status;(0,i.useEffect)(()=>{k&&!el&&"diff"===L&&ee("source")},[L,k,el,ee]),(0,i.useEffect)(()=>{"diff"===T&&el&&!K.current&&(K.current=!0,ee("diff"))},[T,el,ee]);let ed=(0,i.useMemo)(()=>g?.language==="markdown"?(0,oQ.Ep)(g.content):"",[g]),ec=(0,i.useMemo)(()=>g?.language==="markdown"?aY(g.content):null,[g]),eu=g?.content??"",ep=(0,i.useMemo)(()=>eu.split("\n"),[eu]),eh=g?.language??"text",em=(0,aD.c)(!!g&&"text"!==eh),ef=!ei&&"html"===eh,eg=!ei&&"markdown"===eh,ex=es||(ef?!!g&&(!g.truncated||g.size<=aB.en):eg&&!g?.truncated),ev=ea?"diff":L,eb=g?.truncated?X?.text:eu,ey=(0,i.useMemo)(()=>ef&&"preview"===ev?function(e){if(!e||e.includes(aU))return e;let t=aZ(aK,e,0),n=aZ(aq,e,t),r=aZ(aV,e,n),i=r>n?r:t;return e.slice(0,i)+aU+e.slice(i)}(eb??""):"",[ef,ev,eb]),ej=!!g?.truncated&&!(ef&&"preview"===ev),ek=ep.length>1e3&&!("diff"===ev&&el)&&!("preview"===ev&&ex),ew=(0,i.useMemo)(()=>(0,r.jsx)(aP.A,{className:P?"file-source-view is-wrapped":"file-source-view",language:"text"!==eh&&em?eh:"plaintext",style:m?dr:aO.vs,showLineNumbers:!0,lineNumberStyle:{...ds},customStyle:{margin:0,padding:0,border:0,backgroundColor:"var(--bg)",...dn,width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",overflowWrap:P?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(dc,{...e,wrapLines:P}),wrapLongLines:P,children:eu}),[m,eh,em,eu,P]),eS=(0,i.useMemo)(()=>ek?ep.map((e,t)=>(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:di,children:t+1}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:P?"anywhere":"normal",whiteSpace:P?"pre-wrap":"pre"},children:e})]},`source-line-${t}`)):null,[ep,ek,P]);(0,i.useEffect)(()=>{let e=()=>{let e=U.current;Y(t=>{let n=l&&"source"===L&&e?dd(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),l&&"source"===L)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,L,l]);let eC=(0,i.useCallback)(e=>{l&&e&&l((0,tH.qP)(t,n),e.startLine,e.endLine)},[n,t,l]);if((0,i.useEffect)(()=>{if(!l||"source"!==L)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=U.current,r=n?dd(n,window.getSelection()):null;r&&(e.preventDefault(),eC(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[L,eC,l]),(0,i.useEffect)(()=>{if(!V.current||S||I&&!ea||"diff"===T&&!k||"diff"===T&&el&&"diff"!==L)return;let e=U.current;e&&(e.scrollTop=Z.current.scrollTop,e.scrollLeft=Z.current.scrollLeft,V.current=!1)},[g?.content,L,I,k,el,ea,S,T]),S||"diff"===T&&y&&!g)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:f("i18n.loading")});if(I&&!ea)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:I});if(!g&&!ea)return null;let eN=(0,tH.gX)(t),eE=ea?["diff"]:["source",...ex?["preview"]:[],...el?["diff"]:[]],eI=ea?f("files.deleted"):ei?`${f("files.binary")} \xb7 ${dh(g.size)}`:`${eh} \xb7 ${ep.length} lines \xb7 ${dh(g.size)}`;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[(0,r.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:t,children:(0,tH.qP)(t,n)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eI,children:eI}),!ea&&(0,r.jsx)("span",{title:O?f("i18n.liveSync"):f("i18n.notWatching"),"aria-label":O?f("i18n.liveSync"):f("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:O?"#4ade80":"var(--border)",boxShadow:O?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[eE.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":f("i18n.fileViewMode"),children:eE.map(e=>{let t=ev===e;return(0,r.jsx)("button",{type:"button",onClick:()=>ee(e),title:"diff"===e?f("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:dt[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(a||l)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{G&&l?eC(G):a?.((0,tH.qP)(t,n),!1)},title:G&&l?`${f("i18n.mentionSelectedLines")} (L${G.startLine}${G.startLine!==G.endLine?`-L${G.endLine}`:""})`:f("files.insertPath"),"aria-label":f("files.mention"),disabled:!a&&!l,className:"file-viewer-icon-button",children:(0,r.jsx)(dl,{})}),("source"===ev||"diff"===ev)&&!ei&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:et,title:P?f("i18n.disableWrap"):f("i18n.enableWrap"),"aria-label":P?f("i18n.disableWrap"):f("i18n.enableWrap"),"aria-pressed":P,className:"file-viewer-icon-button",style:{background:P?"var(--bg-selected)":"transparent",color:P?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})})})]}),!ea&&(0,r.jsx)(dp,{filePath:t,sourceSessionId:s})]})]}),ej&&g?.truncated&&(0,r.jsxs)("div",{className:"file-viewer-load-more",style:{display:"flex",alignItems:"center",justifyContent:"center",gap:10,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-dim)",fontSize:11},children:[(0,r.jsxs)("span",{children:[dh(g.nextOffset)," / ",dh(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:N,onClick:()=>{E(!0),en(t,g.nextOffset).finally(()=>E(!1))},children:N?f("i18n.loading"):f("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:U,className:"file-viewer-content",onScroll:e=>{Z.current.scrollTop=e.currentTarget.scrollTop,Z.current.scrollLeft=e.currentTarget.scrollLeft},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:ej?48:void 0},children:"diff"===ev&&el?(0,r.jsx)(dm,{patch:v.patch,wrapLines:P}):ef&&"preview"===ev&&g?.truncated&&!X?.text?(0,r.jsx)("div",{style:{padding:24,color:"var(--text-dim)",fontSize:12},children:X?.error??f("i18n.loading")}):ef&&"preview"===ev?(0,r.jsx)("iframe",{srcDoc:ey,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:f("i18n.htmlPreview")}):eg&&"preview"===ev?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[ec?.data&&(0,r.jsx)(a7,{data:ec.data}),(0,r.jsx)(ii.oz,{remarkPlugins:oQ.iA,rehypePlugins:oQ.LA,urlTransform:o?oQ.t9:oQ.SG,components:{code(e){let{className:t,children:n,...i}=e,s=t?.replace("language-","").toLowerCase()??"",o=String(n);return t?.includes("language-")||o.includes("\n")?"mermaid"===s?(0,r.jsx)(aQ.t,{code:o.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(aQ.NG,{code:o.replace(/\n$/,""),lang:s}):(0,r.jsx)("code",{className:t,...i,children:n})},pre(e){let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},a(e){let{href:t,children:i,...s}=e;delete s.node;let l=o?(0,rY.Vc)(t,eN,n??eN):null;return l&&o?(0,r.jsx)("a",{href:t,...s,onClick:e=>{(0,rY.pz)(e)&&(e.preventDefault(),o(l,(0,rY.XJ)(t)??void 0))},children:i}):(0,oQ.AA)(t)?(0,r.jsx)("a",{href:t,...s,target:"_blank",rel:"noopener noreferrer",children:i}):(0,r.jsx)("a",{href:t,...s,onClick:oQ.xq,children:i})},img(e){let{src:t,alt:i,...o}=e;delete o.node;let l="string"==typeof t?(0,rY.Vc)(t,eN,n??eN):null,a=l?du(l,"read",s):t;return(0,r.jsx)("img",{src:a,alt:i??"",loading:"lazy",...o})}},children:ed})]}):es&&"preview"===ev?(0,r.jsx)(a6,{content:eu,filePath:t,complete:!g?.truncated,scrollRef:U}):ei?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:10,padding:24,color:"var(--text-muted)",fontSize:13,textAlign:"center"},children:[(0,r.jsx)("span",{children:f("files.binaryNoPreview")}),(0,r.jsx)("a",{href:du(t,"download",s),download:(0,tH.WP)(t),className:"file-viewer-mode-button",style:{display:"inline-flex",alignItems:"center",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",textDecoration:"none"},children:f("files.download")})]}):ek?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...dn},children:eS}):ew})]})}function dk(e){let{tabs:t,activeTabId:n,onSelectTab:s,onCloseTab:o}=e,{t:l}=(0,tn.s)(),[a,d]=(0,i.useState)(null),c=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=c.current;if(!e)return;let t=t=>{t.ctrlKey||Math.abs(t.deltaY)<=Math.abs(t.deltaX)||e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY*(1===t.deltaMode?16:2===t.deltaMode?e.clientWidth:1))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[]),(0,i.useEffect)(()=>{let e=c.current,t=e?.querySelector('[role="tab"][aria-selected="true"]');if(!e||!t)return;let n=e.getBoundingClientRect(),{left:r,right:i}=t.getBoundingClientRect();r<n.left?e.scrollLeft-=n.left-r:i>n.right&&(e.scrollLeft+=i-n.right)},[n,t.length]),(0,r.jsx)("div",{ref:c,role:"tablist",className:"tabbar-scroll",style:{display:"flex",alignItems:"stretch",background:"var(--bg-panel)",overflowX:"auto",overflowY:"hidden",flexShrink:0,height:36},children:t.map(e=>{let i=e.id===n;return(0,r.jsxs)("div",{role:"tab","aria-label":"terminal"===e.kind?l("terminal.tabLabel",{name:e.label}):"agent"===e.kind?l("subagent.tabLabel",{name:e.label}):"side"===e.kind?l("sideChat.tabLabel"):e.label,"aria-selected":i,tabIndex:i||!n&&t[0].id===e.id?0:-1,onKeyDown:n=>{if(n.target===n.currentTarget){if("Enter"===n.key||" "===n.key)n.preventDefault(),s(e.id);else if(["ArrowLeft","ArrowRight","Home","End"].includes(n.key)){n.preventDefault();let r=t.findIndex(t=>t.id===e.id),i="Home"===n.key?0:"End"===n.key?t.length-1:(r+("ArrowRight"===n.key?1:-1)+t.length)%t.length;s(t[i].id),n.currentTarget.parentElement?.children[i]?.focus()}}},onClick:()=>s(e.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),e.closing||o(e.id))},style:{display:"flex",alignItems:"center",gap:6,paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:i?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:i?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:"terminal"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):"agent"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}):"side"===e.kind?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"})}):tB(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},title:e.filePath,children:e.label}),(0,r.jsx)("button",{disabled:e.closing,onClick:t=>{t.stopPropagation(),o(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:a===e.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:a===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:l("terminal"===e.kind?"terminal.close":"i18n.close"),"aria-label":`${l("terminal"===e.kind?"terminal.close":"i18n.close")} ${e.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}function dw(e,t,n,r){let i=e.findIndex(e=>e.id===t);if(-1===i||(e[i].viewerRevision??0)!==n)return e;let s=[...e];return s[i]={...s[i],viewerState:r},s}var dS=n(68929);let dC=["general","models","skills","agents","plugins","mcp"],dN="pi-web:settings-navigation",dE=new Set(["skills","agents","plugins"]);function dI(e){return dE.has(e)}function d$(){try{return window.localStorage}catch{return null}}function dT(e){let t=e.getItem(dN);if(!t)return{};try{let e=JSON.parse(t);if(null===e||"object"!=typeof e||Array.isArray(e))return{};return{section:"string"==typeof e.section?e.section:void 0,selections:null===e.selections||"object"!=typeof e.selections||Array.isArray(e.selections)?void 0:e.selections}}catch{return{}}}function dM(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e?e:null}function dR(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:d$();if(t)try{let n=dT(t);n.section=e,t.setItem(dN,JSON.stringify(n))}catch{}}function dA(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:d$();if(!n)return null;let r=dM(e,t);if(!r)return null;try{let e=dT(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function dL(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:d$();if(!r||!t)return;let i=dM(e,n);if(i)try{let e=dT(r);e.selections={...e.selections,[i]:t},r.setItem(dN,JSON.stringify(e))}catch{}}function dz(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class dP extends Error{constructor(e){super(`Context window of ${e} must be a positive number of tokens`),this.name="ContextWindowError",this.model=e}}function dW(e){if("string"==typeof e){let t=/^\d+$/.test(e.trim())?Number(e.trim()):0;return Number.isSafeInteger(t)&&t>0?t:void 0}return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}let dO={empty:e=>`Provider ${e} needs a Base URL or at least one model`,baseUrl:e=>`Provider ${e} needs a Base URL`};class dF extends Error{constructor(e,t){super(dO[t](e)),this.name="ProviderEntryError",this.provider=e,this.problem=t}}function dD(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dB(e){return!dD(e)||"string"!=typeof e.id||e.id.trim().length>0}function dH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function d_(e){let t=dH(e.inputLimits)?e.inputLimits.images:void 0,n=dH(t)?t.resize:void 0;return dH(n)?n.maxBytes:void 0}function dU(e){let t="string"==typeof e?/^\d+$/.test(e.trim())?Number(e.trim()):0:e;return"number"==typeof t&&Number.isSafeInteger(t)&&t>=1?t:void 0}function dK(e){let t=["B","KiB","MiB","GiB"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;let i=0===r?String(n):String(Math.round(10*n)/10);return`${i} ${t[r]}`}class dq extends Error{constructor(e){super(`Image size limit of ${e} must be a positive whole number of bytes`),this.name="ImageMaxBytesError",this.model=e}}let dV=["input","output","cacheRead","cacheWrite"];function dZ(e){return{input:e?.input===void 0?"":String(e.input),output:e?.output===void 0?"":String(e.output),cacheRead:e?.cacheRead===void 0?"":String(e.cacheRead),cacheWrite:e?.cacheWrite===void 0?"":String(e.cacheWrite)}}function dJ(e){if(!dG(e))return;let t=e=>{if(!e.trim())return 0;let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0},n=t(e.input),r=t(e.output),i=t(e.cacheRead),s=t(e.cacheWrite);if(void 0!==n&&void 0!==r&&void 0!==i&&void 0!==s)return{input:n,output:r,cacheRead:i,cacheWrite:s}}function dG(e){return dV.some(t=>""!==e[t].trim())}function dY(e,t,n){return{...e,compat:{...e.compat??{},[t]:n}}}function dX(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function dQ(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function d0(e,t){let{renames:n,savedProviders:r}=e;for(let[e,r]of n)if(r===t)return e;return!n.has(t)&&r.has(t)?t:null}function d1(e,t,n){let r=e.trim().toLowerCase();return!r||n.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function d2(e){let{embedded:t,title:n,subtitle:i,closeLabel:s="Close",onClose:o,children:l,width:a=900,height:d="78vh"}=e,c=t?void 0:{"--config-panel-width":`${a}px`,"--config-panel-height":d};return(0,r.jsx)("div",{role:t?void 0:"dialog","aria-modal":t?void 0:"true","aria-label":n,className:`config-panel-root ${t?"is-embedded":"is-modal"}`,onClick:e=>{t||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{className:"config-panel-surface",style:c,children:[!t&&(0,r.jsxs)("div",{className:"config-panel-header",children:[(0,r.jsx)("strong",{className:"config-panel-title",children:n}),i&&(0,r.jsx)("code",{className:"config-panel-subtitle",title:i,children:i}),(0,r.jsx)("button",{type:"button",className:"config-close-button",onClick:o,title:s,"aria-label":s,children:"\xd7"})]}),l]})})}function d4(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-split-view",children:t})}function d8(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function d3(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function d5(e){let{children:t,aside:n}=e;return(0,r.jsxs)("div",{className:"config-sidebar-group-label",children:[(0,r.jsx)("span",{className:"config-sidebar-group-label-text",children:t}),n]})}function d6(e){let{enabled:t,total:n,checked:i,label:s,disabled:o=!1,loading:l=!1,describedBy:a,onChange:d}=e;return(0,r.jsxs)("span",{className:"config-sidebar-group-switch",children:[(0,r.jsxs)("span",{className:"config-sidebar-group-count",children:[t,"/",n]}),(0,r.jsx)(ck,{checked:i??(n>0&&t===n),disabled:o,loading:l,label:s,describedBy:a,onChange:d})]})}function d9(e){let{error:t,note:n}=e;return t||n?(0,r.jsxs)("div",{className:"config-sidebar-group-status",children:[n&&(0,r.jsx)("div",{role:"status",className:"config-sidebar-group-note",children:n}),t&&(0,r.jsx)("div",{role:"alert",className:"config-sidebar-group-error",children:t})]}):null}function d7(e){let{active:t=!1,className:n,children:i,...s}=e;return(0,r.jsx)("button",{type:"button",...s,"aria-current":t?"page":void 0,className:["config-sidebar-item",n].filter(Boolean).join(" "),children:i})}function ce(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function ct(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function cn(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function cr(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function ci(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function cs(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function co(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function cl(e){let{label:t,children:n,style:i,ref:s}=e;return(0,r.jsxs)("div",{ref:s,className:"config-field",style:i,children:[(0,r.jsx)("span",{className:"config-field-label",children:t}),n]})}function ca(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function cd(e){let{label:t,tone:n="muted",mono:i=!1,className:s,style:o,children:l}=e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-detail-grid-label",children:t}),(0,r.jsx)("div",{className:["config-detail-grid-value","plain"===n?null:`is-${n}`,i?"is-mono":null,s].filter(Boolean).join(" "),style:o,children:l})]})}function cc(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function cu(e){let{value:t,options:n,label:s,disabledReason:o,size:l="default",onChange:a,children:d}=e,c=(0,i.useId)(),u=o&&n.some(e=>e.disabled)?o:null;return(0,r.jsxs)("div",{className:"config-scope-switch-field",children:[(0,r.jsxs)("div",{className:"config-scope-switch-row",children:[(0,r.jsx)("div",{role:"group","aria-label":s,className:`config-scope-switch${"small"===l?" is-small":""}`,children:n.map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":e.value===t,"aria-describedby":e.disabled&&u?c:void 0,disabled:e.disabled,className:"config-scope-switch-option",onClick:()=>{e.disabled||a(e.value)},children:e.label},e.value))}),d]}),u&&(0,r.jsx)("span",{id:c,className:"config-scope-switch-reason",children:u})]})}function cp(e){let{value:t,options:n,label:s,path:o,disabledReason:l,onChange:a,aside:d,children:c}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsxs)(cu,{value:t,options:n,label:s,disabledReason:l,size:"small",onChange:a,children:[d,(0,r.jsx)("span",{className:"config-save-target-path",children:"string"==typeof o?o.split(/([\\/])/).map((e,t)=>"/"===e||"\\"===e?(0,r.jsxs)(i.Fragment,{children:[e,(0,r.jsx)("wbr",{})]},t):e):o})]}),c]})}function ch(e){let{title:t,catalogs:n,target:i}=e;return(0,r.jsxs)("div",{className:"config-add-source-heading",children:[(0,r.jsxs)("div",{className:"config-add-source-title-row",children:[(0,r.jsx)(cs,{children:t}),(0,r.jsx)("span",{className:"config-add-source-catalogs",children:n.map(e=>(0,r.jsxs)("a",{href:e.href,target:"_blank",rel:"noopener noreferrer",className:"config-add-source-catalog",children:[e.icon,e.label]},e.href))})]}),i]})}function cm(e){let{title:t,catalogs:n,target:s,inputLabel:o,inputId:l,placeholder:a,value:d,canSubmit:c,normalizeValue:u,onValueChange:p,onSubmit:h,examplesLabel:m,examples:f,error:g,multiline:x=!1,children:v}=e,b=(0,i.useRef)(null),y=(0,i.useRef)(null);(0,i.useEffect)(()=>{x?window.matchMedia?.("(pointer: coarse)").matches||y.current?.focus():b.current?.focus()},[x]);let j=e=>{if(!u)return;let t=e.clipboardData.getData("text"),n=u(t);n!==t&&(e.preventDefault(),p(n))};return(0,r.jsxs)(ct,{className:"is-fill",children:[(0,r.jsx)(ch,{title:t,catalogs:n,target:s}),(0,r.jsx)(cl,{label:o,children:x?(0,r.jsx)("textarea",{id:l,ref:y,value:d,"aria-label":o,className:"config-add-source-input is-multiline",placeholder:a,rows:5,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>p(e.target.value),onPaste:j,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&e.nativeEvent?.isComposing!==!0&&229!==e.keyCode&&(e.preventDefault(),c&&h())}}):(0,r.jsx)("input",{id:l,ref:b,value:d,"aria-label":o,className:"config-add-source-input",placeholder:a,onChange:e=>p(e.target.value),onPaste:j,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&c&&h()}})}),v,f.length>0&&(0,r.jsxs)("div",{className:"config-add-source-examples",children:[(0,r.jsx)("div",{className:"config-add-source-examples-label",children:m}),(0,r.jsx)("div",{className:"config-add-source-example-list",children:f.map(e=>"string"==typeof e?(0,r.jsx)("button",{type:"button",className:"config-add-source-example",onClick:()=>p(e),children:e},e):(0,r.jsxs)("button",{type:"button",className:"config-add-source-example has-label",onClick:()=>p(e.value),children:[(0,r.jsx)("span",{className:"config-add-source-example-label",children:e.label}),(0,r.jsx)("span",{className:"config-add-source-example-value",children:e.value})]},e.value))})]}),g&&(0,r.jsx)("div",{role:"alert",className:"config-add-source-error",children:g})]})}function cf(e){let{id:t,action:n,children:i}=e;return(0,r.jsxs)("div",{id:t,role:"status",className:`config-notice${n?" has-action":""}`,children:[n?(0,r.jsx)("span",{className:"config-notice-text",children:i}):i,n]})}function cg(e){let{id:t,message:n,trustLabel:i,trusting:s=!1,onTrust:o}=e;return(0,r.jsx)(cf,{id:t,action:o&&i?(0,r.jsx)(cj,{size:"small",onClick:o,disabled:s,children:i}):void 0,children:n})}function cx(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function cv(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function cb(e){let{status:t,children:n}=e;return(0,r.jsxs)("footer",{className:"config-footer",children:[(0,r.jsx)("div",{className:"config-footer-status",children:t}),(0,r.jsx)("div",{className:"config-footer-actions",children:n})]})}function cy(e){let{summary:t,tone:n="default",details:i}=e,s=`config-footer-status-summary${"default"===n?"":` is-${n}`}`;return i?.length?(0,r.jsxs)("details",{className:"config-footer-status-details",children:[(0,r.jsx)("summary",{className:s,children:t}),(0,r.jsx)("ul",{className:"config-footer-status-list",children:i.map((e,t)=>(0,r.jsx)("li",{children:e},t))})]}):(0,r.jsx)("span",{className:s,children:t})}function cj(e){let{variant:t="secondary",size:n="default",className:i,children:s,...o}=e;return(0,r.jsx)("button",{type:"button",...o,className:["config-button",`config-button-${t}`,`config-button-${n}`,i].filter(Boolean).join(" "),children:s})}function ck(e){let{checked:t,disabled:n=!1,loading:i=!1,size:s="default",label:o,describedBy:l,onChange:a}=e,d=n||i;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":t,"aria-busy":i||void 0,"aria-label":o,"aria-describedby":l,title:o,disabled:d,className:`config-switch${"small"===s?" is-small":""}${i?" is-loading":""}`,onClick:()=>a(!t),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function cw(e){let{active:t=!1,children:n,className:i,...s}=e;return(0,r.jsx)("div",{className:"config-list-action",children:(0,r.jsxs)("button",{type:"button",...s,"aria-current":t?"page":void 0,className:["config-list-action-button",i].filter(Boolean).join(" "),children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})}),n]})})}function cS(e){let{active:t,color:n}=e;return(0,r.jsx)("span",{"aria-hidden":"true",className:`config-status-dot${t?" is-active":!1===t?" is-inactive":""}`,style:n?{backgroundColor:n}:void 0})}function cC(e,t){let n=t.filter(e=>!e.enabled).map(e=>e.ref),r=t.filter(e=>e.enabled).map(e=>e.ref),i=e?.editable===!0;return{enableRefs:n,disableRefs:r,canEnable:i&&n.length>0,canDisable:i&&r.length>0&&(e?.enabledTotal??0)-r.length>=1}}function cN(e,t){let n=cC(e,t.models),r=t.models.length>0&&t.enabledCount===t.models.length,i=r?!n.canDisable:!n.canEnable;return{checked:r,blocked:i,reason:i?e?.editable?"last-model":"project-scope":null}}function cE(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function cI(e,t){return e?.providers.find(e=>e.id===t)}function c$(e){let{modelName:t,effective:n,value:i,onChange:s,disabled:o=!1,describedBy:l}=e,{t:a}=(0,tn.s)(),d=void 0!==i&&void 0===dW(i);return(0,r.jsx)("input",{type:"text",inputMode:"numeric",className:"model-context-input",value:void 0===i?"":String(i),placeholder:void 0===n?void 0:String(n),title:a("models.contextWindow"),"aria-label":a("models.contextForModel",{model:t}),"aria-invalid":d||void 0,"aria-describedby":l,disabled:o,onChange:e=>s(""===e.target.value.trim()?void 0:e.target.value)})}let cT={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function cM(e){let{controller:t}=e,{t:n}=(0,tn.s)(),{view:i,pending:s}=t;if(!i)return null;let o=!i.allEnabled,l=i.stalePatterns.length;return o||0!==l?(0,r.jsxs)("div",{className:"enabled-models-banner",children:[(0,r.jsxs)("span",{className:"enabled-models-banner-text",...l>0?{title:n("models.enabledStaleHint")}:{},children:[(0,r.jsx)("code",{className:"enabled-models-banner-key",title:i.settingsPath,children:i.settingsPath}),(0,r.jsxs)("code",{className:"enabled-models-banner-facts",children:[`\xb7 enabledModels ${i.enabledTotal}/${i.availableTotal}`,l>0&&` \xb7 ${n("models.enabledStale",{count:l})}`]})]}),i.editable&&l>0&&(0,r.jsx)(cj,{size:"small",onClick:t.pruneStale,disabled:null!==s,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&o&&(0,r.jsx)(cj,{size:"small",onClick:t.clearScope,disabled:null!==s,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function cR(e){let{providerId:t,controller:n,noteId:i}=e,{t:s}=(0,tn.s)(),{view:o,loading:l,pending:a,failure:d}=n,c=cI(o,t),u=d?d.messageKey?s(d.messageKey):d.message:null,p=cA(n,t)?i:void 0;if(l&&!o)return null;if(!c)return(0,r.jsx)(ck,{checked:!1,disabled:!0,label:s("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=cN(o,c);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(ck,{checked:h.checked,loading:a===`provider:${c.id}`,disabled:null!==a||h.blocked,label:s("models.enabledProviderToggle",{provider:c.name}),describedBy:p,onChange:e=>n.setProvider(c.id,e)})]})}function cA(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=cI(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:s}=cN(n,i);return s?cT[s]:null}function cL(e){let{providerId:t,controller:n,id:i}=e,{t:s}=(0,tn.s)(),o=cA(n,t);return o?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:s(o)}):null}function cz(e){var t;let n,{providerId:s,controller:o,contextSettings:l}=e,{t:a}=(0,tn.s)(),[d,c]=(0,i.useState)(""),{view:u,loading:p,pending:h,failure:m}=o,f=cI(u,s),g=function(e,t){let[n,r]=(0,i.useState)(!1),[s,o]=(0,i.useState)(null);return(0,i.useEffect)(()=>o(null),[e]),{refreshing:n,note:s,refresh:(0,i.useCallback)(()=>{r(!0),o(null),(async()=>{try{let n=await fetch("/api/models/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);"offline"===r.reason?o("models.catalogOffline"):r.completed?o(r.changed?"models.catalogUpdated":"models.catalogUnchanged"):o("models.catalogUnreachable"),r.changed&&t()}catch{o("models.catalogUnreachable")}finally{r(!1)}})()},[e,t])}}(s,o.refresh),x=(0,i.useId)();if((0,i.useEffect)(()=>c(""),[s]),p&&!u)return(0,r.jsx)("div",{className:"enabled-models-empty",children:a("agents.modelsLoading")});if(!f)return m?.message?(0,r.jsx)("div",{className:"enabled-models-error",children:m.message}):(0,r.jsx)("div",{className:"enabled-models-empty",children:a("models.enabledUnavailable")});let v=(t=f.models,(n=d.trim().toLowerCase())?t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)):[...t]),b=cC(u,v),y=v.length!==f.models.length,j=null!==h,k=`provider:${f.id}`,w=u?.editable===!0,S=`${x}-scope`,C=`${x}-last`,N=`${x}-context`,E=w&&!b.canDisable&&b.disableRefs.length>0,I=E||w&&v.some(e=>cE(u,e)),$=(e,t)=>{y?o.setModels(k,t,e):o.setProvider(f.id,e)};return(0,r.jsxs)("div",{className:"enabled-models-section",children:[(0,r.jsxs)("div",{className:"enabled-models-header",children:[(0,r.jsx)("span",{className:"enabled-models-title",children:a("models.enabledSection")}),(0,r.jsx)("span",{className:"enabled-models-count",children:a("models.enabledCount",{enabled:f.enabledCount,total:f.models.length})}),(0,r.jsx)(cj,{size:"small",disabled:j||!b.canEnable,"aria-describedby":w?void 0:S,onClick:()=>$(!0,b.enableRefs),children:y?a("models.enableShown"):a("models.enableAll")}),(0,r.jsx)(cj,{size:"small",disabled:j||!b.canDisable,"aria-describedby":w?E?C:void 0:S,onClick:()=>$(!1,b.disableRefs),children:y?a("models.disableShown"):a("models.disableAll")}),(0,r.jsx)(cj,{size:"small",disabled:j||g.refreshing,title:a("models.refreshCatalogHint"),onClick:g.refresh,children:g.refreshing?a("models.refreshingCatalog"):a("models.refreshCatalog")})]}),g.note&&(0,r.jsx)("div",{className:"enabled-models-note",children:a(g.note)}),!w&&(0,r.jsx)("div",{id:S,className:"enabled-models-note",children:a("models.enabledProjectScope")}),I&&(0,r.jsx)("div",{id:C,className:"enabled-models-note",children:a("models.enabledLastModel")}),m&&(0,r.jsx)("div",{className:"enabled-models-error",children:m.messageKey?a(m.messageKey):m.message}),f.models.length>8&&(0,r.jsx)("input",{value:d,onChange:e=>c(e.target.value),placeholder:a("models.enabledFilterPlaceholder",{count:f.models.length}),"aria-label":a("models.enabledFilter"),className:"enabled-models-filter"}),l&&(0,r.jsx)("div",{id:N,className:"enabled-models-note",children:a("models.contextOverrideHelp")}),(0,r.jsx)("div",{className:"enabled-models-list",children:0===v.length?(0,r.jsx)("div",{className:"enabled-models-empty",children:a("models.enabledNoMatches")}):v.map(e=>{let t=cE(u,e),n=l?.overrides?.[e.id],i=n&&"object"==typeof n&&!Array.isArray(n)?n.contextWindow:void 0;return(0,r.jsxs)("div",{className:"enabled-models-row",children:[(0,r.jsxs)("span",{className:"enabled-models-row-text",children:[(0,r.jsx)("span",{className:"enabled-models-row-name",children:e.name}),(0,r.jsx)("code",{className:"enabled-models-row-id",children:e.id})]}),e.thinkingPin&&(0,r.jsx)("span",{className:"enabled-models-pin",title:a("models.enabledPinHint"),children:e.thinkingPin}),l&&(0,r.jsx)(c$,{modelName:e.name,effective:e.contextWindow,value:i,disabled:l.disabled,describedBy:N,onChange:t=>l.onChange(e.id,t)}),(0,r.jsx)(ck,{checked:e.enabled,loading:h===e.ref,disabled:j||!u?.editable||t,label:a("models.enabledToggle",{model:e.name}),describedBy:w?t?C:void 0:S,onChange:t=>o.setModels(e.ref,[e.ref],t)})]},e.ref)})})]})}function cP(e){let{message:t,hint:n,value:i,placeholder:s,submitLabel:o,inputLabel:l,disabled:a=!1,plainEnterSubmits:d=!0,inputRef:c,onValueChange:u,onSubmit:p}=e,h=!a&&i.trim().length>0;return(0,r.jsxs)("div",{className:"oauth-paste-panel",children:[(0,r.jsx)("p",{className:"oauth-paste-message",children:t}),n&&(0,r.jsx)("p",{className:"oauth-paste-hint",children:n}),(0,r.jsxs)("div",{className:"oauth-paste-row",children:[(0,r.jsx)("input",{ref:c,value:i,className:"oauth-paste-input",placeholder:s,"aria-label":l,disabled:a||void 0,onChange:e=>u(e.target.value),onKeyDown:e=>{var t;t={key:e.key,metaKey:e.metaKey,ctrlKey:e.ctrlKey,isComposing:e.nativeEvent.isComposing,keyCode:e.keyCode},"Enter"===t.key&&!t.isComposing&&229!==t.keyCode&&(d||t.metaKey||t.ctrlKey)&&h&&p()}}),(0,r.jsx)("button",{type:"button",className:"oauth-paste-submit",onClick:p,disabled:!h,children:o})]})]})}let cW={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},azure:{symbol:"azure",color:!0},"azure-openai-responses":{symbol:"azure",color:!0},"kimi-coding":{symbol:"kimi",color:!0},nvidia:{symbol:"nvidia",color:!0},opencode:{symbol:"opencode",color:!1},"opencode-go":{symbol:"opencode",color:!1},qwen:{symbol:"qwen",color:!0},xiaomi:{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-ams":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-cn":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-sgp":{symbol:"xiaomimimo",color:!1},zai:{symbol:"zai",color:!1},"zai-coding-cn":{symbol:"zai",color:!1},zhipu:{symbol:"zhipu",color:!0},cohere:{symbol:"cohere",color:!0},perplexity:{symbol:"perplexity",color:!0},together:{symbol:"together",color:!0},grok:{symbol:"grok",color:!1}};function cO(e){let{id:t,size:n}=e,i=cW[t];if(i)return(0,r.jsx)("svg",{"aria-hidden":"true",width:n,height:n,viewBox:"0 0 24 24",fill:i.color?void 0:"currentColor",style:{color:"var(--text-muted)",flexShrink:0},children:(0,r.jsx)("use",{href:`/provider-icons.svg#${i.symbol}`})});let s=t.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:n,height:n,border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*n)),fontWeight:700,lineHeight:1},children:s})}let cF=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],cD="pi-web:provider-usage:";function cB(e){let{providerId:t,enabled:n}=e;return cF.includes(t)?(0,r.jsx)(cH,{providerId:t,enabled:n}):null}function cH(e){let{providerId:t,enabled:n}=e,[s,o]=(0,i.useState)(null),[l,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),{locale:m,t:f}=(0,tn.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),o(null);try{let e=localStorage.getItem(`${cD}${t}`);if(e){let t=JSON.parse(e);t?.status==="ready"&&t.report&&Array.isArray(t.report.buckets)&&Array.isArray(t.report.metrics)&&o(t)}}catch{try{localStorage.removeItem(`${cD}${t}`)}catch{}}return c(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let g=(0,i.useCallback)(async()=>{a(!0),c(null);try{let e=await fetch("/api/provider-usage/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:t})}),n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);if("ready"===n.status){o(n);try{localStorage.setItem(`${cD}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else c(n.message??f("providerUsage.queryFailed"))}catch(e){c(e instanceof Error?e.message:f("providerUsage.queryFailed"))}finally{a(!1)}},[t,f]),x=s?.status==="ready"?s.report:void 0;return(0,r.jsxs)("section",{style:{paddingTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:13,color:"var(--text)",fontWeight:600,lineHeight:1.35},children:f("providerUsage.usage")}),(0,r.jsx)("button",{type:"button",onClick:g,disabled:!n||l,title:f(l?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":f(l?"providerUsage.refreshing":"providerUsage.refresh"),style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:32,height:30,padding:0,background:"none",border:"none",color:u?"#4ade80":"var(--text-dim)",cursor:n&&!l?"pointer":"default",borderRadius:5,flexShrink:0,opacity:n?1:.6,transition:"color 0.3s"},children:u?(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:l?{animation:"spin 0.8s linear infinite"}:void 0,"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}),x&&(0,r.jsx)("span",{title:new Date(x.capturedAt).toLocaleString(m),style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:f("providerUsage.updated",{time:(0,nc.ob)(x.capturedAt,m)})})]}),!x&&!d&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:f("providerUsage.notQueried")}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171"},children:d}),x&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"180px minmax(0, 1fr)",columnGap:14,rowGap:8,alignItems:"baseline",minWidth:0,width:"min(100%, 420px)",maxWidth:"100%",fontSize:12},children:[x.buckets.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.groupLabel?`${e.groupLabel} / ${e.label}`:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:function(e,t){if("percent"===e.unit&&void 0!==e.remaining){let t=e.resetsAt?` / ${new Date(1e3*e.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"";return`${Math.round(e.remaining)}%${t}`}return"currency"===e.unit?`${"CNY"===e.currency?"CNY ":"$"}${c_(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${c_(e.remaining)} / ${c_(e.limit)}`:e.period??t}(e,f("providerUsage.available"))})]},e.id)),x.metrics.map(e=>{var t;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:"currency"===(t=e).unit?`${"CNY"===t.currency?"CNY ":"$"}${t.value}`:String(t.value)})]},e.id)})]})]})}function c_(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function cU(){let e=dA("models");if(!e)return null;try{let t=JSON.parse(e);if(null===t||"object"!=typeof t)return null;if("provider"===t.type&&"string"==typeof t.name)return{type:"provider",name:t.name};if("model"===t.type&&"string"==typeof t.providerName&&"number"==typeof t.index&&Number.isInteger(t.index)&&t.index>=0)return{type:"model",providerName:t.providerName,index:t.index};if(("oauth"===t.type||"apikey"===t.type)&&"string"==typeof t.providerId)return{type:t.type,providerId:t.providerId}}catch{}return null}function cK(e){return 1===Object.keys(e).length&&Object.keys(e.modelOverrides??{}).length>0}let cq=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],cV={empty:"models.providerIncomplete",baseUrl:"models.providerNeedsBaseUrl"};function cZ(e){let{label:t,children:n}=e;return(0,r.jsx)(cl,{label:t,children:n})}let cJ={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function cG(e){let{value:t,onChange:n,placeholder:i,mono:s}=e;return(0,r.jsx)("input",{value:t,onChange:e=>n(e.target.value),placeholder:i,style:{...cJ,fontFamily:s?"var(--font-mono)":"inherit"}})}function cY(e){let{value:t,onChange:n,placeholder:s,mono:o,onKeyDown:l,autoComplete:a="off",spellCheck:d=!1,style:c}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,tn.s)();return(0,i.useEffect)(()=>{t||p(!1)},[t]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,r.jsx)("input",{type:u?"text":"password",value:t,onChange:e=>n(e.target.value),onKeyDown:l,placeholder:s,style:{...cJ,paddingRight:34,fontFamily:o?"var(--font-mono)":"inherit"},autoComplete:a,spellCheck:d}),(0,r.jsx)("button",{type:"button",onClick:()=>p(e=>!e),"aria-label":h(u?"i18n.hideDetails":"i18n.showDetails"),title:h(u?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:u?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function cX(e){let{value:t,onChange:n,placeholder:i,invalid:s}=e;return(0,r.jsx)("input",{type:"number",value:t,onChange:e=>n(e.target.value),placeholder:i,"aria-invalid":s||void 0,style:s?{...cJ,borderColor:"#ef4444"}:cJ})}function cQ(e){let{value:t,onChange:n,options:i,required:s}=e,{t:o}=(0,tn.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...cJ,color:t?"var(--text)":"var(--text-dim)"},children:[!s&&(0,r.jsxs)("option",{value:"",children:["— ",o("i18n.default")," / none —"]}),i.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function c0(e){let{label:t,checked:n,onChange:i}=e;return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:n,onChange:e=>i(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),t]})}function c1(e){let{children:t}=e;return(0,r.jsx)(co,{children:t})}function c2(e){let{name:t,editingName:n,provider:s,onChange:o,onEditingNameChange:l,onRename:a,onDelete:d,onAddModels:c,enabledModels:u}=e,{t:p}=(0,tn.s)(),[h,m]=(0,i.useState)({phase:"idle"}),[f,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),b=(0,i.useRef)(0),y=(0,i.useRef)(null),j=(0,i.useId)(),k=(e,t)=>o({...s,[e]:t});(0,i.useEffect)(()=>{b.current+=1,m({phase:"idle"}),g(""),v([])},[t,s.baseUrl,s.api,s.apiKey]);let w=(0,i.useCallback)(async()=>{if("loading"===h.phase)return;let e=++b.current;m({phase:"loading"}),v([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:{...s,models:void 0}})}),r=await n.json();if(e!==b.current)return;if(!n.ok||r.error||!r.models)return void m({phase:"error",message:r.error??`HTTP ${n.status}`});m({phase:"success",models:r.models,endpoint:r.endpoint??s.baseUrl??""})}catch(t){if(e!==b.current)return;m({phase:"error",message:t instanceof Error?t.message:String(t)})}},[h.phase,t,s]),S=new Set((s.models??[]).map(e=>e.id)),C="success"===h.phase?h.models:[],N=f.trim().toLocaleLowerCase(),E=C.filter(e=>!N||e.id.toLocaleLowerCase().includes(N)||e.name?.toLocaleLowerCase().includes(N)),I=E.slice(0,300),$=I.filter(e=>!S.has(e.id)).map(e=>e.id),T=x.filter(e=>!S.has(e)).length,M=$.length>0&&$.every(e=>x.includes(e)),R=!M&&$.some(e=>x.includes(e));return(0,i.useEffect)(()=>{y.current&&(y.current.indeterminate=R)},[R]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(cn,{children:[(0,r.jsx)(cr,{children:(0,r.jsx)(c1,{children:p("i18n.provider")})}),(0,r.jsxs)(ci,{children:[(0,r.jsx)(cR,{providerId:t,controller:u,noteId:j}),(0,r.jsx)(cj,{variant:"danger",size:"small",onClick:d,children:p("i18n.delete")})]})]}),(0,r.jsx)(cL,{providerId:t,controller:u,id:j})]}),(0,r.jsxs)(cZ,{label:p("i18n.providerName"),children:[(0,r.jsx)(cG,{value:n,onChange:l,placeholder:"provider-name",mono:!0}),n!==t&&n.trim()&&(0,r.jsx)("button",{onClick:()=>a(n.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"var(--accent-contrast)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:p("i18n.rename")})]}),(0,r.jsx)(cZ,{label:"Base URL",children:(0,r.jsx)(cG,{value:s.baseUrl??"",onChange:e=>k("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsx)(cZ,{label:"API Key",children:(0,r.jsx)(cY,{value:s.apiKey??"",onChange:e=>k("apiKey",e||void 0),placeholder:p("models.apiKeyPlaceholder"),mono:!0})}),(0,r.jsx)(cZ,{label:"API",children:(0,r.jsx)(cQ,{value:s.api??"",onChange:e=>k("api",e||void 0),options:cq})}),(0,r.jsx)(cZ,{label:"Headers",children:(0,r.jsx)(c7,{headers:s.headers,onChange:e=>k("headers",e)})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==h.phase&&(0,r.jsx)("button",{onClick:w,disabled:"loading"===h.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"loading"===h.phase?"var(--text-dim)":"var(--text-muted)",cursor:"loading"===h.phase?"not-allowed":"pointer",fontSize:11},children:"loading"===h.phase?p("models.discoveryFetching"):p("models.discoveryFetch")}),"error"===h.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:h.message}),"success"===h.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:f,onChange:e=>g(e.target.value),placeholder:p("models.discoveryFilterPlaceholder",{count:h.models.length}),"aria-label":p("models.discoveryFilter"),style:{...cJ,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:$.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:y,type:"checkbox",checked:M,disabled:0===$.length,onChange:()=>{let e=new Set($);v(t=>M?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...$])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),p("models.discoverySelectShown")]}),0===I.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:p("models.discoveryNoMatches")}):I.map((e,t)=>{let n=S.has(e.id),i=x.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void v(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:p("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:h.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:E.length>I.length?p("models.discoveryShowing",{shown:I.length,total:E.length}):p("models.discoveryFetched",{count:h.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==h.phase)return;let e=new Set(x),t=h.models.filter(t=>e.has(t.id)&&!S.has(t.id));0!==t.length&&(c(t),v([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:T?"var(--accent)":"var(--bg-panel)",color:T?"var(--accent-contrast)":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?p("models.discoveryAddSelectedCount",{count:T}):p("models.discoveryAddSelected")})]})]})]})]})}let c4=["off","minimal","low","medium","high","xhigh","max"],c8={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function c3(e){let{value:t,onChange:n}=e,{t:i}=(0,tn.s)(),s=t??{},o=(e,t)=>{let r={...s};"omit"===t?delete r[e]:r[e]=t,n(Object.keys(r).length?r:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:c4.map(e=>{let t=s[e],n=e in s?null===t?"null":"string":"omit",l="string"==typeof t?t:"",a=c8[e],d={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:a,flexShrink:0,opacity:"null"===n?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===n?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===n?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>o(e,"omit"),style:{...d,..."omit"===n?c:{}},children:i("i18n.default")}),(0,r.jsx)("button",{onClick:()=>o(e,null),style:{...d,borderLeft:"1px solid var(--border)",..."null"===n?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:i("i18n.disabled")})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===n?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>o(e,l||e),style:{...d,..."string"===n?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:i("i18n.custom")}),(0,r.jsx)("input",{value:l,onChange:t=>o(e,t.target.value),onFocus:()=>{"string"!==n&&o(e,l||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===n?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===n?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let c5={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function c6(e){return e.compat?.thinkingFormat==="deepseek"}function c9(e,t){return{...e.compat??{},...t.compat??{}}}function c7(e){let{headers:t,onChange:n}=e,{t:s}=(0,tn.s)(),[o,l]=(0,i.useState)(()=>Object.entries(t??{}).map((e,t)=>{let[n,r]=e;return{id:t,name:n,value:r}})),a=(0,i.useRef)(o.length),d=e=>{l(e),n(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},c=(e,t)=>{d(o.map(n=>n.id===e?{...n,...t}:n))},u={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>c(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...cJ,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>c(e.id,{value:t.target.value}),placeholder:"value",style:{...cJ,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void d(o.filter(e=>e.id!==t))},style:u,children:"✕"})]},e.id)),(0,r.jsxs)("button",{onClick:()=>l(e=>[...e,{id:a.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:["+ ",s("models.addHeader")]})]})}function ue(e){let{providerName:t,provider:n,model:s,onChange:o,onDelete:l}=e,[a,d]=(0,i.useState)({phase:"idle"}),{t:c}=(0,tn.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(()=>dZ(s.cost)),x=(0,i.useRef)(f),[v,b]=(0,i.useState)(!1),y=(0,i.useRef)(0),j=s.baseUrl??n.baseUrl,k=(0,i.useRef)(0),w=(0,i.useRef)(null),S=(0,i.useRef)(s.cost),C=(e,t)=>o({...s,[e]:t}),N=(()=>{if("idle"===a.phase)return null;if("testing"===a.phase)return c("i18n.testingModel");let e=[void 0!==a.latencyMs?`${a.latencyMs}ms`:null,void 0!==a.status?`HTTP ${a.status}`:null].filter(Boolean);return"success"===a.phase?[c("i18n.connected"),...e,a.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,a.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>(y.current+=1,d({phase:"idle"}),()=>{y.current+=1}),[t,n,s]),(0,i.useEffect)(()=>{k.current+=1,p({phase:"idle"}),w.current=null},[t,j,s.id]);let E=(0,i.useCallback)(async()=>{if(!s.id.trim()||"testing"===a.phase)return;let e=++y.current;d({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:n,model:s})}),i=await r.json();if(e!==y.current)return;if(!r.ok||!i.ok)return void d({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});d({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(t){if(e!==y.current)return;d({phase:"error",message:t instanceof Error?t.message:String(t)})}},[s,n,t,a.phase]),I=(0,i.useCallback)(async()=>{let e=s.id.trim();if(!e||"loading"===u.phase)return;let n=++k.current;p({phase:"loading"});try{let r=new URLSearchParams({q:e,provider:t,limit:"50"});j?.trim()&&r.set("baseUrl",j.trim());let i=await fetch(`/api/models-config/catalog?${r}`),l=await i.json();if(n!==k.current)return;if(!i.ok||l.error||!l.recommendation)return void p({phase:"error",message:l.error??`HTTP ${i.status}`});let a=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s+=1);let o=dJ(dZ(i));s>0&&o&&(n.cost={...i,...o},r+=s)}return{model:n,appliedCount:r}}(s,l.recommendation.preset);a.appliedCount>0&&(w.current=s,o(a.model)),m(!1),p({phase:"success",recommendation:l.recommendation,appliedCount:a.appliedCount})}catch(e){if(n!==k.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,s,o,j,t]),$=(()=>{if("success"!==u.phase)return null;let{recommendation:e,appliedCount:n}=u,r=n>0?c("models.catalogFilled",{count:n}):c("models.catalogNoEmptyFields");if("unreliable"===e.price.status){let t="no-exact-match"===e.price.reason?c("models.catalogNoExactMatch"):c("models.catalogPriceUnreliable");return`${r} \xb7 ${t}`}let i="provider"===e.price.method?c("models.catalogPriceProvider",{provider:e.price.providerName??e.price.providerId??t}):"base-url"===e.price.method?c("models.catalogPriceBaseUrl",{provider:e.price.providerName??e.price.providerId??t}):c("models.catalogPriceConsensus",{support:e.price.support,total:e.price.total});return`${r} \xb7 ${i}`})(),T="error"===u.phase?u.message:$,M="error"===u.phase?"#ef4444":"success"===u.phase&&"unreliable"===u.recommendation.price.status?"#d97706":"var(--text-dim)",R=[{key:"input",label:c("models.costInput")},{key:"output",label:c("models.costOutput")},{key:"cacheRead",label:c("models.costCacheRead")},{key:"cacheWrite",label:c("models.costCacheWrite")}],A=new Set(Object.keys(s.compat??{})),L=0;c6(s)&&(L+=1,A.delete("thinkingFormat"),A.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(s.compat??{},"supportsDeveloperRole")&&(L+=1,A.delete("supportsDeveloperRole")),L+=A.size;let z=d_(s),P=dU(z),W=[s.baseUrl?c("models.baseUrlOverride"):null,s.api?`API: ${s.api}`:null,Object.keys(s.headers??{}).length?c("models.headersSummary",{count:Object.keys(s.headers??{}).length}):null,L?c("models.compatSummary",{count:L}):null,Object.keys(s.thinkingLevelMap??{}).length?c("models.thinkingSummary",{count:Object.keys(s.thinkingLevelMap??{}).length}):null,void 0!==P?c("models.imageMaxBytesSummary",{size:dK(P)}):null].filter(e=>!!e),O=W.length?W.join(" \xb7 "):c("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(cn,{children:[(0,r.jsx)(cr,{children:(0,r.jsx)(c1,{children:c("i18n.model")})}),(0,r.jsxs)(ci,{children:[N&&(0,r.jsx)("span",{title:N,style:{maxWidth:260,height:28,padding:"0 8px",border:`1px solid ${"error"===a.phase?"#fecaca":"success"===a.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===a.phase?"#fee2e2":"success"===a.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:N}),(0,r.jsxs)(cj,{size:"small",variant:"success"===a.phase?"primary":"secondary",onClick:"success"===a.phase?()=>d({phase:"idle"}):E,disabled:!s.id.trim()||"testing"===a.phase,title:c("i18n.testConnection"),className:"success"===a.phase?"is-success":void 0,children:["success"===a.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===a.phase?c("i18n.checking"):"success"===a.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)(cj,{variant:"danger",size:"small",onClick:l,children:c("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(cZ,{label:"ID *",children:(0,r.jsx)(cG,{value:s.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(cZ,{label:"Name",children:(0,r.jsx)(cG,{value:s.name??"",onChange:e=>C("name",e||void 0),placeholder:c("models.displayNamePlaceholder")})})]}),(0,r.jsxs)("div",{style:{padding:"2px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void I(),disabled:!s.id.trim()||"loading"===u.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:s.id.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:s.id.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?c("models.catalogFilling"):c("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:c("models.catalogSource")})]}),T&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:M,fontSize:10},children:[(0,r.jsx)("span",{title:T,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T}),w.current&&(0,r.jsx)("button",{onClick:()=>{let e=w.current;e&&(w.current=null,o(e),p({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:c("models.catalogUndo")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(c1,{children:c("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(c0,{label:c("models.reasoning"),checked:s.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,r.jsx)(c0,{label:c("models.imageInput"),checked:s.input?.includes("image")??!1,onChange:e=>C("input",e?["text","image"]:void 0)})]})]}),(0,r.jsxs)("section",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsx)(c1,{children:c("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void m(!1);S.current=s.cost;let e=dZ(s.cost);x.current=e,g(e),m(!0)},"aria-expanded":h,style:{padding:"2px 4px",border:"none",background:"transparent",color:"var(--accent)",cursor:"pointer",fontSize:10},children:h?c("models.finishEditingCosts"):c("models.editCosts")})]}),(0,r.jsxs)("div",{style:{marginTop:10,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[(0,r.jsx)(cZ,{label:c("models.contextWindow"),children:(0,r.jsx)(cX,{value:void 0!==s.contextWindow?String(s.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(cZ,{label:c("models.maxOutputTokens"),children:(0,r.jsx)(cX,{value:void 0!==s.maxTokens?String(s.maxTokens):"",onChange:e=>C("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{style:{marginTop:16},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontWeight:600,textTransform:"uppercase"},children:c("models.costPerMillion")}),h?(0,r.jsxs)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(110px, 1fr))",gap:8},children:[R.map(e=>{let{key:t,label:n}=e;return(0,r.jsx)(cZ,{label:n,children:(0,r.jsx)(cX,{value:f[t],onChange:e=>{let n,r,i;return r=dJ(n={...x.current,[t]:e}),i={...s},void(x.current=n,g(n),r?(i.cost={...S.current??{},...r},S.current=i.cost):delete i.cost,o(i))},placeholder:"0"})},t)}),dG(f)&&!dJ(f)&&(0,r.jsx)("div",{"aria-live":"polite",style:{gridColumn:"1 / -1",color:"#d97706",fontSize:10},children:c("models.costAllRequired")})]}):(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(105px, 1fr))",gap:"8px 16px"},children:R.map(e=>{let t,{key:n,label:i}=e,o=s.cost?.[n]===void 0;return(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:i}),(0,r.jsx)("div",{style:{marginTop:3,color:o?"var(--text-dim)":"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums"},children:void 0===(t=s.cost?.[n])?c("models.notProvided"):`$${String(t)}`})]},n)})})]})]}),(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",paddingTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>b(e=>!e),"aria-expanded":v,"aria-controls":"model-advanced-settings",style:{width:"100%",minHeight:48,padding:"8px 0",border:"none",background:"transparent",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 18px",alignItems:"center",gap:10,color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:11,fontWeight:600},children:c("models.advancedSettings")}),(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-dim)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:O})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{color:"var(--text-dim)",transform:v?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),v&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,r.jsx)(cZ,{label:c("models.baseUrlOverride"),children:(0,r.jsx)(cG,{value:s.baseUrl??"",onChange:e=>C("baseUrl",e.trim()||void 0),placeholder:n.baseUrl??c("models.providerDefaults"),mono:!0})}),(0,r.jsx)(cZ,{label:c("models.apiOverride"),children:(0,r.jsx)(cQ,{value:s.api??"",onChange:e=>C("api",e||void 0),options:cq})}),(0,r.jsxs)(cZ,{label:c("models.headers"),children:[(0,r.jsx)(c7,{headers:s.headers,onChange:e=>C("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("models.headersHelp")})]}),(s.input?.includes("image")||void 0!==z)&&(0,r.jsxs)(cZ,{label:c("models.imageMaxBytes"),children:[(0,r.jsx)(cX,{value:void 0===z?"":String(z),onChange:e=>{var t;let n,r,i,l;return o((t=e.trim()||void 0,n={...dH(s.inputLimits)?s.inputLimits:{}},r={...dH(n.images)?n.images:{}},i={...dH(r.resize)?r.resize:{}},void 0===t?delete i.maxBytes:i.maxBytes=dU(t)??t,Object.keys(i).length?r.resize=i:delete r.resize,Object.keys(r).length?n.images=r:delete n.images,l={...s},Object.keys(n).length?l.inputLimits=n:delete l.inputLimits,l))},placeholder:String(4718592),invalid:void 0===P&&void 0!==z}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[void 0!==P&&`${dK(P)} \xb7 `,c("models.imageMaxBytesHelp",{size:dK(4718592)})]}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"inputLimits.images.resize.maxBytes"})]}),s.reasoning&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(c1,{children:c("models.compatibility")}),(0,r.jsx)(c0,{label:c("models.deepSeekThinkingCompat"),checked:c6(s),onChange:e=>o(function(e,t){if(t)return{...e,compat:{...e.compat??{},...c5}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(s,e))}),(0,r.jsx)(c0,{label:c("models.developerRole"),checked:!1!==c9(n,s).supportsDeveloperRole,onChange:e=>o(dY(s,"supportsDeveloperRole",e))}),(s.api??n.api)==="anthropic-messages"&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,r.jsx)(c0,{label:c("models.adaptiveThinking"),checked:!0===c9(n,s).forceAdaptiveThinking,onChange:e=>o(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(n!==r)return dY(e,t,n);if(!e.compat||!Object.prototype.hasOwnProperty.call(e.compat,t))return e;let i={...e.compat};return delete i[t],{...e,compat:Object.keys(i).length?i:void 0}}(s,"forceAdaptiveThinking",e,n.compat?.forceAdaptiveThinking===!0))}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",paddingLeft:19},children:"compat.forceAdaptiveThinking"})]}),(0,r.jsxs)("div",{style:{marginTop:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,marginBottom:8},children:[(0,r.jsx)(c1,{children:c("models.thinkingLevelMap")}),s.thinkingLevelMap&&(0,r.jsx)("button",{type:"button",onClick:()=>C("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 5px",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer"},children:c("models.clearAll")})]}),(0,r.jsx)(c3,{value:s.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function ut(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:o}=e,[l,a]=(0,i.useState)({phase:"idle"}),{t:d}=(0,tn.s)(),[c,u]=(0,i.useState)(""),p=(0,i.useRef)(null),h=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===l.phase||"prompt"===l.phase)&&setTimeout(()=>h.current?.focus(),50)},[l.phase]),(0,i.useEffect)(()=>{a({phase:"idle"}),u(""),p.current?.close(),p.current=null},[t.id]),(0,i.useEffect)(()=>()=>{p.current?.close()},[]);let m=(0,i.useCallback)(()=>{p.current?.close(),a({phase:"connecting"}),u("");let e=new EventSource(`/api/auth/login/${encodeURIComponent(t.id)}`);p.current=e,e.onmessage=t=>{let r=JSON.parse(t.data);"auth"===r.type?(a({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(a({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),window.open(r.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===r.type?a({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?a({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?a({phase:"progress",message:r.message}):"success"===r.type?(e.close(),a({phase:"success"}),n()):"error"===r.type?(e.close(),a({phase:"error",message:r.message})):"cancelled"===r.type&&(e.close(),a({phase:"idle"}))},e.onerror=()=>{e.close(),a(e=>"success"===e.phase?e:{phase:"error",message:d("models.connectionLost")})}},[t.id,n,d]),f=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(t.id)}`,{method:"POST"}),a({phase:"idle"}),n()},[t.id,n]),g=(0,i.useCallback)(async(e,n)=>{if(n.trim()){a({phase:"progress",message:d("models.verifying")});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));a({phase:"error",message:e.error??d("models.serverError",{status:r.status})});return}u("")}catch(e){a({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}}},[t.id,d]),x=(0,i.useCallback)(async(e,n)=>{a({phase:"progress",message:d("i18n.continuing")});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));a({phase:"error",message:e.error??d("models.serverError",{status:r.status})})}}catch(e){a({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}},[t.id,d]),v="connecting"===l.phase||"progress"===l.phase||"auth"===l.phase||"device_code"===l.phase||"prompt"===l.phase||"select"===l.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:t.loggedIn&&"idle"===l.phase?0:16},children:[(0,r.jsxs)(cn,{children:[(0,r.jsx)(cr,{children:(0,r.jsx)(c1,{children:d("i18n.subscription")})}),(0,r.jsxs)(ci,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.loggedIn?"#4ade80":"var(--text-dim)"},children:t.loggedIn?d("i18n.connected"):d("i18n.notConnected")})]}),v?(0,r.jsx)(cj,{size:"small",onClick:()=>{p.current?.close(),a({phase:"idle"})},children:d("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cj,{variant:"primary",size:"small",onClick:m,children:t.loggedIn?d("i18n.relogin"):d("i18n.login")}),t.loggedIn&&(0,r.jsx)(cj,{variant:"danger",size:"small",onClick:f,children:d("i18n.disconnect")})]})]})]}),(0,r.jsxs)("div",{style:{minHeight:t.loggedIn&&"idle"===l.phase?0:48},children:["idle"===l.phase&&!t.loggedIn&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:d("models.oauthConnect",{provider:t.name})}),"connecting"===l.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:d("i18n.openingBrowser")}),"select"===l.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:l.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:l.options.map(e=>(0,r.jsx)("button",{onClick:()=>x(l.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===l.phase||"prompt"===l.phase)&&(0,r.jsx)(cP,{message:"auth"===l.phase?d("models.oauthPasteRedirect"):l.message,hint:"auth"===l.phase?(0,r.jsxs)(r.Fragment,{children:[d("models.oauthNoBrowser")," ",(0,r.jsx)("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",children:d("models.oauthOpenLoginPage")}),d("models.oauthOpenLoginPageEnd")]}):void 0,value:c,placeholder:"auth"===l.phase?"http://localhost:1455/auth/callback?code=…":l.placeholder??d("models.oauthValuePlaceholder"),submitLabel:d("i18n.submit"),inputRef:h,onValueChange:u,onSubmit:()=>void g(l.token,c)}),"device_code"===l.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:d("models.oauthDeviceCode")}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:l.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:l.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:l.verificationUri}),l.expiresInSeconds?` ${d("models.deviceCodeExpires",{minutes:Math.ceil(l.expiresInSeconds/60)})}`:""]})]}),"progress"===l.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:l.message}),"success"===l.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:d("i18n.connectedSuccessfully")}),"error"===l.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:l.message})]}),(0,r.jsx)(cB,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(cz,{providerId:t.id,controller:s,contextSettings:o})]})}function un(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:o}=e,[l,a]=(0,i.useState)(""),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(!1),{t:x}=(0,tn.s)();(0,i.useEffect)(()=>{a(""),m(null),g(!1)},[t.id]);let v=(0,i.useCallback)(async()=>{if(l.trim()){c(!0),m(null),g(!1);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:l.trim()})}),r=await e.json();!e.ok||r.error?m(r.error??`HTTP ${e.status}`):(a(""),g(!0),setTimeout(()=>g(!1),2e3),n())}catch(e){m(String(e))}finally{c(!1)}}},[l,t.id,n]),b=(0,i.useCallback)(async()=>{p(!0),m(null);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"DELETE"}),r=await e.json();!e.ok||r.error?m(r.error??`HTTP ${e.status}`):n()}catch(e){m(String(e))}finally{p(!1)}},[t.id,n]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(cn,{children:[(0,r.jsx)(cr,{children:(0,r.jsx)(c1,{children:"API Key"})}),(0,r.jsxs)(ci,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.configured?"#4ade80":"var(--text-dim)"},children:x(t.configured?"i18n.configured":"i18n.notConfigured")})]}),t.configured&&(0,r.jsx)(cj,{variant:"danger",size:"small",onClick:b,disabled:u,children:x(u?"i18n.removing":"i18n.disconnect")})]})]}),!t.configured&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:1===t.modelCount?x("models.apiKeyEnableOne",{provider:t.displayName}):x("models.apiKeyEnable",{provider:t.displayName,count:t.modelCount})}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(cY,{value:l,onChange:a,onKeyDown:e=>{"Enter"===e.key&&l.trim()&&v()},placeholder:t.configured?x("models.replaceApiKey"):"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:v,disabled:d||!l.trim()||f,style:{padding:"6px 12px",background:f?"#16a34a":l.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:f?"#fff":l.trim()?"var(--accent-contrast)":"var(--text-dim)",cursor:d||!l.trim()||f?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[f&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),x(f?"i18n.saved":d?"i18n.saving":"i18n.save")]})]}),h&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:h}),(0,r.jsx)(cB,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(cz,{providerId:t.id,controller:s,contextSettings:o})]})}function ur(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:s,onSelectApiKey:o,onAddCustom:l,onClose:a}=e,[d,c]=(0,i.useState)(""),{t:u}=(0,tn.s)(),p=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let h=d.trim().toLowerCase(),m=t.filter(e=>!e.loggedIn&&d1(h,e.id,e.name)),f=n.filter(e=>!e.configured&&d1(h,e.id,e.displayName)),g=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),x=m.length+f.length+ +!!g,v={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&a()},onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),e.stopPropagation(),a())},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:p,value:d,onChange:e=>c(e.target.value),placeholder:u("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===x?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:u("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[g&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.custom")}),g&&(0,r.jsxs)("button",{onClick:()=>{l(),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!g,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.subscriptions")}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(cO,{id:e.id,size:28})]},e.id)),f.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(m.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),f.map(e=>(0,r.jsxs)("button",{onClick:()=>{o(e.id),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:1===e.modelCount?u("models.modelCountOne"):u("models.modelCount",{count:e.modelCount})})]}),(0,r.jsx)(cO,{id:e.id,size:28})]},e.id))]})})]})})}function ui(e){let{onClose:t,embedded:n=!1,cwd:s=null}=e,{t:o}=(0,tn.s)(),l=function(e){let[t,n]=(0,i.useState)(null),[r,s]=(0,i.useState)(!0),[o,l]=(0,i.useState)(null),[a,d]=(0,i.useState)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,m]=(0,i.useState)(0);(0,i.useEffect)(()=>{let t=new AbortController;s(!0);let r=e?`?cwd=${encodeURIComponent(e)}`:"";return fetch(`/api/models/enabled${r}`,{signal:t.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);n(t),d(null)}).catch(e=>{t.signal.aborted||d({message:e instanceof Error?e.message:String(e)})}).finally(()=>{t.signal.aborted||s(!1)}),()=>t.abort()},[e,h]);let f=(0,i.useCallback)((t,r)=>{if(c.current){u.current={key:t,body:r};return}c.current=t,l(t),d(null),(async()=>{try{let t=await fetch("/api/models/enabled",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...e?{cwd:e}:{}})}),i=await t.json();if(!t.ok||i.error){let e=i.reason?cT[i.reason]:void 0;d(e?{messageKey:e}:{message:i.error??`HTTP ${t.status}`});return}n(i)}catch(e){d({message:e instanceof Error?e.message:String(e)})}finally{c.current=null,l(null);let e=u.current;u.current=null,e&&p.current?.(e.key,e.body)}})()},[e]);p.current=f;let g=(0,i.useCallback)((e,t,n)=>{f(e,{op:"models",refs:t,enabled:n})},[f]),x=(0,i.useCallback)((e,t)=>{f(`provider:${e}`,{op:"provider",provider:e,enabled:t})},[f]),v=(0,i.useCallback)(()=>f("clear",{op:"clear"}),[f]),b=(0,i.useCallback)(()=>f("prune",{op:"prune"}),[f]),y=(0,i.useCallback)(()=>m(e=>e+1),[]),j=(0,i.useCallback)((e,n)=>{f("resync",{op:"resync",renames:e,modelRenames:n,fullyEnabled:(t?.providers??[]).filter(e=>e.models.length>0&&e.enabledCount===e.models.length).map(e=>e.id)})},[f,t]);return{view:t,loading:r,pending:o,failure:a,setModels:g,setProvider:x,clearScope:v,pruneStale:b,refresh:y,resync:j}}(s),[a,d]=(0,i.useState)({providers:{}}),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(!1),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[y,j]=(0,i.useState)(cU),[k,w]=(0,i.useState)([]),[S,C]=(0,i.useState)([]),[N,E]=(0,i.useState)(!1),[I,$]=(0,i.useState)(!1),T=(0,i.useRef)(new Set),M=(0,i.useRef)(new Map),R=(0,i.useRef)(new Map),[A,L]=(0,i.useState)(null),z=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>{Array.isArray(e.oauthProviders)&&w(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&C(e.apiKeyProviders)}).catch(()=>{}).finally(()=>E(!0))},[]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);return t}).then(e=>{let t=e.providers?e:{...e,providers:{}};d(t),T.current=new Set(Object.keys(t.providers??{})),R.current=dX(t);let n=Object.keys(t.providers??{});j(e=>e&&("provider"===e.type?t.providers?.[e.name]:"model"!==e.type||t.providers?.[e.providerName]?.models?.[e.index])?e:n[0]?{type:"provider",name:n[0]}:null)}).catch(e=>x(e instanceof Error?e.message:String(e))).finally(()=>u(!1)),z()},[z]),(0,i.useEffect)(()=>{y&&dL("models",JSON.stringify(y))},[y]),(0,i.useEffect)(()=>{if(y?.type!=="provider")return;let e=a.providers?.[y.name];e&&cK(e)&&(k.some(e=>e.id===y.name)?j({type:"oauth",providerId:y.name}):S.some(e=>e.id===y.name)&&j({type:"apikey",providerId:y.name}))},[S,a.providers,k,y]);let P=e=>({overrides:a.providers?.[e]?.modelOverrides,disabled:c||p||null!==g,onChange:(t,n)=>{try{d(function(e,t,n,r){let i={...e.providers},s={...Object.hasOwn(i,t)?i[t]:{}},o={...s.modelOverrides},l=Object.hasOwn(o,n)?o[n]:void 0;if(void 0!==l&&!dz(l))throw Error("Model override must be an object");let a={...l};return void 0===r?delete a.contextWindow:a.contextWindow=r,Object.keys(a).length?Object.defineProperty(o,n,{value:a,enumerable:!0,configurable:!0}):delete o[n],Object.keys(o).length?s.modelOverrides=o:delete s.modelOverrides,Object.keys(s).length?Object.defineProperty(i,t,{value:s,enumerable:!0,configurable:!0}):delete i[t],{...e,providers:i}}(a,e,t,n)),b(!1),f(null)}catch(e){f(String(e))}}}),W=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;a.providers?.[e];)e=`new-provider-${t++}`;d(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),j({type:"provider",name:e})},[a.providers]),O=(0,i.useCallback)((e,t)=>{d(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),F=(0,i.useCallback)((e,t,n)=>{let r=function(e,t,n,r){let i=e.providers??{};if(!Object.hasOwn(i,n))return null;if(n===r)return e;if(Object.hasOwn(i,r))return null;let{renames:s,slots:o}=t,l=d0(t,n);l===r?s.delete(l):null!==l&&s.set(l,r);let a=o.get(n);a&&(o.delete(n),o.set(r,a));let d=Object.entries(i),c=d.findIndex(e=>{let[t]=e;return t===n});return d[c]=[r,d[c][1]],{...e,providers:Object.fromEntries(d)}}(e,{savedProviders:T.current,renames:M.current,slots:R.current},t,n);return r?(d(r),L(null),j(e=>e?"provider"===e.type&&e.name===t?{type:"provider",name:n}:"model"===e.type&&e.providerName===t?{...e,providerName:n}:e:e),r):null},[]),D=(0,i.useCallback)((e,t)=>{F(a,e,t)?f(null):f(o("models.providerNameTaken",{name:t}))},[F,a,o]),B=(0,i.useCallback)(e=>{var t;let n,r,i=(null!==(n=d0(t={savedProviders:T.current,renames:M.current,slots:R.current},e))&&(t.renames.delete(n),t.savedProviders.delete(n)),t.slots.delete(e),r={...a.providers??{}},delete r[e],{...a,providers:r}),s=Object.keys(i.providers??{});L(t=>t?.provider===e?null:t),d(i),j(s.length>0?{type:"provider",name:s[0]}:null)},[a]),H=(0,i.useCallback)(e=>{dQ(R.current,e,1),d(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),d(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return j({type:"model",providerName:e,index:n}),t})},[]),_=(0,i.useCallback)((e,t)=>{d(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));dQ(R.current,e,t.filter(e=>!r.has(e.id)).length);let i=n.providers?.[e]??{},s=[...i.models??[]],o=new Set(s.map(e=>e.id));for(let e of t)o.has(e.id)||(o.add(e.id),s.push({...e}));return{...n,providers:{...n.providers??{},[e]:{...i,models:s}}}})},[]),U=(0,i.useCallback)((e,t,n)=>{d(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]];return s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),K=(0,i.useCallback)((e,t)=>{R.current.get(e)?.splice(t,1),d(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),j({type:"provider",name:e})},[]),q=(0,i.useCallback)(async()=>{if(g)return;h(!0),f(null),b(!1);let e=a,t=A?.name.trim();if(A&&t&&a.providers?.[A.provider]){let n=F(a,A.provider,t);if(!n){f(o("models.providerNameTaken",{name:t})),h(!1);return}e=n}try{var n=e=function(e){let t=structuredClone(e);if(!dz(t.providers))return t;for(let[e,n]of Object.entries(t.providers))if(dz(n)&&dz(n.modelOverrides))for(let[t,r]of Object.entries(n.modelOverrides)){if(!dz(r)||!Object.hasOwn(r,"contextWindow"))continue;let n=dW(r.contextWindow);if(void 0===n)throw new dP(`${e}/${t}`);r.contextWindow=n}return t}(e);if(dD(n.providers))for(let[e,t]of Object.entries(n.providers)){if(!dD(t))continue;if(t.oauth&&!t.baseUrl)throw new dF(e,"baseUrl");let n=Array.isArray(t.models)&&t.models.some(dB),r=dD(t.modelOverrides)&&Object.keys(t.modelOverrides).length>0;if(!n&&!t.baseUrl&&!t.headers&&!t.compat&&!r&&!t.apiKey&&!t.oauth&&void 0===t.authHeader)throw new dF(e,"empty")}var r=e;if(dH(r.providers)){for(let[e,t]of Object.entries(r.providers))if(dH(t)&&Array.isArray(t.models))for(let n of t.models){if(!dH(n)||"string"==typeof n.id&&!n.id.trim())continue;let t=d_(n);if(void 0!==t&&void 0===dU(t))throw new dq(`${e}/${"string"==typeof n.id?n.id:"?"}`)}}let t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),i=await t.json();if(!t.ok||i.error)f(i.error??`HTTP ${t.status}`);else{b(!0),setTimeout(()=>b(!1),2e3);let t=[...M.current].map(e=>{let[t,n]=e;return{from:t,to:n}}),n=function(e,t,n){let r=e=>{for(let[t,r]of n)if(r===e)return t;return e},i=[];for(let[n,s]of Object.entries(e.providers??{})){let e=t.get(n);e&&(s.models??[]).forEach((t,s)=>{let o=e[s];o&&t.id&&o!==t.id&&i.push({from:`${r(n)}/${o}`,to:`${n}/${t.id}`})})}return i}(e,R.current,M.current);T.current=new Set(Object.keys(e.providers??{})),R.current=dX(e),M.current.clear(),l.resync(t,n)}}catch(e){e instanceof dF?(f(o(cV[e.problem],{provider:e.provider})),j({type:"provider",name:e.provider})):e instanceof dP?f(o("models.contextInvalid",{model:e.model})):f(e instanceof dq?o("models.imageMaxBytesInvalid",{model:e.model}):String(e))}finally{h(!1)}},[F,a,l,g,A,o]),V=Object.entries(a.providers??{}).filter(e=>{let[t,n]=e;if(!cK(n))return!0;let r=k.some(e=>e.id===t)||S.some(e=>e.id===t);return N&&!r}),Z=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=cI(e,t);return n?`${n.enabledCount}/${n.models.length}`:null}(l.view,e);return t?(0,r.jsx)("span",{className:"models-sidebar-badge",children:t}):null},J=k.filter(e=>e.loggedIn),G=S.filter(e=>e.configured),Y=(()=>{if(!y)return null;if("oauth"===y.type){let e=k.find(e=>e.id===y.providerId);return e?(0,r.jsx)(ut,{provider:e,onRefresh:z,enabledModels:l,contextSettings:P(e.id)},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,r.jsx)(un,{provider:e,onRefresh:z,enabledModels:l,contextSettings:P(e.id)},e.id):null}if("provider"===y.type){let e=a.providers?.[y.name];return e&&V.some(e=>{let[t]=e;return t===y.name})?(0,r.jsx)(c2,{name:y.name,editingName:A?.provider===y.name?A.name:y.name,provider:e,onChange:e=>O(y.name,e),onEditingNameChange:e=>L(e===y.name?null:{provider:y.name,name:e}),onRename:e=>D(y.name,e),onDelete:()=>B(y.name),onAddModels:e=>_(y.name,e),enabledModels:l},y.name):null}let e=a.providers?.[y.providerName],t=e?.models?.[y.index];return t?(0,r.jsx)(ue,{providerName:y.providerName,provider:e,model:t,onChange:e=>U(y.providerName,y.index,e),onDelete:()=>K(y.providerName,y.index)},`${y.providerName}-${y.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(d2,{embedded:n,title:o("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:o("i18n.close"),onClose:t,children:[(0,r.jsx)(cM,{controller:l}),(0,r.jsxs)(d4,{children:[(0,r.jsxs)(d8,{children:[(0,r.jsxs)(d3,{children:[J.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)(d7,{active:t,onClick:()=>j({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(cO,{id:e.id,size:16}),(0,r.jsx)(ce,{className:"is-grow",children:e.name}),Z(e.id)]},e.id)}),G.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,r.jsxs)(d7,{active:t,onClick:()=>j({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(cO,{id:e.id,size:16}),(0,r.jsx)(ce,{className:"is-grow",children:e.displayName}),Z(e.id)]},e.id)}),(J.length>0||G.length>0)&&V.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:o("i18n.loading")}):V.map(e=>{let[t,n]=e,i=y?.type==="provider"&&y.name===t,s=n.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(d7,{onClick:()=>j({type:"provider",name:t}),active:i,children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)(ce,{className:"is-grow",children:t}),Z(t)]}),s.map((e,n)=>{let i=y?.type==="model"&&y.providerName===t&&y.index===n;return(0,r.jsxs)(d7,{active:i,className:"models-sidebar-indented-item",onClick:()=>j({type:"model",providerName:t,index:n}),children:[(0,r.jsx)(ce,{className:"is-grow",style:{color:e.id?"var(--text-muted)":"var(--text-dim)"},children:e.name?.trim()||e.id||o("i18n.newModel")}),e.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},n)}),(0,r.jsx)(d7,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),H(t)},children:(0,r.jsxs)(ce,{children:["+ ",o("i18n.model")]})})]},t)})]}),(0,r.jsx)(cw,{onClick:()=>$(!0),children:o("i18n.addProvider")})]}),(0,r.jsx)(cv,{children:(0,r.jsx)(ct,{className:"is-fill",children:c?null:Y??(0,r.jsx)(cx,{children:o("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(cb,{status:g||m?(0,r.jsx)("span",{style:{color:"#f87171"},children:g?o("models.configUnreadable",{error:g}):m}):o("models.applyHelp"),children:[!n&&(0,r.jsx)(cj,{onClick:t,children:o("i18n.cancel")}),(0,r.jsxs)(cj,{variant:"primary",onClick:q,disabled:p||v||null!==g,className:v?"is-success":void 0,children:[v&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:v?o("i18n.saved"):p?o("i18n.saving"):o("i18n.save")})]})]})]}),I&&(0,r.jsx)(ur,{oauthProviders:k,apiKeyProviders:S,onSelectOAuth:e=>j({type:"oauth",providerId:e}),onSelectApiKey:e=>j({type:"apikey",providerId:e}),onAddCustom:W,onClose:()=>$(!1)})]})}function us(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;return"visible"!==e.visibilityState||!e.hasFocus()}function uo(){return window.isSecureContext&&"Notification"in window?Notification.permission:"unsupported"}async function ul(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null},n={body:e.body,...e.tag?{tag:e.tag,renotify:!0}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}let ua=null;function ud(){return"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}async function uc(){if(!ud())return!1;try{return!!await navigator.serviceWorker.getRegistration()}catch{return!1}}async function uu(e){let t;if(!ud()||"granted"!==Notification.permission)return!1;if(ua)return ua;let n=Promise.race([(async()=>{try{if(!await uc())return!1;let t=await fetch("/api/push/config");if(!t.ok)return!1;let{publicKey:n}=await t.json();if(!n)return!1;let r=await navigator.serviceWorker.ready,i=await r.pushManager.getSubscription();return i||(i=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){let t="=".repeat((4-e.length%4)%4),n=atob((e+t).replace(/-/g,"+").replace(/_/g,"/")),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}(n)})),(await fetch("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({subscription:i.toJSON(),locale:e})})).ok}catch{return ua=null,!1}})(),new Promise(e=>{t=setTimeout(()=>e(!1),15e3)})]).finally(()=>clearTimeout(t));return ua=n,n.then(e=>{e||ua!==n||(ua=null)}),n}function up(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function uh(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}async function um(e,t){try{let n=await fetch("/api/skills/import/pick",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:e,prompt:t})}),r=await n.json().catch(()=>({}));if(n.ok)return r.path?{path:r.path}:"cancelled";return"busy"===r.error?"busy":"unavailable"}catch{return"unavailable"}}let uf={width:"100%",boxSizing:"border-box",padding:"7px 10px",borderRadius:5,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12},ug={display:"block",fontSize:11,color:"var(--text-muted)",marginBottom:4};function ux(e){let{cwd:t,scope:n,targetRoot:s,onClose:o,onImported:l}=e,{t:a}=(0,tn.s)(),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(null),j=(0,i.useRef)(null),k=(0,i.useRef)(!1),w=async e=>{let t=e.target.files?.[0];if(t){y(null);try{let e=await t.text(),n=t.name.replace(/\.[^/.]+$/,"");p({name:t.name,content:e}),c("");try{let t=aY(e),r=t.data?.name?.trim()||n,i=t.data?.description?.trim()||null;m(r),g(i)}catch{m(n),g(null)}}catch(e){y(e instanceof Error?e.message:String(e))}}},S=async e=>{if(y(null),!k.current){let t=await um(e,"folder"===e?a("skills.import.chooseFolder"):a("skills.import.chooseFile"));if("busy"===t||"cancelled"===t)return;if("unavailable"!==t){c(t.path),p(null);let e=t.path.replace(/[\\/]+$/,"").split(/[\\/]/),n=(e[e.length-1]||"imported-skill").replace(/\.[^/.]+$/,"");m(("SKILL"===n||"skill"===n)&&e[e.length-2]||n);return}k.current=!0}j.current?.click()},C=async()=>{if(x)return;let e=d.trim();if(!u&&!e)return void y(a("skills.import.sourceRequired"));let r=h.trim();if(!r)return void y(a("skills.import.nameRequired"));v(!0),y(null);try{let i=u?{scope:n,cwd:t,name:r,content:u.content}:{scope:n,cwd:t,name:r,sourcePath:e},s=await fetch("/api/skills/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),a=await s.json().catch(()=>({}));if(!s.ok||!a.success||!a.filePath)return void y(a.error||`HTTP ${s.status}`);l({name:a.name??r,filePath:a.filePath,scope:a.scope??n}),o()}catch(e){y(e instanceof Error?e.message:String(e))}finally{v(!1)}};return(0,r.jsx)(uv,{targetRoot:s,pathValue:d,selectedFileName:u?.name??null,skillName:h,skillDescription:f,busy:x,error:b,fileInputRef:j,onFileInputChange:e=>void w(e),onPathChange:e=>{c(e),e.trim()&&p(null)},onSkillNameChange:m,onChooseFile:()=>void S("file"),onChooseFolder:()=>void S("folder"),onCancel:o,onConfirm:()=>void C()})}function uv(e){let{targetRoot:t,pathValue:n,selectedFileName:s,skillName:o,skillDescription:l,busy:a,error:d,fileInputRef:c,onFileInputChange:u,onPathChange:p,onSkillNameChange:h,onChooseFile:m,onChooseFolder:f,onCancel:g,onConfirm:x}=e,{t:v}=(0,tn.s)(),b=(0,i.useRef)(null),y=(0,i.useRef)(a),j=(0,i.useRef)(g);(0,i.useEffect)(()=>{y.current=a,j.current=g},[a,g]),(0,i.useEffect)(()=>{if("u">typeof document)return eD(document,b.current,()=>{y.current||j.current()})},[]);let k=!a&&(!!s||n.trim().length>0),w=(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{a||e.target!==e.currentTarget||g()},children:(0,r.jsxs)("div",{ref:b,role:"dialog","aria-modal":"true","aria-labelledby":"import-skill-title","aria-describedby":"import-skill-description",tabIndex:-1,className:"project-trust-dialog",children:[(0,r.jsx)("input",{ref:c,type:"file",accept:".md,text/markdown,text/plain",style:{display:"none"},onChange:u}),(0,r.jsx)("div",{className:"project-trust-body",children:(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"import-skill-title",className:"project-trust-title",children:v("skills.import.title")}),(0,r.jsx)("div",{id:"import-skill-description",className:"project-trust-text",children:v("skills.import.description")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10,marginTop:12},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:m,disabled:a,children:v("skills.import.chooseFile")}),(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:f,disabled:a,children:v("skills.import.chooseFolder")}),s&&(0,r.jsx)("code",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text)",padding:"4px 8px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg)"},children:s})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:"import-skill-path-input",style:ug,children:v("skills.import.pathLabel")}),(0,r.jsx)("input",{id:"import-skill-path-input",type:"text",value:n,disabled:a,placeholder:"/path/to/my-skill or /path/to/SKILL.md",onChange:e=>p(e.target.value),style:uf})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:"import-skill-name-input",style:ug,children:v("skills.import.nameLabel")}),(0,r.jsx)("input",{id:"import-skill-name-input",type:"text",value:o,disabled:a,placeholder:"my-skill",onChange:e=>h(e.target.value),style:uf}),(0,r.jsxs)("span",{style:{display:"block",marginTop:4,fontSize:11,color:"var(--text-dim)",overflowWrap:"anywhere"},children:[v("skills.import.targetLocation"),": ",(0,r.jsxs)("code",{children:[t,o||"...","/SKILL.md"]})]})]}),l&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:l})]})]})}),d&&(0,r.jsx)("div",{role:"alert",className:"project-trust-error",style:{overflowWrap:"anywhere"},children:d}),(0,r.jsxs)("div",{className:"project-trust-footer",children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:g,disabled:a,children:v("import.cancel")}),(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:x,disabled:!k,children:v(a?"import.importing":"import.confirm")})]})]})});return"u">typeof document?(0,tk.createPortal)(w,document.body):null}function ub(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function uy(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function uj(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function uk(e,t){return e?e.slice(0,8):t}function uw(e){let{skill:t,cwd:n,onToggle:s,toggling:o,saveError:l,removing:a,onRemove:d,updateStatus:c,checkingUpdate:u,updating:p,updateError:h,onCheckUpdate:m,onUpdate:f}=e,{t:g}=(0,tn.s)(),x=ub(t),v=!t.disableModelInvocation,b=e=>"project"===x?eC(e,n):eS(e),{removal:y}=t,[j,k]=(0,i.useState)(!1),[w,S]=(0,i.useState)(null),C=(0,i.useId)(),N=/[\\/]\.agents[\\/]skills[\\/]/.test(t.filePath),E=async()=>{S(null);let e=await d(t);e&&S(e)},[I,$]=(0,i.useState)(null),[T,M]=(0,i.useState)(null),R=t.filePath.split(/[\\/]/).pop(),[A,L]=(0,i.useState)([]),z=A.at(-1)??R,P=(0,i.useRef)(null),W=(0,i.useRef)(null),[O,F]=(0,i.useState)(0),D=(0,i.useCallback)(e=>{let t=function(e,t){let n=e.indexOf("#"),[r,i]=[n<0?e:e.slice(0,n),n<0?"":e.slice(n+1)].map(e=>{try{return decodeURIComponent(e)}catch{return e}});if(!r)return{document:t,anchor:i};if(r.startsWith("/"))return{document:r,anchor:i};let s=t.split("/").slice(0,-1);for(let e of r.split("/"))".."===e&&s.length&&".."!==s[s.length-1]?s.pop():e&&"."!==e&&s.push(e);return{document:s.join("/"),anchor:i}}(e,z);W.current=t.anchor,t.document===z?F(e=>e+1):L(e=>[...e,t.document])},[z]);return(0,i.useLayoutEffect)(()=>{let e=W.current,t=P.current;null!==e&&(null!==I||T)&&t&&(W.current=null,((e?t.querySelector(`[data-heading-anchor="${CSS.escape(e)}"]`):null)??t).scrollIntoView({block:"start"}))},[I,T,O]),(0,i.useEffect)(()=>{let e=new AbortController;return $(null),M(null),(async()=>{try{var r;let i=new URLSearchParams({cwd:n,filePath:t.filePath});z!==R&&i.set("document",z);let s=await fetch(`/api/skills/content?${i}`,{signal:e.signal}),o=await s.json();if(!s.ok||o.error||"string"!=typeof o.content)throw Error(o.error??`HTTP ${s.status}`);$((r=o.content,aY(r).rest.trim()))}catch(t){if(e.signal.aborted)return;M(t instanceof Error?t.message:String(t))}})(),()=>e.abort()},[n,t.filePath,z,R]),(0,r.jsxs)(ct,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(cn,{children:[(0,r.jsxs)(cr,{children:[(0,r.jsx)(cc,{scope:x,children:uy(x,g)}),(0,r.jsx)("span",{className:"config-detail-path",children:b(t.filePath)})]}),(0,r.jsxs)(ci,{children:[(0,r.jsx)(cj,{variant:"danger",size:"small",disabled:!y||a||j,"aria-describedby":y?void 0:C,onClick:()=>{S(null),k(!0)},children:g("i18n.remove")}),(0,r.jsx)(ck,{checked:v,loading:o,label:g(v?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>s(t)})]})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!v&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:g("i18n.hiddenButInvocable")}),l&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:l}),w&&(0,r.jsx)("span",{role:"alert",style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:w})]}),!y&&(0,r.jsx)("div",{id:C,className:"config-detail-heading-note",children:g("skills.removeUnavailable")}),j&&y&&(0,r.jsxs)("div",{className:"skill-remove-confirm",children:[(0,r.jsxs)("span",{className:"skill-remove-confirm-text",children:["cli"===y.method?g("skills.removeConfirmCli",{name:t.name,path:b(y.path)}):g("skills.removeConfirmFiles",{path:b(y.path)}),N&&(0,r.jsxs)(r.Fragment,{children:[" ",g("skills.removeConfirmShared")]})]}),(0,r.jsx)(cj,{size:"small",onClick:()=>k(!1),disabled:a,children:g("i18n.cancel")}),(0,r.jsx)(cj,{variant:"danger",size:"small",onClick:()=>void E(),disabled:a,children:g(a?"i18n.removing":"i18n.remove")})]})]}),t.install?.skillsShUrl&&(0,r.jsx)(cl,{label:g("config.source"),children:(0,r.jsx)("a",{href:t.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:t.install.skillsShUrl,className:"skill-source-link",children:(0,r.jsxs)("span",{className:"skill-source-link-text",children:[t.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})}),t.install&&(0,r.jsxs)(cl,{label:g("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:uk(c?.currentVersion??t.install.versionHash,g("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(cj,{size:"small",onClick:m,disabled:u||p,children:g("i18n.check")}),c?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:uk(c.latestVersion,g("i18n.unknown"))}),(u||c&&"update-available"!==c.state)&&(0,r.jsx)("span",{className:`skill-update-status ${u?"is-checking":c?.state==="up-to-date"?"is-success":c?.state==="error"?"is-error":"is-muted"}`,children:u?g("i18n.checking"):c?.state==="up-to-date"?g("i18n.upToDate"):c?.state==="unsupported"?g("i18n.automaticChecksUnavailable"):c?.message||g("i18n.checkFailed")}),c?.state==="update-available"&&(0,r.jsx)(cj,{variant:"primary",size:"small",onClick:f,disabled:p||u,children:g(p?"i18n.updating":"i18n.update")})]}),h&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:h})]}),(0,r.jsx)(cl,{label:g("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(cl,{label:g("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})}),(0,r.jsxs)(cl,{label:g("skills.instructions"),ref:P,children:[A.length>0&&(0,r.jsx)(cn,{children:(0,r.jsxs)(cr,{children:[(0,r.jsx)(cj,{size:"small",onClick:()=>{W.current="",L(e=>e.slice(0,-1))},children:g("skills.documentBack")}),(0,r.jsx)("span",{className:"config-detail-path",title:z,children:z})]})}),T?(0,r.jsx)("span",{role:"alert",className:"skill-instructions-status is-error",children:T}):null===I?(0,r.jsx)("span",{role:"status",className:"skill-instructions-status",children:g("i18n.loading")}):I?(0,r.jsx)(is.m,{className:"skill-instructions",cwd:[t.baseDir,...z.split("/").slice(0,-1)].join("/"),onNavigateLink:D,children:I}):(0,r.jsx)("span",{className:"skill-instructions-status",children:g("skills.noInstructions")})]})]})}function uS(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:s,onInstalled:o,onImported:l}=e,{t:a}=(0,tn.s)(),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)([]),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(new Set),[w,S]=(0,i.useState)("global"),[C,N]=(0,i.useState)(!1),E=(0,i.useRef)(null);(0,i.useEffect)(()=>{E.current?.focus()},[]);let I=(0,i.useCallback)(async e=>{if(e.trim()){m(!0),g(null),p([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void g(n.error);p(n.results??[]),0===(n.results??[]).length&&g(a("i18n.noSkills"))}catch(e){g(String(e))}finally{m(!1)}}},[a]),$=(0,i.useCallback)(async e=>{v(e),y(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:e,scope:w,cwd:t})}),r=await n.json();if(!n.ok||r.error)return void y(r.error??`HTTP ${n.status}`);k(t=>new Set(t).add(`${w}:${e}`)),o()}catch(e){y(String(e))}finally{v(null)}},[o,w,t]),T="global"===w?"~/.pi/agent/skills/":`${eS(t)}/.pi/skills/`,M=a("skills.import.importToScope",{scope:uy(w,a)});return(0,r.jsxs)(ct,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(ch,{title:a("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(cp,{value:w,label:a("config.saveTo"),options:[{value:"global",label:uy("global",a)},{value:"project",label:uy("project",a),disabled:!s}],path:T,disabledReason:a("trust.projectScopeUnavailable"),onChange:S,aside:(0,r.jsx)(cj,{size:"small",title:M,"aria-label":M,onClick:()=>N(!0),children:(0,r.jsx)(nD,{size:13})})})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:E,value:d,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&I(d)},placeholder:a("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:12,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)(cj,{variant:"primary",onClick:()=>I(d),disabled:h||!d.trim(),children:h?a("i18n.searching"):a("i18n.search")})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:f}),b&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:b})]}),u.length>0&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:u.map(e=>{let t=n[w].has(e.package)||j.has(`${w}:${e.package}`),i=x===e.package,s=e.package.indexOf("@"),o=s>-1?e.package.slice(0,s):e.package,l=s>-1?e.package.slice(s+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??o}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:o}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)(cj,{size:"small",onClick:()=>!t&&!i&&$(e.package),disabled:t||i||null!==x,style:{flexShrink:0,background:t?"rgba(34,197,94,0.1)":"none",color:t?"#16a34a":i?"var(--accent)":"var(--text-muted)"},children:t?`✓ ${a("i18n.installed")}`:i?a("i18n.installing"):a("i18n.install")})]},e.package)})}),C&&(0,r.jsx)(ux,{cwd:t,scope:w,targetRoot:T,onClose:()=>N(!1),onImported:e=>{N(!1),l(e)}})]})}function uC(e){let{cwd:t,onClose:n,embedded:s=!1,trust:o}=e,{t:l}=(0,tn.s)(),[a,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(()=>dA("skills",t)),[g,x]=(0,i.useState)(new Set),[v,b]=(0,i.useState)(null),[y,j]=(0,i.useState)(null),[k,w]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,E]=(0,i.useState)({}),[I,$]=(0,i.useState)(new Set),[T,M]=(0,i.useState)(!1),[R,A]=(0,i.useState)(null),[L,z]=(0,i.useState)(null),[P,W]=(0,i.useState)(!0),[O,F]=(0,i.useState)(!1),[D,B]=(0,i.useState)(null),H=(0,i.useRef)(null),_=(0,i.useCallback)(async()=>{u(!0),h(null);try{let e=await fetch(`/api/skills?cwd=${encodeURIComponent(t)}`),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);let r=n.skills??[];return d(r),W(n.projectResourcesLoaded??!0),f(e=>{if(e&&r.some(t=>t.filePath===e))return e;let t=r.find(e=>!e.disableModelInvocation)??r[0];return t?.filePath??null}),r}catch(e){return h(String(e)),[]}finally{u(!1)}},[t]);(0,i.useEffect)(()=>{E({}),z(null),_()},[t]);let U=uh(o),K=(0,i.useRef)(U);(0,i.useEffect)(()=>{K.current!==U&&(K.current=U,_())},[U,_]),(0,i.useEffect)(()=>{m&&dL("skills",m,t)},[t,m]);let q=(0,i.useCallback)(async e=>{let n=(e?[e]:a.filter(e=>!!e.install)).map(uj).filter(e=>!!e);if(0!==n.length){z(null),$(e=>new Set([...e,...n])),e||M(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e?.install?.package,scope:e?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);E(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){z(e instanceof Error?e.message:String(e))}finally{$(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||M(!1)}}},[t,a]),V=(0,i.useCallback)(async e=>{if(!e.install)return;let n=uj(e);A(n),z(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e.install.package,scope:e.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await _();let s=i.skill?.install?.versionHash;E(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{A(null)}},[t,_]),Z=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;x(t=>new Set(t).add(e.filePath)),b(null),w(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void b(r.error??`HTTP ${n.status}`);d(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n))}catch(e){b(String(e))}finally{x(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),J=(0,i.useCallback)(async e=>{F(!0);try{let n=await fetch("/api/skills/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",cwd:t,filePath:e.filePath})}),r=await n.json();if(!n.ok||r.error||!r.token)return r.error??`HTTP ${n.status}`;return B({token:r.token,name:r.name??e.name,expiresInMs:r.expiresInMs??0,undoing:!1,error:null}),await _(),eB(document,H.current),null}catch(e){return e instanceof Error?e.message:String(e)}finally{F(!1)}},[t,_]),G=(0,i.useCallback)(async()=>{if(!D)return;let{token:e}=D,t=t=>B(n=>n?.token!==e?n:t&&{...n,...t});t({undoing:!0,error:null});try{let n=await fetch("/api/skills/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"undo",token:e})}),r=await n.json();if(!n.ok||r.error||!r.filePath)throw Error(r.error??`HTTP ${n.status}`);t(null),await _(),f(r.filePath),C(!1)}catch(e){t({undoing:!1,error:e instanceof Error?e.message:String(e)})}},[D,_]),Y=D?.token,X=D?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===Y||void 0===X)return;let e=setTimeout(()=>B(e=>e?.token===Y?null:e),X);return()=>clearTimeout(e)},[Y,X]);let Q=(0,i.useCallback)(async(e,t,n)=>{let r=up(t,n,e=>!e.disableModelInvocation);if(0===r.length)return;let i=r.map(e=>e.filePath),s=!n;x(e=>new Set([...e,...i])),j(e),b(null),w(null);try{let t=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePaths:i,disableModelInvocation:s})}),n=await t.json();if(!t.ok||n.error||!n.results)throw Error(n.error??`HTTP ${t.status}`);let o=n.results;d(e=>{let t;return t=new Set(o.filter(e=>!e.error).map(e=>e.filePath)),e.map(e=>t.has(e.filePath)?{...e,disableModelInvocation:s}:e)});let a=o.filter(e=>e.error);if(a.length>0){let t=new Map(r.map(e=>[e.filePath,e.name]));w({group:e,error:[l("skills.bulkFailed",{count:a.length,total:o.length}),...a.map(e=>`${t.get(e.filePath)??e.filePath}: ${e.error}`)].join("\n")})}}catch(t){w({group:e,error:t instanceof Error?t.message:String(t)})}finally{j(null),x(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t})}},[l]),ee=a.find(e=>e.filePath===m)??null,et=c||g.size>0||null!==R||O;return(0,r.jsxs)(d2,{embedded:s,title:l("common.skills"),subtitle:eS(t),closeLabel:l("i18n.close"),onClose:n,children:[!P&&(0,r.jsx)(cg,{message:l("trust.skillsNotLoaded")}),D&&(0,r.jsxs)(cf,{action:(0,r.jsx)(cj,{ref:H,size:"small",onClick:()=>void G(),disabled:D.undoing,children:D.undoing?l("skills.undoing"):l("skills.undo")}),children:[l("skills.removed",{name:D.name}),D.error&&(0,r.jsxs)(r.Fragment,{children:[" ",l("skills.undoFailed")," ",D.error]})]}),(0,r.jsxs)(d4,{children:[(0,r.jsxs)(d8,{children:[(0,r.jsx)(d3,{children:c?(0,r.jsx)("div",{className:"config-sidebar-message",children:l("i18n.loading")}):p?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:p}):0===a.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:l("i18n.noSkills")}):(()=>{let e=[],t={project:l("skills.scope.project"),global:l("skills.scope.global"),path:l("skills.scope.path")};for(let{label:n,matches:r}of[{label:`${t.project} / skills.sh`,matches:e=>"project"===ub(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===ub(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===ub(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===ub(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===ub(e)}]){let t=a.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!S&&m===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)(d7,{active:i,onClick:()=>{f(e.filePath),C(!1)},children:[(0,r.jsx)(cS,{active:!s}),(0,r.jsx)(ce,{className:`is-grow${s?" is-muted":""}`,children:e.name}),(n=(t=uj(e))?N[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:l("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"}))]},e.filePath)};return e.map(e=>{let{label:t,skills:i}=e,s=i.filter(e=>!e.disableModelInvocation).length,o=s===i.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(d5,{aside:(0,r.jsx)(d6,{enabled:s,total:i.length,disabled:et,loading:y===t,label:l(o?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void Q(t,i,e)}),children:t}),k?.group===t&&(0,r.jsx)(d9,{error:k.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(cw,{onClick:()=>C(!0),active:S,children:l("i18n.addSkill")})]}),(0,r.jsx)(cv,{children:(0,r.jsx)(ct,{className:"is-fill",children:S?(0,r.jsx)(uS,{cwd:t,projectResourcesLoaded:P,installedPackages:{global:new Set(a.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(a.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{_()},onImported:e=>{_().then(()=>{f(e.filePath),C(!1)})}}):c?null:ee?(0,r.jsx)(uw,{skill:ee,cwd:t,onToggle:Z,toggling:g.has(ee.filePath),saveError:v,removing:O,onRemove:J,updateStatus:uj(ee)?N[uj(ee)]:void 0,checkingUpdate:!!uj(ee)&&I.has(uj(ee)),updating:R===uj(ee),updateError:L,onCheckUpdate:()=>void q(ee),onUpdate:()=>void V(ee)},ee.filePath):(0,r.jsx)(cx,{children:l("i18n.selectSkill")})})})]}),(0,r.jsxs)(cb,{status:Object.values(N).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(N).filter(e=>"update-available"===e.state).length," ",1===Object.values(N).filter(e=>"update-available"===e.state).length?l("i18n.update"):l("i18n.updates")]}),children:[!s&&(0,r.jsx)(cj,{onClick:n,children:l("i18n.close")}),a.some(e=>!!e.install)&&(0,r.jsx)(cj,{variant:"secondary",onClick:()=>void q(),disabled:T||null!==R,children:T?l("i18n.checking"):l("i18n.checkUpdates")})]})]})}let uN={builtin:0,global:1,workspace:2,project:3},uE=["read","bash","edit","write","grep","find","ls"],uI=["","off","minimal","low","medium","high","xhigh","max"],u$={name:"custom-agent",displayName:"Custom agent",description:"",systemPrompt:"",tools:["read","bash","edit","write","grep","find","ls"],loadSkills:!1,loadExtensions:!1,codemode:"off",mcp:"off",promptMode:"append",inheritContext:!1,runInBackground:!1,enabled:!0},uT={width:"100%",minWidth:0,height:34,padding:"0 9px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"},uM={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function uR(e){return{name:e.name,displayName:e.displayName,description:e.description,systemPrompt:e.systemPrompt,tools:[...e.tools],loadSkills:e.loadSkills,...void 0!==e.skills?{skills:[...e.skills]}:{},loadExtensions:e.loadExtensions,codemode:e.codemode??"off",mcp:e.mcp??"off",...void 0!==e.extensions?{extensions:[...e.extensions]}:{},promptMode:e.promptMode,...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},...e.maxTurns?{maxTurns:e.maxTurns}:{},inheritContext:e.inheritContext,runInBackground:e.runInBackground,enabled:e.enabled}}function uA(e){return`${e.scope}:${e.name}`}function uL(e){return"global"===e||"project"===e}function uz(e){return uL(e)||"builtin"===e}function uP(e){let{label:t,children:n}=e;return(0,r.jsx)(cl,{label:t,children:n})}function uW(e){let{checked:t,disabled:n,label:i,onChange:s}=e;return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:7,color:n?"var(--text-dim)":"var(--text-muted)",fontSize:12,cursor:n?"default":"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,disabled:n,onChange:e=>s(e.target.checked)}),i]})}function uO(e){let{cwd:t,sessionId:n=null,onClose:s,onReloaded:o,embedded:l=!1,trust:a}=e,d=tp(),{t:c}=(0,tn.s)(),[u,p]=(0,i.useState)([]),[h,m]=(0,i.useState)([]),[f,g]=(0,i.useState)(!0),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(()=>dA("agents",t)),[j,k]=(0,i.useState)(u$),[w,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[E,I]=(0,i.useState)(!0),[$,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(10),[B,H]=(0,i.useState)(!0),[_,U]=(0,i.useState)(!1),[K,q]=(0,i.useState)(null),[V,Z]=(0,i.useState)(!1),[J,G]=(0,i.useState)(!1),Y=(0,i.useMemo)(()=>u.find(e=>uA(e)===b)??null,[u,b]),X=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[h]),Q=(0,i.useCallback)(async e=>{I(!0),P(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(t)}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);let i=r.profiles??[];p(i);let s=e??dA("agents",t),o=i.find(e=>uA(e)===s)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(o?uA(o):null),o&&(k(uR(o)),S(uL(o.scope)?"edit":"view"),uL(o.scope)&&N(o.scope))}catch(e){P(e instanceof Error?e.message:String(e))}finally{I(!1)}},[t]);(0,i.useEffect)(()=>{Q()},[Q]),(0,i.useEffect)(()=>{let e=new AbortController;return H(!0),q(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);O(n.enabled),"number"==typeof n.maxConcurrent&&D(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;q(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||H(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{b&&dL("agents",b,t)},[t,b]);let ee=uh(a);(0,i.useEffect)(()=>{let e=new AbortController;return g(!0),v(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(t)}`,{signal:e.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);m(r.modelList??[]),v(r.modelError??null)}catch(t){if(e.signal.aborted)return;v(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||g(!1)}})(),()=>e.abort()},[t,ee]);let et=async()=>{T(!0),P(null),R(!1);try{let e=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:C,profile:j})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await Q(uA(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){P(e instanceof Error?e.message:String(e))}finally{T(!1)}},en=async()=>{if(Y&&uL(Y.scope)&&window.confirm(c("agents.deleteConfirm",{name:Y.displayName}))){T(!0),P(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:Y.scope,name:Y.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await Q()}catch(e){P(e instanceof Error?e.message:String(e))}finally{T(!1)}}},er="view"!==w,ei="create"===w,es=!er||$||A,eo=ei?C:Y?.scope,el=ei?"global"===C?`~/.pi/agent/agents/${j.name||"..."}.md`:`./.pi/agents/${j.name||"..."}.md`:Y?(Y.filePath?"project"===Y.scope||"workspace"===Y.scope?eC(Y.filePath,t):eS(Y.filePath):null)??c("agents.builtinPath"):"",ea=ei?el:Y?.filePath??el,ed=e=>h.some(t=>`${t.provider}/${t.id}`===e),ec=j.model&&function(e,t){if(t(e))return e;let n=e.lastIndexOf(":"),r=e.slice(n+1);return n>0&&r&&uI.includes(r)?e.slice(0,n):e}(j.model,ed),eu=!ec||ed(ec),ep=(()=>{if(!ec)return null;let e=ec.indexOf("/");return e<0?{provider:"",modelId:ec}:{provider:ec.slice(0,e),modelId:ec.slice(e+1)}})(),eh=es?{...uT,...uM}:uT,em=ei?es:!Y||!uz(Y.scope)||$||A,ef=(e,t)=>{k(n=>({...n,[e]:t}))},eg=0===j.tools.length&&!j.loadSkills&&!j.loadExtensions,ex=async e=>{if(ei)return void ef("enabled",e);if(Y&&uz(Y.scope)){L(!0),P(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:Y.scope,name:Y.name,enabled:e})}),r=await n.json();if(!n.ok||r.error||!r.profile)throw Error(r.error??`HTTP ${n.status}`);let i=r.profile;p(e=>e.map(e=>uA(e)===uA(i)?i:e)),k(e=>({...e,enabled:i.enabled}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{L(!1)}}},ev=async e=>{U(!0),q(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await t.json();if(!t.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${t.status}`);O(r.enabled),Z(!!n)}catch(e){q(e instanceof Error?e.message:String(e))}finally{U(!1)}},eb=async e=>{D(e),q(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);D(n.maxConcurrent)}catch(e){q(e instanceof Error?e.message:String(e))}},ey=async()=>{if(n){G(!0),q(null);try{await lw(n,{type:"reload"}),Z(!1),o?.()}catch(e){q(e instanceof Error?e.message:String(e))}finally{G(!1)}}};return(0,r.jsxs)(d2,{embedded:l,title:c("common.agents"),subtitle:eS(t),closeLabel:c("agents.close"),onClose:s,children:[(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:c("agents.builtInTitle")}),(0,r.jsx)("span",{children:c("agents.builtInDescription")}),V&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:c("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[V&&n&&(0,r.jsx)(cj,{size:"small",onClick:()=>void ey(),disabled:J||_,children:J?c("agents.reloading"):c("agents.reloadSession")}),(0,r.jsxs)("label",{className:"agents-concurrency-control",title:c("agents.maxConcurrentDescription"),children:[(0,r.jsx)("span",{children:c("agents.maxConcurrent")}),(0,r.jsx)("input",{"aria-label":c("agents.maxConcurrent"),type:"number",min:1,max:32,value:F,disabled:B||_,onChange:e=>D(Number(e.target.value)),onBlur:()=>void eb(F)})]}),(0,r.jsx)(ck,{checked:W,disabled:B||J,loading:_,label:c("agents.builtInTitle"),onChange:e=>void ev(e)})]})]}),(0,r.jsxs)(d4,{children:[(0,r.jsxs)(d8,{children:[(0,r.jsx)(d3,{children:E?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:c("agents.loading")}):["project","global","workspace","builtin"].map(e=>{let t=u.filter(t=>t.scope===e);return 0===t.length?null:(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(d5,{children:c(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=uN[e.scope],u.some(e=>e.name.toLowerCase()===t&&uN[e.scope]>n));return(0,r.jsxs)(d7,{active:b===uA(e)&&!ei,onClick:()=>{y(uA(e)),k(uR(e)),S(uL(e.scope)?"edit":"view"),uL(e.scope)&&N(e.scope),P(null)},children:[(0,r.jsx)(cS,{active:e.enabled}),(0,r.jsx)(ce,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:c("agents.overridden")})]},uA(e))})]},e)})}),(0,r.jsx)(cw,{active:ei,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),k({...u$,name:e,displayName:e}),S("create"),N("global"),P(null)},children:c("agents.new")})]}),(0,r.jsx)(cv,{children:(0,r.jsx)(ct,{className:"is-fill",children:Y||ei?(0,r.jsxs)(ct,{children:[(0,r.jsxs)(cn,{children:[(0,r.jsx)(cr,{children:ei?(0,r.jsx)(cp,{value:C,label:c("config.saveTo"),options:["global","project"].map(e=>({value:e,label:c(`agents.scope.${e}`),disabled:$})),path:el,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[eo&&(0,r.jsx)(cc,{scope:eo,children:c(`agents.scope.${eo}`)}),(0,r.jsx)("span",{title:ea,className:"config-detail-path",children:el})]})}),(0,r.jsxs)(ci,{children:[Y&&("view"===w||"edit"===w)&&(0,r.jsx)(cj,{size:"small",onClick:()=>{if(!Y)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,s=2;for(;n.has(i.toLowerCase());)i=`${r}-${s++}`;return i}(Y.name,u);y(null),k({...uR(Y),name:e,displayName:c("agents.copyName",{name:Y.displayName})}),S("create"),N(uL(Y.scope)?Y.scope:"global"),P(null)},disabled:$||A,children:c("agents.duplicate")}),Y&&uL(Y.scope)&&"edit"===w&&(0,r.jsx)(cj,{variant:"danger",size:"small",onClick:()=>void en(),disabled:$||A,children:c("agents.delete")}),(0,r.jsx)(ck,{checked:j.enabled,disabled:em,label:j.enabled?c("agents.disable"):c("agents.enable"),onChange:e=>void ex(e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(uP,{label:c("agents.name"),children:ei?(0,r.jsx)("input",{"aria-label":c("agents.name"),value:j.name,disabled:es,onChange:e=>ef("name",e.target.value),style:uT}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:j.name})}),(0,r.jsx)(uP,{label:c("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":c("agents.displayName"),value:j.displayName,disabled:es,onChange:e=>ef("displayName",e.target.value),style:eh})})]}),(0,r.jsx)(uP,{label:c("agents.description"),children:(0,r.jsx)("input",{"aria-label":c("agents.description"),value:j.description,disabled:es,onChange:e=>ef("description",e.target.value),style:eh})}),(0,r.jsx)(uP,{label:c("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":c("agents.prompt"),value:j.systemPrompt,disabled:es,onChange:e=>ef("systemPrompt",e.target.value),style:{...eh,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:es?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(uP,{label:c("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:uE.map(e=>(0,r.jsx)(uW,{label:e,disabled:es,checked:j.tools.includes(e),onChange:t=>ef("tools",t?[...j.tools,e]:j.tools.filter(t=>t!==e))},e))})}),(0,r.jsxs)(uP,{label:c("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(uW,{label:c("agents.loadSkills"),disabled:es,checked:j.loadSkills,onChange:e=>ef("loadSkills",e)}),(0,r.jsx)(uW,{label:c("agents.loadExtensions"),disabled:es,checked:j.loadExtensions,onChange:e=>ef("loadExtensions",e)}),(0,r.jsx)(uW,{label:c("agents.mcp"),disabled:es||eg&&"on"!==j.mcp,checked:"on"===j.mcp,onChange:e=>ef("mcp",e?"on":"off")})]}),j.loadSkills&&void 0!==j.skills&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:j.skills.length>0?c("agents.skillsOnly",{skills:j.skills.join(", ")}):c("agents.skillsNone")}),j.loadExtensions&&void 0!==j.extensions&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:j.extensions.length>0?c("agents.extensionsOnly",{extensions:j.extensions.join(", ")}):c("agents.extensionsNone")}),!es&&eg?(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpChatOnly")}):"on"===j.mcp&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpHint")})]}),(0,r.jsx)(uP,{label:c("agents.codemode"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[(0,r.jsxs)("select",{"aria-label":c("agents.codemode"),value:j.codemode??"off",disabled:es,onChange:e=>ef("codemode",e.target.value),style:{...eh,width:"auto",minWidth:180,alignSelf:"flex-start"},children:[(0,r.jsx)("option",{value:"inherit",children:c("agents.codemode.inherit")}),(0,r.jsx)("option",{value:"on",children:c("agents.codemode.on")}),(0,r.jsx)("option",{value:"off",children:c("agents.codemode.off")})]}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.codemodeHint")})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(uP,{label:c("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(oj,{options:X,value:ep,onChange:(e,t)=>ef("model",`${e}/${t}`),onClear:()=>ef("model",void 0),emptyLabel:f?c("agents.modelsLoading"):c("agents.inherit"),selectedLabel:j.model&&!eu?c("agents.modelUnavailable",{model:j.model}):j.model!==ec?j.model:void 0,disabled:es||f||0===h.length&&!j.model,ariaLabel:c("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(uP,{label:c("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":c("agents.thinking"),value:j.thinking??"",disabled:es,onChange:e=>ef("thinking",e.target.value||void 0),style:eh,children:uI.map(e=>(0,r.jsx)("option",{value:e,children:e||c("agents.inherit")},e||"default"))})}),(0,r.jsx)(uP,{label:c("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":c("agents.maxTurns"),type:"number",min:1,value:j.maxTurns??"",disabled:es,onChange:e=>ef("maxTurns",e.target.value?Number(e.target.value):void 0),style:eh})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(uW,{label:c("agents.inheritContext"),disabled:es,checked:j.inheritContext,onChange:e=>ef("inheritContext",e)}),(0,r.jsx)(uW,{label:c("agents.background"),disabled:es,checked:j.runInBackground,onChange:e=>ef("runInBackground",e)})]})]}):(0,r.jsx)(cx,{children:c("agents.empty")})})})]}),(0,r.jsx)(cb,{status:(K||z)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:K||z}),children:er&&(0,r.jsxs)(cj,{variant:"primary",onClick:()=>void et(),disabled:$||M||A||!j.name.trim(),className:M?"is-success":void 0,children:[M&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:M?c("i18n.saved"):$?c("agents.saving"):c("agents.save")})]})})]})}let uF=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function uD(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function uB(e){return`${e.scope}\0${e.source}`}function uH(e){return`extension\0${e.path}`}function u_(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function uU(e,t){return t(`plugins.status.${e}`)}function uK(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function uq(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function uV(e){let{pkg:t}=e,{t:n}=(0,tn.s)(),i=[["extension",n("i18n.extensions")],["skill",n("i18n.skills")],["prompt",n("i18n.prompts")],["theme",n("i18n.themes")]].map(e=>{let[n,r]=e;return{kind:n,label:r,resources:t.resources.filter(e=>e.kind===n)}}).filter(e=>e.resources.length>0);return 0===i.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n(t.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:i.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function uZ(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:s,busy:o,actionError:l,onSourceChange:a,onScopeChange:d,onInstall:c}=e,{t:u}=(0,tn.s)();return(0,r.jsx)(cm,{title:u("i18n.addPlugin"),catalogs:[{href:"https://pi.dev/packages",label:"pi.dev/packages",icon:(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]})}],target:(0,r.jsx)(cp,{value:i,label:u("config.saveTo"),options:[{value:"global",label:u_("global",u)},{value:"project",label:u_("project",u),disabled:!s}],path:"project"===i?`${eS(t)}/.pi/{npm,git}`:"~/.pi/agent/{npm,git}",disabledReason:u("trust.projectScopeUnavailable"),onChange:d}),inputLabel:u("config.source"),inputId:"plugin-source",placeholder:"npm:@scope/package",value:n,canSubmit:!o&&!!n.trim(),normalizeValue:uD,onValueChange:a,onSubmit:c,examplesLabel:u("config.examples"),examples:uF,error:l,children:(0,r.jsx)(cj,{variant:"primary",onClick:c,disabled:o||!n.trim(),className:"is-pushed-right",children:u(o?"i18n.installing":"i18n.install")})})}function uJ(e){let t,{pkg:n,cwd:s,busyKey:o,actionError:l,actionMessage:a,sessionId:d,updateStatus:c,checkingUpdate:u,updateError:p,onAction:h,onCheckUpdate:m,onReloadSession:f}=e,{t:g}=(0,tn.s)(),x=uB(n),v=(o?.endsWith(x)||o?.startsWith("bulk:"))??!1,b="reload"===o,y=!n.disabled,j=n.canCheckForUpdates,k=c?.state==="update-available",w=n.description?.trim(),S=(0,i.useId)();return(0,r.jsxs)(ct,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(cn,{className:"is-top-aligned",children:[(0,r.jsxs)(cr,{children:[(0,r.jsx)(cc,{scope:n.scope,children:u_(n.scope,g)}),n.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:g("i18n.disabled")}):n.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:g("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.source})]}),(0,r.jsxs)(ci,{children:[(0,r.jsx)(cj,{size:"small",variant:k?"primary":void 0,onClick:k||!j?()=>h("update",n):m,disabled:v||b||u,title:k?g("i18n.updateAvailable"):void 0,children:g(o===`update:${x}`?"i18n.updating":u?"i18n.checking":k||!j?"i18n.update":"i18n.check")}),(0,r.jsx)(cj,{size:"small",onClick:f,disabled:!d||b||v,"aria-describedby":d?void 0:S,children:g(b?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(cj,{variant:"danger",size:"small",onClick:()=>h("remove",n),disabled:v||b,children:g(o===`remove:${x}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(ck,{checked:y,loading:v||b,onChange:()=>h(n.disabled?"enable":"disable",n),label:g(n.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!d&&(0,r.jsx)("div",{id:S,className:"config-detail-heading-note",children:g("i18n.openSessionToReload")})]}),(0,r.jsxs)(ca,{children:[w&&(0,r.jsx)(cd,{label:g("i18n.description"),children:w}),(0,r.jsx)(cd,{label:g("i18n.status"),tone:"plain",style:{color:uq(n.status),textTransform:"capitalize"},children:uU(n.status,g)}),(0,r.jsxs)(cd,{label:g("i18n.version"),tone:"plain",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:(t=[],n.version&&t.push(g("i18n.installedVersion",{version:n.version})),n.configuredVersion&&t.push(g("i18n.configuredVersion",{version:n.configuredVersion})),t.length?t.join(" \xb7 "):g("i18n.unknown"))}),k&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:c.displayName,children:g("i18n.updateAvailable")}),j&&(u||c&&!k)&&(0,r.jsx)("span",{className:`skill-update-status ${u?"is-checking":c?.state==="up-to-date"?"is-success":c?.state==="error"?"is-error":"is-muted"}`,children:u?g("i18n.checking"):c?.state==="up-to-date"?g("i18n.upToDate"):c?.state==="unsupported"?g("i18n.automaticChecksUnavailable"):c?.message||g("i18n.checkFailed")})]}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:p})]}),(0,r.jsx)(cd,{label:g("i18n.package"),mono:!0,children:n.packageName??g("i18n.unknown")}),(0,r.jsx)(cd,{label:g("i18n.resources"),children:function(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}(n,g)}),(0,r.jsx)(cd,{label:g("i18n.installedPath"),tone:n.installedPath?"muted":"error",mono:!0,children:n.installedPath?eS(n.installedPath):g("i18n.notFound")}),(0,r.jsx)(cd,{label:g("i18n.cwd"),tone:"dim",mono:!0,children:eS(s)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(co,{children:g("i18n.resolvedResources")}),(0,r.jsx)(uV,{pkg:n})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),l&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:l})]})}function uG(e){let{extension:t}=e,{t:n}=(0,tn.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(ct,{children:[(0,r.jsx)(cn,{children:(0,r.jsxs)(cr,{children:[(0,r.jsx)(cc,{scope:t.scope,children:u_(t.scope,n)}),(0,r.jsx)(cs,{children:t.name})]})}),(0,r.jsxs)(ca,{children:[(0,r.jsx)(cd,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:uU(i,n)}),(0,r.jsx)(cd,{label:n("i18n.installedPath"),mono:!0,children:eS(t.path)})]})]})}function uY(e){let{extension:t,cwd:n,busyKey:s,actionError:o,actionMessage:l,sessionId:a,onToggle:d,onReloadSession:c}=e,{t:u}=(0,tn.s)(),p=s===uH(t),h="reload"===s,m="project"===t.scope,f=(0,i.useId)(),g=(0,i.useId)();return(0,r.jsxs)(ct,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(cn,{className:"is-top-aligned",children:[(0,r.jsxs)(cr,{children:[(0,r.jsx)(cc,{scope:t.scope,children:u_(t.scope,u)}),(0,r.jsx)(cs,{children:t.name})]}),(0,r.jsxs)(ci,{children:[(0,r.jsx)(cj,{size:"small",onClick:c,disabled:!a||h||p,"aria-describedby":a?void 0:f,children:u(h?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(ck,{checked:t.enabled,loading:p||h,disabled:m,describedBy:m?g:void 0,onChange:e=>d(t,e),label:u(t.enabled?"plugins.disableBuiltin":"plugins.enableBuiltin")})]})]}),!a&&(0,r.jsx)("div",{id:f,className:"config-detail-heading-note",children:u("i18n.openSessionToReload")}),m&&(0,r.jsx)("div",{id:g,className:"config-detail-heading-note",children:u("plugins.builtinProject",{path:`${eS(n)}/.pi/settings.json`})})]}),(0,r.jsxs)(ca,{children:[(0,r.jsx)(cd,{label:u("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:uU(t.enabled?"loaded":"disabled",u)}),(0,r.jsx)(cd,{label:u("plugins.builtin"),children:u("plugins.builtinNote")})]}),l&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:l}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:o})]})}function uX(e){var t;let{cwd:n,sessionId:s,onClose:o,onReloaded:l,embedded:a=!1,trust:d}=e,{t:c}=(0,tn.s)(),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(!0),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(()=>dA("plugins",n)),[b,y]=(0,i.useState)(!1),[j,k]=(0,i.useState)(""),[w,S]=(0,i.useState)("global"),[C,N]=(0,i.useState)(null),[E,I]=(0,i.useState)(null),[$,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(null),[A,L]=(0,i.useState)({}),[z,P]=(0,i.useState)(new Set),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(null),[B,H]=(0,i.useState)(!1),_=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),U=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),K=_.find(e=>uB(e)===x)??null,q=U.find(e=>uH(e)===x)??null,V=u?.projectResourcesLoaded??!0,Z=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:_.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[_]),J=(0,i.useCallback)(async()=>{m(!0),g(null),R(null);try{let e=await fetch(`/api/plugins?cwd=${encodeURIComponent(n)}`),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),y(e=>0===t.packages.length&&0===t.standaloneExtensions.length||e),v(e=>e&&(t.packages.some(t=>uB(t)===e)||t.standaloneExtensions.some(t=>uH(t)===e))?e:t.packages[0]?uB(t.packages[0]):t.standaloneExtensions[0]?uH(t.standaloneExtensions[0]):null)}catch(e){g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[n]);(0,i.useEffect)(()=>{L({}),D(null),J()},[n]);let G=uh(d),Y=(0,i.useRef)(G);(0,i.useEffect)(()=>{Y.current!==G&&(Y.current=G,J())},[G,J]),(0,i.useEffect)(()=>{x&&dL("plugins",x,n)},[n,x]);let X=(0,i.useCallback)(async e=>{let t=(e?[e]:_.filter(e=>e.canCheckForUpdates)).map(uB);if(0!==t.length){D(null),P(e=>new Set([...e,...t])),e||O(!0);try{let t=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,source:e?.source,scope:e?.scope})}),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);L(e=>{let t={...e};for(let e of r.updates??[])t[uB(e)]=e;return t})}catch(e){D(e instanceof Error?e.message:String(e))}finally{P(e=>{let n=new Set(e);for(let e of t)n.delete(e);return n}),e||O(!1)}}},[n,_]),Q=(0,i.useCallback)(async()=>{H(!0),I(null),T(null),D(null);try{let e=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",cwd:n})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),L({}),T(c("i18n.packagesUpdated")),s&&T(`${c("i18n.packagesUpdated")} ${c("agents.reloadRequired")}`)}catch(e){I(e instanceof Error?e.message:String(e))}finally{H(!1)}},[n,s,c]),ee=(0,i.useCallback)(async(e,t)=>{let r=uB(t);N(`${e}:${r}`),I(null),T(null),R(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,source:t.source,scope:t.scope,cwd:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);if(p(s),"remove"===e)v(s.packages[0]?uB(s.packages[0]):s.standaloneExtensions[0]?uH(s.standaloneExtensions[0]):null),0===s.packages.length&&0===s.standaloneExtensions.length&&y(!0),T(c("i18n.packageRemoved")),L(e=>{let t={...e};return delete t[r],t});else{let t={install:c("i18n.packageInstalled"),update:c("i18n.packageUpdated"),disable:c("i18n.packageDisabled"),enable:c("i18n.packageEnabled")};T(t[e]),"update"===e&&L(e=>{let t={...e};return delete t[r],t})}}catch(e){I(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,c]),et=(0,i.useCallback)(async(e,t)=>{N(uH(e)),I(null),T(null),R(null);try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"set-builtin",name:e.name.replace(/^builtin:/,""),enabled:t,cwd:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);p(i);let o=t?c("plugins.builtinEnabled"):c("plugins.builtinDisabled");T(s?`${o} ${c("agents.reloadRequired")}`:o)}catch(e){I(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,s,c]),en=(0,i.useCallback)(async(e,t,r)=>{let i=up(t,r,e=>!e.disabled,e=>e.filtered),o=r?0:t.filter(e=>!e.disabled&&e.filtered).length,l=o>0?c("plugins.bulkKeptFiltered",{count:o}):void 0;if(I(null),T(null),R(l?{scope:e,note:l}:null),0===i.length)return;let a=r?"enable":"disable";N(`bulk:${e}`);try{let t=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:a,cwd:n,packages:i.map(t=>{let{source:n}=t;return{source:n,scope:e}})})}),o=await t.json();if(!t.ok||o.error||!o.results)throw Error(o.error??`HTTP ${t.status}`);let{results:d,...u}=o;p(u);let h=d.filter(e=>e.error);if(h.length<d.length){let e=r?c("plugins.bulkEnabled"):c("plugins.bulkDisabled");T(s?`${e} ${c("agents.reloadRequired")}`:e)}h.length>0&&R({scope:e,note:l,error:[c("plugins.bulkFailed",{count:h.length,total:d.length}),...h.map(e=>`${e.source}: ${e.error}`)].join("\n")})}catch(t){R({scope:e,note:l,error:t instanceof Error?t.message:String(t)})}finally{N(null)}},[n,s,c]),er=(0,i.useCallback)(async()=>{let e=uD(j).trim();if(!e)return;k(e);let t=`${w}\0${e}`;N(`install:${t}`),I(null),T(null),R(null);try{var r;let i,s,o=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:e,scope:w,cwd:n})}),l=await o.json();if(!o.ok||l.error)throw Error(l.error??`HTTP ${o.status}`);p(l);let a=(r=l.packages,s=(i=e.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===w&&e.source===i)??r.find(e=>e.scope===w&&e.source===`npm:${s}`)??r.find(e=>e.scope===w&&e.source.endsWith(i)));v(a?uB(a):t),y(!1),k(""),T(c("i18n.packageInstalled"))}catch(e){I(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,w,j,c]),ei=(0,i.useCallback)(async()=>{if(s){N("reload"),I(null),T(null),R(null);try{await lw(s,{type:"reload"}),l?.(),await J(),T(c("i18n.sessionReloaded"))}catch(e){I(e instanceof Error?e.message:String(e))}finally{N(null)}}},[J,l,s,c]),es=C?.startsWith("install:")??!1,eo=Object.values(A).filter(e=>"update-available"===e.state).length,el=_.some(e=>e.canCheckForUpdates),ea=h||null!==C||z.size>0||B;return(0,r.jsxs)(d2,{embedded:a,title:c("common.plugins"),subtitle:eS(n),closeLabel:c("i18n.close"),onClose:o,children:[!V&&(0,r.jsx)(cg,{message:c("trust.pluginsNotLoaded")}),(0,r.jsxs)(d4,{children:[(0,r.jsxs)(d8,{children:[(0,r.jsx)(d3,{children:h?(0,r.jsx)("div",{className:"config-sidebar-message",children:c("i18n.loading")}):f?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:f}):0===_.length&&0===U.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:c("i18n.noPlugins")}):(0,r.jsxs)(r.Fragment,{children:[U.length>0&&(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(d5,{children:c("i18n.extensions")}),U.map(e=>{let t=uH(e);return(0,r.jsxs)(d7,{active:!b&&x===t,title:e.path,onClick:()=>{v(t),y(!1),I(null),T(null)},children:[(0,r.jsx)(cS,{active:e.enabled}),(0,r.jsx)(ce,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),Z.map(e=>{let t=e.packages.filter(e=>!e.disabled).length,n=t===e.packages.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(d5,{aside:(0,r.jsx)(d6,{enabled:t,total:e.packages.length,disabled:ea,loading:C===`bulk:${e.scope}`,label:c(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:u_(e.scope,c)}),onChange:t=>void en(e.scope,e.packages,t)}),children:u_(e.scope,c)}),M?.scope===e.scope&&(0,r.jsx)(d9,{error:M.error,note:M.note}),e.packages.map(e=>{let t=uB(e),n=!b&&x===t;return(0,r.jsxs)(d7,{active:n,title:e.description??e.source,onClick:()=>{v(t),y(!1),I(null),T(null)},children:[(0,r.jsx)(cS,{active:!e.disabled,color:uq(e.status)}),(0,r.jsx)(ce,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),A[uB(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:c("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(cw,{active:b,onClick:()=>{y(!0),I(null),T(null)},children:c("i18n.addPlugin")})]}),(0,r.jsx)(cv,{children:(0,r.jsx)(ct,{className:"is-fill",children:b?(0,r.jsx)(uZ,{cwd:n,source:j,scope:w,projectResourcesLoaded:V,busy:es,actionError:E,onSourceChange:k,onScopeChange:S,onInstall:er}):h?null:q?q.builtin?(0,r.jsx)(uY,{extension:q,cwd:n,busyKey:C,actionError:E,actionMessage:$,sessionId:s,onToggle:et,onReloadSession:ei},uH(q)):(0,r.jsx)(uG,{extension:q}):K?(0,r.jsx)(uJ,{pkg:K,cwd:n,busyKey:C,actionError:E,actionMessage:$,sessionId:s,updateStatus:A[uB(K)],checkingUpdate:z.has(uB(K)),updateError:F,onAction:ee,onCheckUpdate:()=>void X(K),onReloadSession:ei},uB(K)):(0,r.jsx)(cx,{children:c("i18n.selectPackage")})})})]}),(0,r.jsxs)(cb,{status:eo>0?(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[eo," ",1===eo?c("i18n.update"):c("i18n.updates")]}):u?.diagnostics.length?(0,r.jsx)(cy,{tone:u.diagnostics.some(e=>"error"===e.type)?"error":"warning",summary:1===u.diagnostics.length?c("plugins.diagnostic"):c("plugins.diagnostics",{count:u.diagnostics.length}),details:u.diagnostics.map(uK)}):(0,r.jsx)(cy,{summary:u?[c("i18n.resourceCount",{count:(t=u.totals).extensions,label:c("i18n.extensionShort")}),c("i18n.resourceCount",{count:t.skills,label:c("i18n.skillShort")}),c("i18n.resourceCount",{count:t.prompts,label:c("i18n.promptShort")}),c("i18n.resourceCount",{count:t.themes,label:c("i18n.themeShort")})].join(" \xb7 "):""}),children:[!a&&(0,r.jsx)(cj,{onClick:o,children:c("i18n.close")}),el&&(0,r.jsx)(cj,{variant:eo>0?"primary":"secondary",onClick:()=>void(eo>0?Q():X()),disabled:ea,title:eo>0?c("i18n.updateAllPluginsHint"):void 0,children:B?c("i18n.updating"):W?c("i18n.checking"):eo>0?`${c("i18n.updateAllPlugins")} (${eo})`:c("i18n.checkUpdates")}),(0,r.jsx)(cj,{variant:"secondary",onClick:()=>void J(),disabled:ea,children:c("i18n.refresh")})]})]})}let uQ="\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}\\u00A0\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000\\uFE00-\\uFE0F\\u{E0100}-\\u{E01EF}\\u115F\\u1160\\u3164\\uFFA0\\u2800",u0=RegExp(`[${uQ}]`,"gu"),u1=RegExp(`[${uQ}]`,"u");function u2(e){return e.replace(u0,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let u4=/[\s"'`$|&;<>()*?#~]/;function u8(e){let t=u1.test(e),n=u2(e);return""===n||t||u4.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function u3(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(u8).join(" ")}function u5(e){let t=void 0!==e.command?u3(e.command,e.args):void 0,n=void 0!==e.url?u2(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function u6(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&u1.test(e))}function u9(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:u2(e.name??"")}}}function u7(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function pe(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function pt(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function pn(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?u2(e.error):"link-outside"===e.reason?void 0===t?void 0:u2(t):void 0}let pr="codemode";function pi(e){return`${e.scope}\0${e.name}`}function ps(e){return e?.trust?.decision===!0}function po(e){return"test"===e.origin?e.state:void 0!==e.closedAt||"not-trusted"===e.state?"on":e.state}function pl(e,t){return void 0!==e.invalidError?"invalid":e.webPasswordField?"web-password":e.enabled?"project"!==e.scope||t.projectServersLoad?"global"===e.scope&&e.shadowedByProject&&t.projectServersLoad?"replaced":"global"===e.scope&&e.overriddenByProject&&t.projectServersLoad?"overridden":t.mcpAvailable?e.status?po(e.status):"on":"mcp-off":"not-trusted":"disabled"}let pa={invalid:"mcp.state.invalid","web-password":"mcp.state.web-password",disabled:"mcp.state.disabled","not-trusted":"mcp.state.not-trusted",replaced:"mcp.state.replaced",overridden:"mcp.state.overridden","mcp-off":"mcp.state.mcp-off",connected:"mcp.state.connected","needs-auth":"mcp.state.needs-auth",failed:"mcp.state.failed",connecting:"mcp.state.connecting",disconnected:"mcp.state.disconnected",conflict:"mcp.state.conflict",on:"mcp.state.on"},pd={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function pc(e,t){return(t?.origin==="session"?pd[e]:void 0)??pa[e]}let pu={disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},pp={invalid:"mcp.stateShort.invalid","web-password":"mcp.stateShort.web-password",disabled:"mcp.stateShort.disabled","not-trusted":"mcp.stateShort.not-trusted",replaced:"mcp.stateShort.replaced",overridden:"mcp.stateShort.overridden","needs-auth":"mcp.stateShort.needs-auth",failed:"mcp.stateShort.failed",connecting:"mcp.stateShort.connecting",disconnected:"mcp.stateShort.disconnected",conflict:"mcp.stateShort.conflict"};function ph(e){return"on"===e||"connected"===e?"on":"invalid"===e||"web-password"===e||"failed"===e||"conflict"===e?"error":"not-trusted"===e||"needs-auth"===e||"disconnected"===e?"warning":"off"}function pm(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function pf(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),r=new Date(e),i=new Date(n);return r.getFullYear()===i.getFullYear()&&r.getMonth()===i.getMonth()&&r.getDate()===i.getDate()?r.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"}):r.toLocaleString(t,{dateStyle:"medium",timeStyle:"short"})}let pg={connecting:"mcp.session.state.connecting",connected:"mcp.session.state.connected","needs-auth":"mcp.session.state.needs-auth",failed:"mcp.session.state.failed",disconnected:"mcp.session.state.disconnected",conflict:"mcp.session.state.conflict","not-trusted":"mcp.session.state.not-trusted"},px={connecting:"mcp.session.summary.connecting",connected:"mcp.session.summary.connected","needs-auth":"mcp.session.summary.needs-auth",failed:"mcp.session.summary.failed",disconnected:"mcp.session.summary.disconnected",conflict:"mcp.session.summary.conflict","not-trusted":"mcp.session.summary.not-trusted"},pv={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},pb={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},py=["codemode","deferred","direct","hidden"],pj={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function pk(e){return"auto-enable-codemode-invalid"!==e.reason}function pw(e,t){return(t?["project","global"]:["global"]).map(t=>{let n=e.files.find(e=>e.scope===t);return{scope:t,...n?{file:n}:{},servers:e.servers.filter(e=>e.scope===t)}})}function pS(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function pC(e,t){let n=e.flatMap(e=>e.servers.map(pi));return t===pr||null!==t&&n.includes(t)?t:n[0]??null}function pN(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function pE(e){return e.projectOverride?.preference??e.preference}let pI={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},p$={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},pT={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},pM={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function pR(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let pA=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function pL(e,t){let n=e??{},r=n.breadth,i=n.trust;return{error:"string"==typeof n.error?n.error:`HTTP ${t}`,..."string"==typeof n.reason?{reason:n.reason}:{},..."string"==typeof n.path?{path:n.path}:{},..."string"==typeof n.name?{name:n.name}:{},..."string"==typeof n.suggestedName?{suggestedName:n.suggestedName}:{},...pA(n.names)?{names:n.names}:{},...pA(n.fields)?{fields:n.fields}:{},...Array.isArray(n.notes)?{notes:n.notes.filter(e=>"string"==typeof e?.code)}:{},..."string"==typeof r?.kind&&"string"==typeof r.path?{breadth:r}:{},..."boolean"==typeof i?.requiresTrust&&"boolean"==typeof i.trusted?{trust:i}:{},...!0===n.trustKept?{trustKept:!0}:{}}}async function pz(e,t,n,r){let i,{abortAtDeadline:s=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=new AbortController,l=()=>o.abort();r?.aborted?o.abort():r?.addEventListener("abort",l,{once:!0});let a=new Promise(e=>{i=setTimeout(()=>{e(t()),s&&o.abort()},n)});try{return await Promise.race([e(o.signal),a])}finally{clearTimeout(i),r?.removeEventListener("abort",l)}}function pP(e){return null!==e&&"object"==typeof e&&"object"==typeof e.mcp&&null!==e.mcp&&"object"==typeof e.codemode&&null!==e.codemode&&Array.isArray(e.files)&&Array.isArray(e.servers)}async function pW(e,t,n){let r,i;try{r=await t(e?`/api/mcp?cwd=${encodeURIComponent(e)}`:"/api/mcp",{cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&pP(i)?{ok:!0,data:i}:{ok:!1,error:pL(i,r.status)}}let pO=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function pF(e,t,n){let r=await pW(e,t,n);if(r.ok||!e||!r.error.reason||!pO.has(r.error.reason))return r;let i=await pW(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function pD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return pz(n=>pF(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function pB(e,t,n,r){let i,s;try{i=await n("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:r})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{s=await i.json()}catch{return{ok:!1,error:{error:`HTTP ${i.status}`}}}let o=i.ok&&null!==s&&"object"==typeof s?t(s):void 0;return void 0!==o?{ok:!0,stored:o}:{ok:!1,error:pL(s,i.status)}}async function pH(e,t,n){let r=await pB({codemode:e},e=>{var t;return"automatic"===(t=e.codemode)||"always"===t?e.codemode:void 0},t,n);return r.ok?{ok:!0,preference:r.stored}:r}async function p_(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return pz(n=>pH(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function pU(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return pz(async n=>{let r=await pB({codemodeMode:e},e=>{var t;return null!==(t=e.codemodeMode)&&"object"==typeof t&&("on"===t.value||"only"===t.value)&&(void 0===t.invalid||"string"==typeof t.invalid)?e.codemodeMode:void 0},t,n);return r.ok?{ok:!0,mode:r.stored}:r},()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function pK(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return pz(async n=>{let r=await pB({codemodeInlineBudget:e},e=>{var t;return null!==(t=e.codemodeInlineBudget)&&"object"==typeof t&&(void 0===t.value||"number"==typeof t.value)&&(void 0===t.invalid||"string"==typeof t.invalid)?e.codemodeInlineBudget:void 0},t,n);return r.ok?{ok:!0,inlineBudget:r.stored}:r},()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}function pq(e){return!e.available&&"builtin-disabled"!==e.reason}function pV(e,t){if(pq(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!ps(t.project))return"project-untrusted"}}let pZ={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function pJ(e){return!0!==e.notAnObject}function pG(e){return pJ(e)&&void 0===e.webPasswordField}async function pY(e,t,n){let r,i;try{r=await t("/api/mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&pP(i)?{ok:!0,data:i}:{ok:!1,error:pL(i,r.status)}}async function pX(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3,s={...e,...t?{cwd:t}:{}};return pz(e=>pY(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let pQ={"mcp-off":"mcp.test.blocked.mcp-off","project-untrusted":"mcp.test.blocked.project-untrusted","trust-unreadable":"mcp.test.blocked.trust-unreadable",invalid:"mcp.test.blocked.invalid","web-password":"mcp.test.blocked.web-password"};function p0(e,t){let n=pV(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let p1={"mcp-off":"mcp.test.blocked.mcp-off","project-untrusted":"mcp.test.blocked.project-untrusted","trust-unreadable":"mcp.test.blocked.trust-unreadable","server-invalid":"mcp.test.blocked.invalid","web-password":"mcp.test.blocked.web-password","entry-not-object":"mcp.test.refused.entry-not-object","invalid-request":"mcp.test.refused.invalid-request",unparsable:"mcp.test.refused.unparsable","invalid-shape":"mcp.test.refused.invalid-shape","link-dangling":"mcp.test.refused.link-dangling","link-outside":"mcp.test.refused.link-outside","not-a-file":"mcp.test.refused.not-a-file","too-large":"mcp.test.refused.too-large","too-many-servers":"mcp.test.refused.too-many-servers"},p2={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},p4={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},p8={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function p3(e){return(Math.max(0,e)/1e3).toFixed(1)}async function p5(e,t,n){let r,i;try{r=await t("/api/mcp/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&function(e){if(null===e||"object"!=typeof e)return!1;let t=e.result;return"string"==typeof e.configKey&&"string"==typeof e.name&&("global"===e.scope||"project"===e.scope)&&"object"==typeof t&&null!==t&&"string"==typeof t.state&&Array.isArray(t.tools)&&"number"==typeof t.testedAt}(i)?{ok:!0,data:i}:{ok:!1,error:pL(i,r.status)}}async function p6(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:6e4,s={scope:e.scope,name:e.name,...t?{cwd:t}:{}};return pz(e=>p5(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let p9="•••",p7=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),he=new Set([...p7,"auth","sig","code","pw"]),ht=["token","secret","password","passwd","apikey"],hn=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),hr=new Set(["-k"]);function hi(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function hs(e,t){let n=hi(e);return!(n.length>1&&hn.has(n[n.length-1]))&&n.some(e=>t.has(e)||ht.some(t=>e.length>t.length&&e.endsWith(t)))}function ho(e){return hs(e,p7)}let hl=RegExp("^(?:sk-[A-Za-z0-9_-]{16,}|(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{16,}|xox[abposr]-[A-Za-z0-9-]{10,}|(?:AKIA|ASIA)[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|ya29\\.[0-9A-Za-z_-]{20,}|npm_[A-Za-z0-9]{30,}|hf_[A-Za-z0-9]{30,}|shp(?:at|ss|ca|pa)_[A-Fa-f0-9]{20,}|dop_v1_[a-f0-9]{40,}|lin_api_[A-Za-z0-9]{20,})"),ha=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,hd=/^[A-Za-z0-9_\-+/=.~]+$/;function hc(e){return!(/\s/.test(e)||hf(e))&&(!!(hl.test(e)||ha.test(e))||!(e.length<24||!hd.test(e)||/^[./~]/.test(e)||/\.[A-Za-z][A-Za-z0-9]{0,4}$/.test(e)||e.split("/").length>2)&&!!/\d/.test(e)&&!!/[A-Za-z]/.test(e)&&(/[a-z]/.test(e)&&/[A-Z]/.test(e)||/^[0-9a-f]+$/i.test(e)||!/[-_.]/.test(e))&&function(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);let n=0;for(let r of t.values()){let t=r/e.length;n-=t*Math.log2(t)}return n}(e)>=3.5)}let hu=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,hp=RegExp(hu.source,"g"),hh=/^(?:bearer|basic|token)\s+/i;function hm(e,t,n){let r=e.replace(hh,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function hf(e){return hm(e.replace(/\$[$!]/g,"_x"),hu,hp)}let hg=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,hx=RegExp(hg.source,"g");function hv(e){return hm(e,hg,hx)}function hb(e,t){if(!e||""===t)return;e.push(t);let n=hk(t);n!==t&&e.push(n)}let hy=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function hj(e,t,n){let r=!1,i=e,s="",o=hy.exec(e);if(o){let[l,a,d]=o,c=d.lastIndexOf("@");if(c>=0&&!t(hk(d.slice(0,c)))){s=`${a}${p9}${d.slice(c)}`,r=!0;let e=d.slice(0,c);hb(n,e);let t=e.indexOf(":");t>=0&&hb(n,e.slice(t+1))}else s=l;i=e.slice(l.length)}let l=i.search(/[?#]/),a=l<0?i:i.slice(0,l),d=l<0?"":i.slice(l),c=a.split("/").map(e=>hc(hk(e))?(r=!0,hb(n,e),p9):e).join("/");return d=d.replace(/([?&#;])([^&#;]*)/g,(e,i,s)=>{let o=s.indexOf("=");if(o<0){let o=hk(s);return!hc(o)||t(o)?e:(r=!0,hb(n,s),`${i}${p9}`)}let l=s.slice(0,o),a=hk(s.slice(o+1));return""===a||t(a)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return hs(t,he)}(l)&&!hc(a)?e:(r=!0,hb(n,s.slice(o+1)),`${i}${l}=${p9}`)}),{value:`${s}${c}${d}`,masked:r}}function hk(e){try{return decodeURIComponent(e)}catch{return e}}let hw=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function hS(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&ho(r[1])){let[,i,s,o]=r;return t(o)?{value:e,masked:!1}:(hb(n,o.trim()),{value:`${i}:${s}${p9}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||hw.test(e)))return;let i=!1;return{value:r.map(e=>{let r=hw.exec(e);if(!r)return e;let[,s,o]=r;if(""===o.trim()||t(o))return e;if(ho(s.slice(0,-1).trim()))return i=!0,hb(n,o.trim()),`${s}${p9}`;let l=hS(o,t,n);return i||=l.masked,`${s}${l.value}`}).join(";"),masked:i}}(e,t,n):void 0;if(i)return i;let s=/^([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/.exec(e);if(s&&""!==s[2]&&ho(s[1]))return t(s[2])?{value:e,masked:!1}:(hb(n,s[2]),{value:`${s[1]}=${p9}`,masked:!0});if(/\s/.test(e)){var o,l,a;let r,i;return o=e,l=t,a=n,i=hE((r=o.split(/(\s+)/)).filter((e,t)=>t%2==0),l,!0,a),{value:r.map((e,t)=>t%2==0?i.values[t/2]:e).join(""),masked:i.masked}}if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(e))return hj(e,t,n);if(s&&""!==s[2]){let e=hS(s[2],t,n);return{value:`${s[1]}=${e.value}`,masked:e.masked}}return hc(e)&&!t(e)?(hb(n,e),{value:p9,masked:!0}):{value:e,masked:!1}}function hC(e){if(hr.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return ho(t)||"auth"===hi(t).at(-1)}let hN=/^(?:bearer|basic|token)$/i;function hE(e,t,n,r){let i=!1,s=!1;return{values:e.map(e=>{if(""===e)return e;if(s){if(n&&hN.test(e))return e;if(s=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,hb(r,e),p9)}let o=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(o){let[,e,n]=o;if(""!==n&&hC(e)&&!t(n))return i=!0,hb(r,n),`${e}=${p9}`;let s=hS(n,t,r);return i||=s.masked,`${e}=${s.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return s=hC(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(hN.test(e)||t&&ho(t[1]))return s=!0,e}let l=hS(e,t,r);return i||=l.masked,l.value}),masked:i}}function hI(e){let{values:t,masked:n}=hE(e,hv,!1);return{args:t,masked:n}}function h$(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function hT(e){return!e.startsWith("!")&&!hf(e)}function hM(e){return JSON.parse(e.replace(/^\uFEFF/,"").replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,e=>'"'===e[0]?e:"*"===e[1]?" ":"").replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g,(e,t)=>t??('"'===e[0]?e:"")))}let hR={"empty-input":"error","unrecognized-input":"error","invalid-json":"error","no-servers-found":"error","shell-operator":"error","shell-command-substitution":"error","shell-multiple-commands":"error","shell-unterminated-quote":"error","shell-parameter":"error","shell-expansion":"error","unsupported-url-scheme":"error","github-repo-link":"error","github-mcp-page":"error","github-page":"error","by-name-link":"error","badge-image":"error","install-link-invalid":"error","claude-desktop-import":"error","cli-unsupported":"error","cli-usage":"error","cli-unknown-option":"error","cli-option-needs-value":"error","cli-option-wrong-transport":"error","cli-invalid-pair":"error","cli-not-a-server":"error","pi-help":"error","field-required":"error","field-invalid-option":"error","field-reference-invalid":"error","sse-transport":"error","websocket-transport":"error","unsupported-transport":"error","ambiguous-command-and-url":"error","no-command-or-url":"error","zed-extension-server":"error","registry-packages-unsupported":"error","invalid-config":"error","dropped-key":"warning","variable-unsupported-here":"warning","variable-fallback-dropped":"warning","bare-dollar-literal":"warning","header-env-reference":"warning","client-secret-env-reference":"warning","shell-command-value":"warning","shell-variable":"warning","unsupported-variable":"warning","input-undefined":"warning","input-command-unsupported":"warning","timeout-clamped":"warning","timeout-dropped":"warning","timeout-unit-guessed":"warning","env-null-dropped":"warning","oauth-option-dropped":"warning","oauth-disable-unsupported":"warning","callback-url-dropped":"warning","callback-port-dropped":"warning","invalid-exposure-dropped":"warning","tool-filter-imported":"warning","transport-guessed":"warning","insecure-http":"warning","literal-secret":"warning","cli-option-ignored":"warning","cli-option-as-arg":"warning","cli-extra-arguments":"warning","mcp-remote-bridge":"warning","looks-like-pi-config":"warning","workspace-folder-relative":"warning","home-variable-translated":"warning","name-taken":"warning","escaped-value":"info","variable-translated":"info","home-translated":"info","timeout-converted":"info","env-value-stringified":"info","empty-authorization-dropped":"info","imported-disabled":"info","name-derived":"info","name-sanitized":"info","name-deduplicated":"info","command-split":"info","transport-assumed-http":"info","scheme-assumed":"info","client-secret-prompt":"info","userinfo-moved-to-header":"info"};Object.keys(hR);let hA={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},hL={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},hz={...hL,bareDollar:!0},hP={...hA,braceEnv:!0},hW=/^[A-Za-z_][A-Za-z0-9_]*$/,hO=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function hF(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function hD(e,t,n){let r=[],i=0;hO.lastIndex=0;for(let s=hO.exec(e);s;s=hO.exec(e)){let[o,l,a,d,c,u]=s,p=o;if(void 0!==l&&t.dollarBrace)p=function(e,t){let n=/^env:([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);if(n)return{kind:"env",name:n[1],from:t};let r=/^input:(.+)$/.exec(e);if(r)return{kind:"input",id:r[1],from:t};if("userHome"===e)return{kind:"home",from:t};if("workspaceFolder"===e||"workspaceRoot"===e||"CLAUDE_PROJECT_DIR"===e)return{kind:"workspace",from:t};if("workspaceFolderBasename"===e)return{kind:"workspace-basename",from:t};if("pathSeparator"===e||"/"===e)return"/";if("CLAUDE_PLUGIN_ROOT"===e||"CLAUDE_PLUGIN_DATA"===e)return{kind:"unsupported",from:t};if(hW.test(e))return{kind:"env",name:e,from:t};let i=/^([A-Za-z_][A-Za-z0-9_]*):?-([\s\S]*)$/.exec(e);return i?{kind:"env",name:i[1],from:t,fallback:i[2]}:/^[A-Za-z]+:/.test(e)?{kind:"unsupported",from:t}:t}(l,o);else if(void 0!==a&&t.bareDollar)p={kind:"env",name:a,from:o};else if(void 0!==d&&t.percent&&n)p={kind:"env",name:d,from:o};else if(void 0!==c&&t.braceEnv)p="env"===c&&hW.test(u)?{kind:"env",name:u,from:o}:{kind:"unsupported",from:o};else if(void 0!==d||void 0!==c){hF(r,e.slice(i,s.index+1)),i=s.index+1,hO.lastIndex=s.index+1;continue}hF(r,e.slice(i,s.index)),"string"==typeof p?hF(r,p):r.push(p),i=s.index+o.length}return hF(r,e.slice(i)),r}function hB(e){let{atStart:t=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.replace(/\$/g,"$$$$");return t&&n.startsWith("!")?`$${n}`:n}function hH(e){return e.startsWith("!")}function h_(e){if(hH(e))return[];let t=[];for(let n=0;n<e.length;n++){if("$"!==e[n])continue;let r=e[n+1];if("$"===r||"!"===r){n++;continue}if("{"===r){let r=e.indexOf("}",n+2);if(r<0)continue;let i=e.slice(n+2,r);hW.test(i)&&!t.includes(i)&&t.push(i),n=r;continue}let i=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(n+1));i&&(t.includes(i[0])||t.push(i[0]),n+=i[0].length)}return t}let hU=/<[A-Za-z][^<>\n]{0,80}>|\{\{\s*[A-Za-z_][\w.-]*\s*\}\}|\b[Yy][Oo][Uu][Rr][_-][A-Za-z0-9_.-]*[A-Za-z0-9]|\b[A-Za-z0-9_-]{0,80}[A-Za-z0-9][_-](?:HERE|[Hh]ere)\b|\b(?:REPLACE[_-]?ME|CHANGE[_-]?ME|PLACEHOLDER)\b|\bMY_[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PAT)\b|\b(?:sk|pk|ghp|gho|github_pat|glpat|xoxb|xoxp)[_-][xX*]{4,}\b|\b[xX]{6,}\b/g,hK=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,hq=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,hV=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function hZ(e){return e.join("\0")}function hJ(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function hG(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function hY(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let hX=new Set(["HOME","USERPROFILE"]);class hQ{constructor(e,t){this.source=e,this.rawPi=t,this.args=[],this.env=[],this.headers=[],this.oauth={},this.notes=[]}note(e,t){let n=JSON.stringify([e,t??{}]);this.notes.some(e=>JSON.stringify([e.code,e.params??{}])===n)||this.notes.push(t?{code:e,params:t}:{code:e})}}function h0(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let h1=/\$\{[^{}]*\}/g,h2=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class h4{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(h0),this.urlText=h0(e.url??[])}encode(e,t){let n,r=hG(e),i=hJ(e),s=h0(t),o=[],l=!1,a=()=>o.every(e=>""===e),d=e=>{if(!r)return void o.push(e);let t=/\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e);t&&this.draft.note("bare-dollar-literal",{field:i,name:t[1]});let n=hB(e,{atStart:a()});n!==e&&(l=!0),o.push(n)},c=e=>o.push(e),u=e=>o.push({field:e});if(!r&&hY(e)&&1===t.length&&"text"in t[0]&&hq.test(s)){let t="args"===e[0]?/^(?:--?[A-Za-z][A-Za-z0-9_.-]*|[A-Za-z_][A-Za-z0-9_]*)=/.exec(s)?.[0]??"":"",n=s.slice(t.length);if(hq.test(n))return t&&c(t),u(this.field(e,"placeholder-path",n,n,"text")),this.target(e,o,void 0)}let p=0;return t.forEach((o,l)=>{let h=t[l+1],m=void 0===h||"text"in h&&/^[\\/]/.test(h.text),f=(t,r,i)=>{let o=0;for(let[d,c]of function(e){let t=e.trim();if(hK.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=hV.exec(t);if(n&&hK.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];hU.lastIndex=0;for(let t=hU.exec(e);t;t=hU.exec(e))/^your[-_]/.test(t[0])&&/[@/]/.test(e[t.index-1]??"")||r.push([t.index,t.index+t[0].length]);return r}(t)){var l,a;if(i.some(e=>{let[t,n]=e;return d<n&&c>t}))continue;d>o&&r(t.slice(o,d)),"url"===e[0]&&h8(s,p+d)&&(n="uri-component");let h=t.slice(d,c);u(this.field(e,"placeholder",(l=e,a=h,"env"===l[0]||"headers"===l[0]?l[1]:a.replace(/^[<{\s]+|[>}\s]+$/g,"")||hJ(l)),h)),o=c}o<t.length&&r(t.slice(o))};switch(o.kind){case"text":f(o.text,d,[]);break;case"pi":{var g;let e=h?(g=o.text,(/\$+$/.exec(g)?.[0].length??0)%2==1?`${g}$`:g):o.text;if(r&&a()&&hH(e)){this.draft.note("shell-command-value",{field:i}),c(e);break}let t=[...e.matchAll(h1)].map(e=>[e.index,e.index+e[0].length]);f(e,c,t);break}case"env":r?(c(`$\{${o.name}}`),void 0!==o.fallback&&this.draft.note("variable-fallback-dropped",{field:i,name:o.name,fallback:o.fallback}),o.shell?this.draft.note("shell-variable",{field:i,name:o.name}):o.from!==`$\{${o.name}}`&&this.draft.note("variable-translated",{field:i,from:o.from,to:`$\{${o.name}}`})):hY(e)&&a()&&hX.has(o.name)&&m?(c("~"),this.draft.note("home-translated",{field:i,from:o.from})):(u(this.field(e,"variable",o.name,o.from,void 0,o.fallback)),this.draft.note(o.shell?"shell-variable":"variable-unsupported-here",{field:i,name:o.name}));break;case"input":u(this.inputField(e,o));break;case"home":r?(c("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:o.from,to:"${HOME}"})):hY(e)&&a()&&m?(c("~"),this.draft.note("home-translated",{field:i,from:o.from})):u(this.field(e,"home","userHome",o.from,"text"));break;case"workspace":"url"===e[0]||"oauth"===e[0]?u(this.field(e,"variable","workspaceFolder",o.from,"text")):(c("."),this.draft.note("workspace-folder-relative",{field:i,from:o.from}));break;case"workspace-basename":u(this.field(e,"workspace-basename","workspaceFolderBasename",o.from,"text"));break;case"unsupported":u(this.field(e,"unsupported-variable",o.from,o.from)),this.draft.note("unsupported-variable",{field:i,variable:o.from});break;case"prompt":"url"===e[0]&&h8(s,p)&&(n="uri-component"),u(this.promptField(e,o))}p+=("text"in o?o.text:o.from).length}),l&&this.draft.note("escaped-value",{field:i}),this.target(e,o,n)}target(e,t,n){let r=t.filter(e=>""!==e);for(let t of new Set(r.flatMap(e=>"string"==typeof e?[]:[e.field]))){let i=this.fields.get(t);i.targets.some(t=>hZ(t.path)===hZ(e))||i.targets.push({path:e,parts:r,...n?{encoding:n}:{}})}return r.map(e=>"string"==typeof e?e:this.fields.get(e.field).placeholder??"").join("")}field(e,t,n,r,i,s){let o=h2.has(t)?`${t}.${n}`:hJ(e);if(h2.has(t)){if(this.fields.has(o))return o}else for(let t=2;this.fields.has(o);t++)o=`${hJ(e)}#${t}`;let l=this.isSecretContext(e,r)||ho(n),a="headers"===e[0]&&"authorization"===e[1].toLowerCase();return this.fields.set(o,{id:o,kind:i??(l?"password":"text"),reason:t,label:n,placeholder:r,...void 0!==s?{defaultValue:s}:{},..."placeholder"===t&&a?{optional:!0}:{},targets:[]}),o}inputField(e,t){let n=`input.${t.id}`;if(this.fields.has(n))return n;let r=this.draft.inputs?.get(t.id);r?"command"===r.type&&this.draft.note("input-command-unsupported",{id:t.id}):this.draft.note("input-undefined",{id:t.id});let i=r?.type==="pickString"&&r.options&&r.options.length>0?r.options:void 0,s=r?.password===!0||this.isSecretContext(e,t.from);return this.fields.set(n,{id:n,kind:i?"select":s?"password":"text",reason:"input",label:t.id,placeholder:t.from,...r?.description?{description:r.description}:{},...r?.default!==void 0?{defaultValue:r.default}:{},...i?{options:i}:{},targets:[]}),n}promptField(e,t){return this.fields.has(t.id)||this.fields.set(t.id,{id:t.id,kind:t.options?"select":t.secret||this.isSecretContext(e,t.from)?"password":"text",reason:t.reason,label:t.label,placeholder:t.from,...t.description?{description:t.description}:{},...void 0!==t.defaultValue?{defaultValue:t.defaultValue}:{},...t.options?{options:t.options}:{},...t.optional?{optional:!0}:{},targets:[]}),t.id}isSecretContext(e,t){switch(e[0]){case"env":case"headers":return ho(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(hI([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&hI([t,"x"]).args[1]===p9}case"url":{var n;let e=this.urlText.indexOf(t),r=e<0?void 0:/[?&]([^=&?#]+)=[^&#]*$/.exec(this.urlText.slice(0,e))?.[1];return void 0!==r&&(n=r,hj(`https://host.invalid/?${n}=x`,hv).masked)}default:return!1}}}function h8(e,t){let n=e.indexOf("//"),r=e.slice(n<0?0:n+2).search(/[/?#]/);return r>=0&&t>=(n<0?0:n+2)+r}function h3(e,t,n){let r=n?void 0:function(e){let t;try{t=new URL(e)}catch{return}if(""===t.username&&""===t.password)return;let n=e=>{try{return decodeURIComponent(e)}catch{return e}},r=new TextEncoder().encode(`${n(t.username)}:${n(t.password)}`),i="";for(let e of r)i+=String.fromCharCode(e);return t.username="",t.password="",{url:t.toString(),authorization:`Basic ${btoa(i)}`}}(t);if(!r){e.url=[{kind:"text",text:t}];return}e.url=[{kind:"text",text:r.url}],e.headers.push(["Authorization",[{kind:"text",text:r.authorization}]]),e.note("userinfo-moved-to-header")}let h5=/^[A-Za-z0-9_-]+$/;function h6(e,t){let n=new Set(t);if(!n.has(e))return e;for(let t=2;;t++){let r=`${e}-${t}`;if(!n.has(r))return r}}let h9=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function h7(e){let t=e.trim(),n=t.lastIndexOf("@");n>0&&(t=t.slice(0,n)),t=t.replace(/==.*$|\[.*\]$/,"");let r="",i=/^@([^/]+)\/(.+)$/.exec(t);if(i)r=i[1],t=i[2];else if(t.includes("/")){let e=t.split("/").filter(Boolean);t=e[e.length-1]??t}let s=mt(t);return s&&!h9.has(s.toLowerCase())?s:mt(r)||r||s||t}let me=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function mt(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,me)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let mn=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function mr(e){let t;try{t=new URL(e).hostname}catch{return""}if("localhost"===t||"127.0.0.1"===t||"[::1]"===t||"::1"===t)return"local";if(/^\d+(?:\.\d+){3}$/.test(t))return"";let n=t.split(".").filter(Boolean);n.length>1&&n.pop(),n.length>1&&/^(?:co|com|org|net|ac|gov)$/.test(n[n.length-1])&&n.pop();let r=n.filter(e=>!mn.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let mi=new Set(["-e","--env","--env-file","-v","--volume","-p","--publish","--name","--network","--net","-w","--workdir","-u","--user","--mount","--entrypoint","-l","--label","--platform","--pull","-h","--hostname","--add-host","--cpus","-m","--memory","--restart","--runtime","--cap-add","--cap-drop","--device","--dns","--ipc","--pid","--security-opt","--tmpfs","--ulimit","--log-driver","--log-opt","--gpus"]);function ms(e,t){for(let n=0;n<e.length;n++){let r=e[n];if("--"===r)return e[n+1];if(r.startsWith("-")){!r.includes("=")&&t.has(r)&&n++;continue}return r}}function mo(e){let t=e.split(/[\\/]/).filter(Boolean);for(let e=t.length-1;e>=0;e--){let n=t[e].replace(/\.[A-Za-z0-9]+$/,"");if(!h9.has(n.toLowerCase())&&"."!==n&&".."!==n)return mt(n.replace(/_/g,"-"))||n}return""}function ml(e,t){ma(e,t)&&md(e,Math.ceil(t/1e3),t)}function ma(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function md(e,t,n){let r=Math.min(Math.max(t,1),3600);void 0!==n&&e.note("timeout-converted",{from:n,to:r}),r!==t&&e.note("timeout-clamped",{from:t,to:r}),e.timeout=r}let mc=["codemode","deferred","direct","hidden"],mu={"codemode-deferred":"codemode"},mp=["localhost","127.0.0.1","[::1]"];function mh(e){return"string"==typeof e&&mc.includes(e)?e:"string"==typeof e&&Object.hasOwn(mu,e)?mu[e]:void 0}function mm(e){try{return new URL(e)}catch{return}}function mf(e){let t=mm(e);return void 0!==t&&"http:"===t.protocol&&mp.includes(t.hostname)&&""===t.search&&""===t.hash}function mg(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function mx(e){return mg(e)&&Object.values(e).every(e=>"string"==typeof e)}function mv(e,t){if(!h5.test(e))return{problem:"name",name:e};if(!mg(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:s,toolExposure:o,description:l}=t;if(void 0!==r&&!mh(r))return{problem:"exposure",value:String(r)};if(void 0!==o){if(!mg(o))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(o))if(!mh(t))return{problem:"tool-exposure",tool:e}}if(void 0!==i&&"boolean"!=typeof i)return{problem:"enabled"};if(void 0!==l&&"string"!=typeof l)return{problem:"description"};if(void 0!==s&&("number"!=typeof s||!(s>0)))return{problem:"timeout",value:String(s)};if("sse"===n)return{problem:"sse"};if("string"==typeof t.url&&(void 0===n||"http"===n||"streamable-http"===n)){let e=mm(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!mx(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!mg(e))return{problem:"oauth"};if(void 0!==e.clientId&&"string"!=typeof e.clientId)return{problem:"oauth-client-id"};if(void 0!==e.clientSecret&&"string"!=typeof e.clientSecret)return{problem:"oauth-client-secret"};let r=e.callbackPort;if(void 0!==r&&("number"!=typeof r||!Number.isInteger(r)||r<1||r>65535))return{problem:"callback-port",value:String(r)};if(void 0!==e.callbackUrl){if("string"!=typeof e.callbackUrl||!mf(e.callbackUrl))return{problem:"callback-url",value:String(e.callbackUrl)};let t=new URL(e.callbackUrl).port;if(t&&void 0!==r&&Number(t)!==r)return{problem:"callback-port-mismatch",value:t}}if(void 0!==e.scope&&"string"!=typeof e.scope)return{problem:"oauth-scope"};if(void 0!==e.clientName&&("string"!=typeof e.clientName||!e.clientName.trim()))return{problem:"oauth-client-name"};if(void 0!==e.clientRegistration&&"dcr"!==e.clientRegistration){if("cimd"!==e.clientRegistration)return{problem:"oauth-client-registration",value:String(e.clientRegistration)};if(void 0!==e.clientId||void 0!==e.clientName)return{problem:"oauth-client-registration-client"};let t="string"==typeof e.callbackUrl?mm(e.callbackUrl):void 0;if(t&&("[::1]"===t.hostname||"/callback"!==t.pathname))return{problem:"oauth-client-registration-callback"}}if(void 0!==e.authServerMetadataUrl&&!(void 0!==(n="string"==typeof(t=e.authServerMetadataUrl)?mm(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&mp.includes(n.hostname))))return{problem:"auth-server-metadata-url",value:String(e.authServerMetadataUrl)}}(t.oauth);if(n)return n;let r=t.auth;if(void 0!==r){if(!mg(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!mp.includes(e.hostname))return{problem:"auth-url"}}return}return"string"==typeof t.command&&(void 0===n||"stdio"===n)?void 0===t.args||Array.isArray(t.args)&&t.args.every(e=>"string"==typeof e)?void 0===t.env||mx(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let mb=/[A-Za-z_]/,my=/[A-Za-z0-9_]/,mj=/^[A-Za-z_][A-Za-z0-9_]*$/,mk=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),mw=new Set([..."|&;<>()"]),mS=/[0-9@*#?$!-]/,mC={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function mN(e,t){let n=t+1;for(;" "===e[n]||" "===e[n];)n++;return"\r"===e[n]&&"\n"===e[n+1]?n+2-t:"\n"===e[n]?n+1-t:0}function mE(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class mI{constructor(e){this.input=e,this.index=0,this.words=[],this.windowsWord=!1,this.lineBreak=!1}run(){try{this.scan()}catch(e){if(e instanceof m$)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new m$(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=mE(this.input,this.index)),this.parts}endWord(){if(!this.parts)return;let e=this.parts.filter(e=>"text"!==e.type||""!==e.value),t=e.length>0?e:this.parts.slice(0,1);this.words.push({parts:t,text:t.map(e=>"text"===e.type?e.value:e.raw).join("")}),this.parts=void 0,this.windowsWord=!1}appendText(e,t){let n=this.startWord(),r=n[n.length-1];r?.type==="text"&&r.quote===t?r.value+=e:n.push({type:"text",value:e,quote:t})}scan(){let{input:e}=this;for(;this.index<e.length;){let t=e[this.index];if(" "===t||" "===t)this.endWord(),this.index++;else if("\r"===t&&"\n"===e[this.index+1])this.index++;else if("\n"===t)this.endWord(),this.words.length>0&&(this.lineBreak=!0),this.index++;else if(("\\"===t||"^"===t||"`"===t)&&mN(e,this.index)>0)this.index+=mN(e,this.index);else if("#"!==t||this.parts)"'"===t?(this.startWord(),this.singleQuoted()):'"'===t?(this.startWord(),this.doubleQuoted()):"$"===t?this.dollar("none"):"`"===t?this.fail({code:"command-substitution",syntax:"`"}):mw.has(t)?this.fail({code:"shell-operator",operator:function(e,t){let n=e.slice(t,t+2);return["||","&&",";;",">>","<<",">&","<&",">|","<(",">(","&>"].includes(n)?n:e[t]}(e,this.index)}):"\\"===t?this.backslash():(this.appendText(t,"none"),this.index++);else for(;this.index<e.length&&"\n"!==e[this.index];)this.index++}this.endWord()}backslash(){let e=this.input[this.index+1];if(this.startWord(),void 0===e||this.windowsWord||!mk.has(e)){this.appendText("\\","none"),this.index++;return}this.appendText(e,"none"),this.index+=2}singleQuoted(){let e=this.input.indexOf("'",this.index+1);e<0&&this.fail({code:"unterminated-quote",quote:"'"}),this.appendText(this.input.slice(this.index+1,e),"single"),this.index=e+1}doubleQuoted(){let{input:e}=this,t=mE(e,this.index+1);for(this.index++,this.appendText("","double");this.index<e.length;){let n=e[this.index];if('"'===n)return void this.index++;if("\\"===n){let n=e[this.index+1];"\n"===n?this.index+=2:"\r"===n&&"\n"===e[this.index+2]?this.index+=3:'"'!==n&&(t||"$"!==n&&"`"!==n&&"\\"!==n)?(this.appendText("\\","double"),this.index++):(this.appendText(n,"double"),this.index+=2)}else"$"===n?this.dollar("double"):"`"===n?this.fail({code:"command-substitution",syntax:"`"}):(this.appendText(n,"double"),this.index++)}this.fail({code:"unterminated-quote",quote:'"'})}ansiQuoted(){let{input:e}=this;this.index+=2;let t="";for(;this.index<e.length;){let n=e[this.index];if("'"===n){this.appendText(t,"ansi"),this.index++;return}if("\\"!==n){t+=n,this.index++;continue}let r=e[this.index+1];if("x"===r&&/^[0-9A-Fa-f]{1,2}/.test(e.slice(this.index+2))){let n=/^[0-9A-Fa-f]{1,2}/.exec(e.slice(this.index+2))[0];t+=String.fromCharCode(parseInt(n,16)),this.index+=2+n.length}else if(("u"===r||"U"===r)&&/^[0-9A-Fa-f]{1,8}/.test(e.slice(this.index+2))){let n=RegExp(`^[0-9A-Fa-f]{1,${"u"===r?4:8}}`).exec(e.slice(this.index+2))[0],i=parseInt(n,16);t+=i>1114111||i>=55296&&i<=57343?e.slice(this.index,this.index+2+n.length):String.fromCodePoint(i),this.index+=2+n.length}else void 0!==r&&r in mC?(t+=mC[r],this.index+=2):(t+="\\",this.index++)}this.fail({code:"unterminated-quote",quote:"'"})}dollar(e){let{input:t}=this,n=t[this.index+1];if("("===n&&this.fail({code:"command-substitution",syntax:"("===t[this.index+2]?"$((":"$("}),"none"===e&&"'"===n){this.startWord(),this.ansiQuoted();return}if("none"===e&&'"'===n){this.startWord(),this.index++,this.doubleQuoted();return}if("{"===n)return void this.braced(e);if(void 0!==n&&mb.test(n)){let n=this.index+1;for(;n<t.length&&my.test(t[n]);)n++;let r=t.slice(this.index+1,n);this.startWord().push({type:"variable",name:r,raw:`$${r}`,quote:e}),this.index=n;return}void 0!==n&&mS.test(n)&&this.fail({code:"shell-parameter",parameter:`$${n}`}),this.appendText("$",e),this.index++}braced(e){let{input:t}=this,n=t.indexOf("}",this.index+2);n<0&&this.fail({code:"unsupported-expansion",expansion:t.slice(this.index)});let r=t.slice(this.index,n+1),i=r.slice(2,-1);if(/^[0-9@*#?$!-]$/.test(i)&&this.fail({code:"shell-parameter",parameter:r}),mj.test(i)){this.startWord().push({type:"variable",name:i,raw:r,quote:e}),this.index=n+1;return}let s=/^([A-Za-z_][A-Za-z0-9_]*):?-([\s\S]*)$/.exec(i);if(s&&!/[$`{}\\'"]/.test(s[2])){this.startWord().push({type:"variable",name:s[1],raw:r,quote:e,fallback:s[2]}),this.index=n+1;return}this.fail({code:"unsupported-expansion",expansion:r})}}class m$ extends Error{constructor(e){super(e.code),this.detail=e}}function mT(e){return new mI(e).run()}function mM(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function mR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let mA=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function mL(e){if(mA.some(t=>t in e))return!0;let t=e.oauth;return mR(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function mz(e){if(!mR(e))return!1;let{command:t,url:n,serverUrl:r,httpUrl:i}=e;return"string"==typeof t&&""!==t||Array.isArray(t)&&"string"==typeof t[0]||mR(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function mP(e){switch(e.toLowerCase().replace(/[-_]/g,"")){case"stdio":case"local":return"stdio";case"http":case"streamablehttp":case"remote":return"http";case"sse":return"sse";case"ws":case"wss":case"websocket":return"ws";default:return"unknown"}}function mW(e){try{let t=new URL(e);if(!/\/sse\/?$/.test(t.pathname))return;return t.pathname=t.pathname.replace(/\/sse\/?$/,"/mcp"),t.toString()}catch{return}}function mO(e,t){let n=t?mW(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function mF(e){return e?{server:e}:{}}function mD(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function mB(e,t,n){let r;if(!mR(t))return{note:{code:"no-command-or-url",params:mF(e)}};let i=new Set,s=e=>(i.add(e),t[e]),o=n.rawPi,l=function(e,t){switch(e.flavor){case"zed":return hA;case"opencode":return hP;case"vscode":return hL;default:return mL(t)?hz:hL}}(n,t),a=s("name"),d=e??("string"==typeof a?a:void 0),c=new hQ(n.source,o),u=(e,t)=>{if(o)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&c.note("looks-like-pi-config"),hD(e,l,t)};c.name=d,c.inputs=n.inputs;let p=s("inputs");Array.isArray(p)&&(c.inputs=new Map([...n.inputs??[],...mU(p)]));let h=s("type"),m=s("command"),f=[s("httpUrl"),s("url"),s("serverUrl")].find(e=>"string"==typeof e);if("tcp"in t)return{note:{code:"websocket-transport",params:mF(d)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?mP(h):"unknown"))return{note:{code:"unsupported-transport",params:{...mF(d),type:String(h)}}};let g="string"==typeof m&&""!==m||Array.isArray(m)||mR(m),x=void 0!==f;if("sse"===r)return{note:mO(d,f)};if("ws"===r)return{note:{code:"websocket-transport",params:{...mF(d),...f?{url:f}:{}}}};if(void 0===r){if(g&&x)return{note:{code:"ambiguous-command-and-url",params:mF(d)}};if(x){if(void 0!==mW(f))return{note:mO(d,f)};r="http","mcp-servers"===n.flavor&&"string"==typeof t.url&&"string"!=typeof t.httpUrl&&c.note("transport-guessed")}else{if(!g)return{note:{code:"no-command-or-url",params:mF(d)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...mF(d),type:String(h)}}};if("stdio"===r&&!g||"http"===r&&!x)return{note:{code:"no-command-or-url",params:mF(d)}};if(c.transport=r,"stdio"===r){let e=function(e,t,n,r,i,s){let o,l=r("args"),a=r("opencode"===s.flavor?"environment":"env");if("opencode"===s.flavor&&void 0===a&&(a=r("env")),Array.isArray(n)){if(!n.every(e=>"string"==typeof e)||0===n.length)return{code:"invalid-config",params:{...mF(e.name),problem:"args"}};o=n[0],l=[...n.slice(1),...Array.isArray(l)?l:[]]}else if(mR(n))for(let t of(o="string"==typeof n.path?n.path:void 0,void 0===l&&(l=n.args),void 0===a&&(a=n.env),Object.keys(n)))["path","args","env"].includes(t)||e.note("dropped-key",{key:`command.${t}`});else"string"==typeof n&&(o=n);if(!o)return{code:"no-command-or-url",params:mF(e.name)};let d=Array.isArray(l)?[...l]:[];if(void 0!==l&&!Array.isArray(l))return{code:"invalid-config",params:{...mF(e.name),problem:"args"}};if(0===d.length&&/\s/.test(o.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(o.trim())){let t=mT(o.trim()),n=t.ok?t.words.map(mM):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:o}),o=n[0],d.push(...n.slice(1)))}for(let[t,n]of(e.command=i(o,!1),d.entries())){let r=mD(n);if(void 0===r)return{code:"invalid-config",params:{...mF(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==a){if(!mR(a))return{code:"invalid-config",params:{...mF(e.name),problem:"env"}};for(let[t,n]of Object.entries(a)){if(null===n){e.note("env-null-dropped",{name:t});continue}let r=mD(n);if(void 0===r){e.note("dropped-key",{key:`env.${t}`});continue}if("string"!=typeof n&&e.note("env-value-stringified",{name:t}),""===r&&ho(t)){e.env.push([t,[{kind:"prompt",id:`env.${t}`,reason:"empty",label:t,from:"",secret:!0}]]);continue}e.env.push([t,i(r,!0)])}}let c=r("cwd");for(let n of("string"==typeof c&&""!==c?e.cwd=i(c,!1):void 0!==c&&""!==c&&e.note("dropped-key",{key:"cwd"}),["headers","oauth","auth","url","httpUrl","serverUrl"]))n in t&&(r(n),e.note("dropped-key",{key:n}))}(c,t,m,s,u,n);if(e)return{note:e}}else!function(e,t,n,r,i){let s=r("headers"),o=i(n,!1),l=mR(s)&&Object.keys(s).some(e=>"authorization"===e.toLowerCase());if(1===o.length&&"text"in o[0]?h3(e,n,l):e.url=o,mR(s))for(let[t,n]of Object.entries(s)){let r=mD(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):ho(t)?e.headers.push([t,[{kind:"prompt",id:`headers.${t}`,reason:"empty",label:t,from:"",secret:!0,optional:!0}]]):e.headers.push([t,[]]);continue}e.headers.push([t,i(r,!0)])}else void 0!==s&&e.note("dropped-key",{key:"headers"});let a=r("oauth"),d=r("auth");if(!1===a?e.note("oauth-disable-unsupported"):mR(a)?mH(e,a,i):void 0!==a&&e.note("dropped-key",{key:"oauth"}),mR(d))for(let t of(mH(e,{...void 0!==d.CLIENT_ID?{clientId:d.CLIENT_ID}:{},...void 0!==d.CLIENT_SECRET?{clientSecret:d.CLIENT_SECRET}:{},...void 0!==d.scopes?{scopes:d.scopes}:{}},i,"auth."),Object.keys(d)))["CLIENT_ID","CLIENT_SECRET","scopes"].includes(t)||e.note("oauth-option-dropped",{key:`auth.${t}`});else void 0!==d&&e.note("dropped-key",{key:"auth"});for(let n of["command","args","env","environment","cwd"])n in t&&(r(n),e.note("dropped-key",{key:n}))}(c,t,f,s,u);let v=s("timeout");if(void 0!==v)if(o)"number"==typeof v&&v>0?c.timeout=v:c.note("timeout-dropped",{value:String(v)});else if("opencode"===n.flavor)c.note("timeout-dropped",{value:String(v)});else if(mL(t))ml(c,v);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?ma(c,v)&&md(c,Math.ceil(v),void 0):!function(e,t){if(!ma(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?md(e,Math.ceil(t/1e3),t):md(e,Math.ceil(t),void 0)}(c,v);let b=s("enabled"),y=s("disabled");!1===b||!0===y?(c.enabled=!1,c.note("imported-disabled")):(void 0!==b&&"boolean"!=typeof b||void 0!==y&&"boolean"!=typeof y)&&c.note("dropped-key",{key:void 0!==b?"enabled":"disabled"});let j=s("exposure");if(void 0!==j){let e=mh(j);e?c.exposure=e:c.note("invalid-exposure-dropped",{value:String(j)})}let k=s("toolExposure");if(void 0!==k){let e=mR(k)?Object.entries(k).map(e=>{let[t,n]=e;return[t,mh(n)]}):void 0;e?.every(e=>{let[,t]=e;return void 0!==t})?c.toolExposure=Object.fromEntries(e):c.note("invalid-exposure-dropped",{value:"toolExposure"})}if(o||void 0===j&&void 0===k||c.note("looks-like-pi-config"),o){let e=s("description");"string"==typeof e?c.description=e:void 0!==e&&c.note("dropped-key",{key:"description"})}for(let e of(m_(c,s("includeTools"),s("excludeTools")),Object.keys(t)))i.has(e)||c.note("dropped-key",{key:e});return{draft:c}}function mH(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"oauth.";for(let[i,s]of Object.entries(t))switch(i){case"clientId":"string"==typeof s&&""!==s&&(e.oauth.clientId=n(s,!1));break;case"clientSecret":"string"==typeof s&&""!==s&&(e.oauth.clientSecret=n(s,!0));break;case"callbackPort":"number"==typeof s&&Number.isInteger(s)&&s>=1&&s<=65535?e.oauth.callbackPort=s:e.note("callback-port-dropped",{value:String(s)});break;case"clientName":"string"==typeof s&&s.trim()?e.oauth.clientName=n(s,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"clientRegistration":"dcr"===s||"cimd"===s?e.oauth.clientRegistration=s:e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"authServerMetadataUrl":"string"==typeof s&&""!==s?e.oauth.authServerMetadataUrl=n(s,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"callbackUrl":case"redirectUri":"string"==typeof s&&mf(s)?e.oauth.callbackUrl=n(s,!1):e.note("callback-url-dropped",{value:String(s)});break;case"scope":case"scopes":{let t=Array.isArray(s)?s.filter(e=>"string"==typeof e).join(" "):"string"==typeof s?s:"";t&&(e.oauth.scope=n(t,!1));break}case"enabled":!1===s&&e.note("oauth-disable-unsupported");break;default:e.note("oauth-option-dropped",{key:`${r}${i}`})}let{callbackPort:i,callbackUrl:s}=e.oauth;if(void 0!==i&&s){let t=s.map(e=>"text"in e?e.text:"").join(""),n="";try{n=new URL(t).port}catch{}n&&Number(n)!==i&&(e.note("callback-url-dropped",{value:t}),e.oauth.callbackUrl=void 0)}}function m_(e,t,n){let r=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e&&""!==e):[],i=r(t),s=r(n);if(0===i.length&&0===s.length)return;let o={...e.toolExposure??{}};if(i.length>0){let t=e.exposure??"codemode";for(let n of(e.exposure="hidden",i))o[n]=t;e.note("tool-filter-imported",{mode:"include",tools:i.join(", ")})}for(let e of s)o[e]="hidden";s.length>0&&e.note("tool-filter-imported",{mode:"exclude",tools:s.join(", ")}),e.toolExposure=o}function mU(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)mR(n)&&"string"==typeof n.id&&t.set(n.id,{id:n.id,..."string"==typeof n.type?{type:n.type}:{},..."string"==typeof n.description?{description:n.description}:{},...!0===n.password?{password:!0}:{},..."string"==typeof n.default?{default:n.default}:{},...Array.isArray(n.options)?{options:n.options.map(e=>mR(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function mK(e,t,n,r){let i=[],s=0;for(let o of e.matchAll(/\{([A-Za-z_][A-Za-z0-9_-]*)\}/g)){o.index>s&&i.push({kind:"text",text:e.slice(s,o.index)});let l=mR(t)&&mR(t[o[1]])?t[o[1]]:{};i.push(mq(`${n}${o[1]}`,o[1],o[0],l,r)),s=o.index+o[0].length}return s<e.length&&i.push({kind:"text",text:e.slice(s)}),i}function mq(e,t,n,r,i){let s=Array.isArray(r.choices)?r.choices.filter(e=>"string"==typeof e):[];return{kind:"prompt",id:e,reason:i,label:t,from:n,secret:!0===r.isSecret,..."string"==typeof r.description?{description:r.description}:{},..."string"==typeof r.default?{defaultValue:r.default}:{},...!0===r.isRequired?{}:{optional:"registry-header"===i},...s.length>0?{options:s}:{}}}function mV(e,t,n){let r=[],i="",s=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...hD(i,t,n)),i="")};for(let t of e)"variable"===t.type?(s(),r.push({kind:"env",name:t.name,from:t.raw,shell:!0,...void 0!==t.fallback?{fallback:t.fallback}:{}})):i+=t.value;return s(),r}function mZ(e,t){let n="";for(let r=0;r<e.length;r++){let i=e[r];if("variable"===i.type){n+=i.raw;continue}let s=i.value.indexOf(t);if(s<0){n+=i.value;continue}n+=i.value.slice(0,s);let o=i.value.slice(s+t.length);return[n,[...o?[{...i,value:o}]:[],...e.slice(r+1)]]}}let mJ=/^https?:\/\//i,mG=/^wss?:\/\//i,mY={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},mX=new Set(["pi","claude","codex","gemini"]),mQ=new Set(["install","remove","uninstall","update","list","config"]);function m0(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let m1={local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},m2=new Map([["-l","--local"]]),m4=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"],m8=["env","cwd"];function m3(e,t,n,r){let i={positional:[],afterDashDash:[],values:new Map,lists:new Map,seen:new Map};for(let s=0;s<t.length;s++){let o=t[s],l=o.text;if("--"===l){i.afterDashDash.push(...t.slice(s+1));break}if(void 0!==r.stopAfter&&i.positional.length>=r.stopAfter){i.positional.push(...t.slice(s));break}if(!l.startsWith("-")||"-"===l){i.positional.push(o);continue}let a=l.startsWith("--")?l.indexOf("="):-1,d=a>0?l.slice(0,a):l,c=n[d];if(!c){if(i.positional.length>=r.asArgAfter){i.positional.push(o),i.seen.set(`as-arg:${d}`,d);continue}return{error:{code:"cli-unknown-option",params:{cli:e,option:d}}}}if(i.seen.set(c.name,d),"flag"===c.kind){i.values.set(c.name,!0);continue}let u=a>0?m5(o,a+1):void 0;if("value"===c.kind||"list"===c.kind){let n=u??t[++s];if(void 0===n)return{error:{code:"cli-option-needs-value",params:{cli:e,option:d}}};"value"===c.kind?i.values.set(c.name,n):i.lists.set(c.name,[...i.lists.get(c.name)??[],n]);continue}let p=u?[u]:[];if(!u)for(;s+1<t.length&&r.variadic(c.name,t[s+1]);)p.push(t[++s]);if(0===p.length)return{error:{code:"cli-option-needs-value",params:{cli:e,option:d}}};i.lists.set(c.name,[...i.lists.get(c.name)??[],...p])}return i}function m5(e,t){let n=0,r=[];for(let i of e.parts){let e="text"===i.type?i.value.length:i.raw.length;n>=t?r.push(i):n+e>t&&"text"===i.type&&r.push({...i,value:i.value.slice(t-n)}),n+=e}return{parts:r,text:e.text.slice(t)}}let m6=/^[A-Za-z_][A-Za-z0-9_]*=/,m9=/^[^\s:]+:/;function m7(e,t,n,r){for(let i of t??[]){let t=mZ(i.parts,"=");if(!t||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t[0]))return{code:"cli-invalid-pair",params:{cli:r,option:"--env",value:i.text}};e.env.push([t[0],mV(t[1],n,!0)])}}function fe(e,t,n,r){for(let i of t??[]){let t=mZ(i.parts,":"),s=t?.[0].trim();if(!t||!s)return{code:"cli-invalid-pair",params:{cli:r,option:"--header",value:i.text}};let o=function(e){let t=e.map(e=>({...e})),n=t[0];n?.type==="text"&&(n.value=n.value.replace(/^\s+/,""));let r=t[t.length-1];return r?.type==="text"&&(r.value=r.value.replace(/\s+$/,"")),t}(t[1]);if("authorization"===s.toLowerCase()&&o.every(e=>"text"===e.type&&""===e.value)){e.note("empty-authorization-dropped");continue}e.headers.push([s,mV(o,n,!0)])}}function ft(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function fn(e,t,n,r,i){let s,[o,l,...a]=r;if(!o||!l)return{code:"cli-usage",params:{cli:t}};e.name=o.text;let d=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===d){if("http"==(s=mJ.test(l.text)?"http":mG.test(l.text)?"ws":"stdio")&&void 0!==mW(l.text))return mO(o.text,l.text);"http"===s&&"gemini"===t&&e.note("transport-assumed-http")}else s="streamable-http"===d?"http":d;return"sse"===s?mO(o.text,l.text):"ws"===s?{code:"websocket-transport",params:{server:o.text,url:l.text}}:"http"===s?(e.transport="http",e.url=mV(l.parts,i,!1),a.length>0&&e.note("cli-extra-arguments",{cli:t,arguments:a.map(e=>e.text).join(" ")}),"http"):"stdio"!==s?{code:"unsupported-transport",params:{server:o.text,type:s}}:(e.transport="stdio",e.command=mV(l.parts,i,!1),e.args=a.map(e=>mV(e.parts,i,!1)),"stdio")}let fr={"-t":{name:"transport",kind:"value"},"--transport":{name:"transport",kind:"value"},"-e":{name:"env",kind:"variadic"},"--env":{name:"env",kind:"variadic"},"-H":{name:"header",kind:"variadic"},"--header":{name:"header",kind:"variadic"},"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-id":{name:"client-id",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"},"--callback-port":{name:"callback-port",kind:"value"},"--no-browser":{name:"no-browser",kind:"flag"}};function fi(e,t){return"env"===e?m6.test(t.text):m9.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function fs(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let fo={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function fl(e){let t,n=mM(e)??e.text;try{t=hM(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return mR(t)?{value:t}:{error:{code:"no-servers-found"}}}let fa={"--env":{name:"env",kind:"list"},"--url":{name:"url",kind:"value"},"--bearer-token-env-var":{name:"bearer-token-env-var",kind:"value"},"--oauth-client-id":{name:"oauth-client-id",kind:"value"},"--oauth-resource":{name:"oauth-resource",kind:"value"},"-c":{name:"config",kind:"value"},"--config":{name:"config",kind:"value"},"--enable":{name:"enable",kind:"value"},"--disable":{name:"disable",kind:"value"}},fd={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"-t":{name:"transport",kind:"value"},"--transport":{name:"transport",kind:"value"},"--type":{name:"transport",kind:"value"},"-e":{name:"env",kind:"list"},"--env":{name:"env",kind:"list"},"-H":{name:"header",kind:"list"},"--header":{name:"header",kind:"list"},"--timeout":{name:"timeout",kind:"value"},"--trust":{name:"trust",kind:"flag"},"--description":{name:"description",kind:"value"},"--include-tools":{name:"include-tools",kind:"value"},"--includeTools":{name:"include-tools",kind:"value"},"--exclude-tools":{name:"exclude-tools",kind:"value"},"--excludeTools":{name:"exclude-tools",kind:"value"}};function fc(e){let t=new Map;for(let n of e.replace(/^\?/,"").split("&")){if(!n)continue;let e=n.indexOf("="),r=e<0?n:n.slice(0,e),i=e<0?"":n.slice(e+1);t.set(fu(r),fu(i))}return t}function fu(e){try{return decodeURIComponent(e)}catch{return e}}function fp(e){let t=e.trim();for(let e=0;e<4;e++)try{return hM(t)}catch{let e=fu(t);if(e===t)break;t=e.trim()}}function fh(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function fm(e){let t=e.get("config");if(!t)return fh("config");let n=t.trim().startsWith("{")?t:function(e){let t=e.trim().replace(/ /g,"+").replace(/-/g,"+").replace(/_/g,"/").replace(/=+$/,"");if(/^[A-Za-z0-9+/]+$/.test(t)&&t.length%4!=1){t+="=".repeat((4-t.length%4)%4);try{let e=atob(t),n=Uint8Array.from(e,e=>e.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return}}}(t),r=void 0===n?void 0:fp(n);return mR(r)?{entries:[mB(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:fh("config")}function ff(e,t,n,r){return mR(e)?{entries:[mB(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:mU(r)})],notes:[]}:fh("config")}function fg(e){return{error:{code:"by-name-link",params:{name:e}}}}function fx(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function fv(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=e.replace(/&amp;/g,"&");try{t=new URL(r)}catch{if(/^https?:\/\/\S+$/i.test(r)&&0===n)return{entries:[fy(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return fh("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return fm(fc(t.search));return fh("cursor");case"vscode":case"vscode-insiders":case"code-oss":{let e=r.slice(r.indexOf(":")+1).replace(/^\/+/,""),t=/^mcp\/by-name\/([^?#]+)/.exec(e);if(t)return fg(fu(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return fg(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return ff(fp(fx(r)),"vscode-install-link");return fh(i)}case"vsweb+mcp":return ff(fp(fx(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return ff(fp(fx(r)),"copilot-app-install-link");return fh(i);case"ws":case"wss":return{entries:[{note:{code:"websocket-transport",params:{url:r}}}],notes:[]};case"http":case"https":return function(e,t,n){let r=e.hostname.toLowerCase().replace(/^www\./,""),i=e.pathname;if(("cursor.com"===r||"lmstudio.ai"===r)&&/^\/(?:[a-z]{2}(?:-[A-Za-z]{2,4})?\/)?install-mcp\/?$/.test(i))return fm(fc(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=fc(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return fv(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?ff(fp(e),"vscode-install-link",t.get("name")||void 0,fp(t.get("inputs")??"[]")):fh("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return ff(fp(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=fc(e.search).get("open");return t?fv(t,n+1):fh("open")}if(/\.(?:svg|png)$/i.test(i)&&("cursor.com"===r||"img.shields.io"===r||r.endsWith("githubusercontent.com")))return{error:{code:"badge-image"}};if("github.com"===r){let e=i.split("/").filter(Boolean);return"mcp"===e[0]&&e.length>=2?{error:{code:"github-mcp-page",params:{name:e.slice(1).join("/")}}}:"mcp"!==e[0]&&e.length>=2?{error:{code:"github-repo-link",params:{repository:`${e[0]}/${e[1]}`}}}:{error:{code:"github-page"}}}return{entries:[fy(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let fb=new Set(["localhost","127.0.0.1","[::1]"]);function fy(e,t){let n=mr(t)||void 0;if(void 0!==mW(t))return{note:mO(n,t)};let r=new hQ("url",!1);return r.transport="http",h3(r,t,!1),e?.protocol!=="http:"||fb.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let fj=/[\u200B-\u200D\u2060\uFEFF]/g,fk=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,fw={"unterminated-quote":"shell-unterminated-quote","shell-operator":"shell-operator","command-substitution":"shell-command-substitution","multiple-commands":"shell-multiple-commands","shell-parameter":"shell-parameter","unsupported-expansion":"shell-expansion"};function fS(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>hZ(e.path))))}function fC(e){var t;let n,r,i,s,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},l=(n=e.replace(fj,"").replace(/\u00A0/g," ").trim(),(r=/```[^\n]*\n([\s\S]*?)(?:```|$)/.exec(n))?n=r[1].trim():/^`[^`\n]+`$/.test(n)&&(n=n.slice(1,-1).trim()),(i=n.startsWith("[")?/\]\(([^()\s]+)\)\s*$/.exec(n):null)&&(n=i[1]),/^<\S+>$/.test(n)&&(n=n.slice(1,-1)),n);if(!l)return{ok:!1,notes:[{code:"empty-input"}]};if(l.startsWith("{")||l.startsWith("[")||/^"[^"\n]+"\s*:/.test(l))s=function(e,t){let n;try{n=hM(e)}catch(t){try{n=hM(`{${e.replace(/,\s*$/,"")}}`)}catch{return{error:{code:"invalid-json",params:{detail:t instanceof Error?t.message:String(t)}}}}}return function(e,t){let n=[],r=(e,t)=>Object.entries(e).map(e=>{let[n,r]=e;return mB(n,r,t)});if(Array.isArray(e)){let r=e.filter(mz);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>mB(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!mR(e))return{error:{code:"no-servers-found"}};let i=mR(e.server)&&(Array.isArray(e.server.remotes)||Array.isArray(e.server.packages))?e.server:Array.isArray(e.remotes)||Array.isArray(e.packages)?e:void 0;if(i)return{entries:function(e){let t="string"==typeof e.name?e.name:"",n=t?h7(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(mR):[],i=r.filter(e=>"string"==typeof e.type&&"http"===mP(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:mO(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:mF(n)}}]}return i.map(e=>{let r=new hQ("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=mK(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(mR):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,mK(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[mq(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(mR(e.mcpServers))return"boolean"!=typeof e.autoEnableCodemode||t||n.push({code:"looks-like-pi-config"}),{entries:r(e.mcpServers,{source:"mcp-servers-json",flavor:"mcp-servers",rawPi:t}),notes:n};if(mR(e.servers)){let t=mU(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(mR(e.mcp)){let t=e.mcp;if(mR(t.servers)){let e=mU(t.inputs);return{entries:r(t.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:e}),notes:n}}return{entries:r(t,{source:"opencode-json",flavor:"opencode",rawPi:!1}),notes:n}}if(mR(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return mR(r)&&("extension"===r.source||!mz(r))?{note:{code:"zed-extension-server",params:{server:n}}}:mB(n,mR(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(mz(e))return{entries:[mB(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let s=Object.values(e);return s.length>0&&s.every(mR)&&s.some(mz)?{entries:r(e,{source:"server-map",flavor:"mcp-servers",rawPi:t}),notes:n}:{error:{code:"no-servers-found"}}}(n,t)}(l,!0===o.rawPi);else if(fk.test(l)){if(!("error"in(s=fv(`http://${l}`))))for(let e of s.entries)"draft"in e&&e.draft.note("scheme-assumed",{url:`http://${l}`})}else{let e;s=!/\s/.test(l)&&/^[A-Za-z][A-Za-z0-9+.-]+:/.test(l)?fv(l):(e=mT(l.replace(/^(?:\$|%|>|❯|PS [^\n>]*>)[ \t]+/,"").replace(/[\u201C\u201D\u201E\u201F\u2033]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032]/g,"'").replace(/(^|\s)[\u2013\u2014](?=\S)/g,"$1--").replace(/(^|\s)[\u2013\u2014](?=\s|$)/g,"$1--"))).ok?0===e.words.length?{error:{code:"empty-input"}}:function(e){var t;let n=0,r=(t=e[0],(t?.text.split(/[\\/]/).pop()??"").replace(/\.(?:cmd|exe|ps1)$/i,"").toLowerCase());if(["npx","bunx","pnpx"].includes(r)){let t=1;for(;e[t]?.text.startsWith("-");)t++;let i=e[t]?.text.replace(/^(@?[^@]+)@.*$/,"$1");i&&mY[i]&&e[t+1]?.text==="mcp"&&(n=t,r=mY[i])}let i=e.slice(n+1);if(i[0]?.text==="mcp"&&i.length>=2){let e=i[1].text,t=i.slice(2);if("pi"===r&&"add"===e)return m0(function(e,t){if(t.some(e=>"--help"===e.text||"-h"===e.text))return{error:{code:"pi-help"}};let n=[],r=new Map,i=new Map;for(let t=0;t<e.length;t++){let s=m2.get(e[t].text)??e[t].text;if("--"===s||n.length>=2){n.push(...e.slice("--"===s?t+1:t));break}if(!s.startsWith("--")){n.push(e[t]);continue}let o=s.slice(2),l=m1[o];if(!l)return{error:{code:"cli-unknown-option",params:{cli:"pi",option:s}}};if("flag"===l){r.set(o,!0);continue}let a=e[++t];if(void 0===a)return{error:{code:"cli-option-needs-value",params:{cli:"pi",option:s}}};"list"===l?i.set(o,[...i.get(o)??[],a]):r.set(o,a)}let[s,...o]=n,l=r.get("url");if(!s||""===s.text||void 0===l==(0===o.length))return{error:{code:"cli-usage",params:{cli:"pi"}}};let a=e=>{let t=r.get(e);return!0===t?void 0:t},d=(void 0===l?m4:m8).find(e=>r.has(e)||i.has(e));if(d)return{error:{code:"cli-option-wrong-transport",params:{cli:"pi",option:`--${d}`,transport:void 0===l?"stdio":"http"}}};let c=new hQ("pi-mcp-add",!0);c.name=s.text,c.scopeHint=r.has("local")?"project":"global";let u=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"=",n=[];for(let r of i.get(e)??[]){let i=mZ(r.parts,t);if(!i||""===i[0])return{error:{code:"cli-invalid-pair",params:{cli:"pi",option:`--${e}`,value:r.text}}};let s=n.findIndex(e=>{let[t]=e;return t===i[0]});s>=0?n[s]=i:n.push(i)}return n},p={};if(void 0!==l&&!0!==l){c.transport="http",c.url=mV(l.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)c.headers.push([t,mV(n,"pi",!0)]);let t=a("bearer-token-env-var");if(void 0!==t){let e=["Authorization",[{kind:"pi",text:`Bearer $\{${t.text}}`}]],n=c.headers.findIndex(e=>{let[t]=e;return"Authorization"===t});n>=0?c.headers[n]=e:c.headers.push(e)}let n=a("oauth-client-id"),r=a("oauth-client-secret"),i=a("oauth-callback-port"),s=a("oauth-client-name");n&&(c.oauth.clientId=mV(n.parts,"pi",!1)),r&&(c.oauth.clientSecret=mV(r.parts,"pi",!0)),i&&(c.oauth.callbackPort=Number(i.text)),s&&(c.oauth.clientName=mV(s.parts,"pi",!1)),p.url=l.parts.some(e=>"variable"===e.type)?"https://placeholder.invalid/":l.text,(i||s)&&(p.oauth={...i?{callbackPort:Number(i.text)}:{},...s?{clientName:s.text}:{}})}else{c.transport="stdio";let e=u("env");if("error"in e)return e;for(let[t,n]of e)c.env.push([t,mV(n,"pi",!0)]);let[t,...n]=o;c.command=mV(t.parts,"pi",!1),c.args=n.map(e=>mV(e.parts,"pi",!1));let r=a("cwd");r&&(c.cwd=mV(r.parts,"pi",!1)),p.command=t.text}let h=a("exposure");void 0!==h&&(p.exposure=h.text,c.exposure=mh(h.text)??h.text);let m=a("description");void 0!==m&&(p.description=m.text,c.description=m.text);let f=mv("server",p);return f?{note:{code:"invalid-config",params:{server:s.text,...f}}}:{draft:c}}(t,i.slice(1)));if("claude"===r&&"add"===e)return m0(function(e){let t=m3("claude",e,fr,{asArgAfter:2,variadic:fi});if("error"in t)return{error:t.error};let n=new hQ("claude-mcp-add",!1),r=fn(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],hL);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};for(let[e,r]of t.seen)e.startsWith("as-arg:")&&n.note("cli-option-as-arg",{cli:"claude",option:r});if(n.scopeHint=ft(t.values.get("scope")),"http"===r){var i,s;let e;t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"claude",option:"--env",transport:"http"});let r=fe(n,t.lists.get("header"),hL,"claude");if(r)return{error:r};let o=t.values.get("client-id");o&&!0!==o&&(n.oauth.clientId=mV(o.parts,hL,!1)),t.values.has("client-secret")&&fs(n);let l=t.values.get("callback-port");l&&!0!==l&&(i=n,Number.isInteger(e=Number(s=l.text))&&e>=1&&e<=65535?i.oauth.callbackPort=e:i.note("callback-port-dropped",{value:s}))}else{for(let e of["header","client-id","client-secret","callback-port"])(t.lists.has(e)||t.values.has(e))&&n.note("cli-option-wrong-transport",{cli:"claude",option:t.seen.get(e)??`--${e}`,transport:"stdio"});let e=m7(n,t.lists.get("env"),hL,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return m0(function(e){let t=m3("claude",e,fo,{asArgAfter:1/0});if("error"in t)return{error:t.error};let[n,r,...i]=[...t.positional,...t.afterDashDash];if(!n||!r||i.length>0)return{error:{code:"cli-usage",params:{cli:"claude"}}};let s=fl(r);if("error"in s)return s;let o=mB(n.text,s.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in o||(o.draft.scopeHint=ft(t.values.get("scope")),t.values.has("client-secret")&&"http"===o.draft.transport&&!o.draft.oauth.clientSecret&&fs(o.draft)),o}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return m0(function(e){let t=m3("codex",e,fa,{asArgAfter:1/0,stopAfter:2});if("error"in t)return{error:t.error};let n=t.afterDashDash,r=t.lists.get("env")??[],[i,...s]=t.positional,o=n.length>0?n:s,l=t.values.get("url");if(!i||void 0===l==(0===o.length)||n.length>0&&s.length>0)return{error:{code:"cli-usage",params:{cli:"codex"}}};let a=new hQ("codex-mcp-add",!1);for(let e of(a.name=i.text,["config","enable","disable"]))t.values.has(e)&&a.note("cli-option-ignored",{cli:"codex",option:t.seen.get(e)});if(t.values.has("oauth-resource")&&a.note("oauth-option-dropped",{key:"--oauth-resource"}),void 0!==l&&!0!==l){if(r.length>0)return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:"--env",transport:"http"}}};if(void 0!==mW(l.text))return{note:mO(i.text,l.text)};a.transport="http",a.url=mV(l.parts,hA,!1);let e=t.values.get("bearer-token-env-var");e&&!0!==e&&a.headers.push(["Authorization",[{kind:"text",text:"Bearer "},{kind:"env",name:e.text,from:`$\{${e.text}}`}]]);let n=t.values.get("oauth-client-id");n&&!0!==n&&(a.oauth.clientId=mV(n.parts,hA,!1))}else{for(let e of["bearer-token-env-var","oauth-client-id","oauth-resource"])if(t.values.has(e))return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:`--${e}`,transport:"stdio"}}};a.transport="stdio";let e=m7(a,r,hA,"codex");if(e)return{error:e};a.command=mV(o[0].parts,hA,!1),a.args=o.slice(1).map(e=>mV(e.parts,hA,!1))}return{draft:a}}(t));if("gemini"===r&&"add"===e)return m0(function(e){let t=m3("gemini",e,fd,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new hQ("gemini-mcp-add",!1),r=fn(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],hz);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=ft(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=fe(n,t.lists.get("header"),hz,"gemini");if(e)return{error:e}}else{t.lists.has("header")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--header",transport:"stdio"});let e=m7(n,t.lists.get("env"),hz,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&ml(n,Number(i.text)),["trust","description"]))t.values.has(e)&&n.note("cli-option-ignored",{cli:"gemini",option:`--${e}`});let s=e=>{let n=t.values.get(e);return n&&!0!==n?n.text.split(",").map(e=>e.trim()).filter(Boolean):void 0};return m_(n,s("include-tools"),s("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(mX.has(r)&&!e.startsWith("-")&&("claude"!==r||"serve"!==e))return{error:{code:"cli-not-a-server",params:{cli:r,command:`mcp ${e}`}}}}return"pi"===r&&i[0]&&mQ.has(i[0].text)?{error:{code:"cli-not-a-server",params:{cli:r,command:i[0].text}}}:["code","code-insiders","codium","cursor"].includes(r)&&e.some(e=>"--add-mcp"===e.text||e.text.startsWith("--add-mcp="))?function(e){let t=[];for(let n=0;n<e.length;n++){let r,i=e[n].text;if("--add-mcp"===i)r=e[++n];else{if(!i.startsWith("--add-mcp="))continue;r=m5(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let s=fl(r);if("error"in s)return s;t.push(mB(void 0,s.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):m0(function(e){let t=new hQ("command-line",!1);t.transport="stdio";let n=0,r=()=>{for(;n<e.length;n++){let r=function(e){let[t,...n]=e.parts;if(t?.type!=="text"||"none"!==t.quote)return;let r=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(t.value);if(!r)return;let i=t.value.slice(r[0].length);return{name:r[1],value:[...i?[{...t,value:i}]:[],...n]}}(e[n]);if(!r)break;t.env.push([r.name,mV(r.value,hA,!0)])}};if(r(),e[n]?.text==="env"){if(n++,e[n]?.text.startsWith("-"))return{error:{code:"cli-unknown-option",params:{cli:"env",option:e[n].text}}};r()}let i=e[n];if(!i)return{error:{code:"no-command-or-url"}};t.command=mV(i.parts,hA,!1),t.args=e.slice(n+1).map(e=>mV(e.parts,hA,!1));let s=e.slice(n+1).map(e=>e.text),o=s.some(e=>/^mcp-remote(?:@|$)/.test(e))?s.find(e=>mJ.test(e)):void 0;return o&&t.note("mcp-remote-bridge",{url:o}),{draft:t}}(e))}(e.words):{error:function(e){let{code:t,...n}=e;return Object.keys(n).length>0?{code:fw[t],params:n}:{code:fw[t]}}(e.error)}}if("error"in s)return{ok:!1,notes:[s.error]};let a=[...s.notes],d=[],c=[...o.takenNames??[]],u=new Set;for(let e of s.entries){if("note"in e){a.push(e.note);continue}let n=function(e){let t,n=new h4(e);if("stdio"===e.transport&&e.command&&""!==h0(e.command)){let r=n.encode(["command"],e.command),i=e.args.map((e,t)=>n.encode(["args",t],e)),s={};for(let[t,r]of e.env)s[t]=n.encode(["env",t],r);t={command:r,...i.length>0?{args:i}:{},...Object.keys(s).length>0?{env:s}:{},...e.cwd?{cwd:n.encode(["cwd"],e.cwd)}:{}}}else{if("http"!==e.transport||!e.url||""===h0(e.url))return{note:{code:"no-command-or-url",...e.name?{params:{server:e.name}}:{}}};let r=n.encode(["url"],e.url),i={};for(let[t,r]of e.headers)i[t]=n.encode(["headers",t],r);let s={},{clientId:o,clientSecret:l,callbackPort:a,clientName:d,clientRegistration:c,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;o&&(s.clientId=n.encode(["oauth","clientId"],o)),l&&(s.clientSecret=n.encode(["oauth","clientSecret"],l)),void 0!==a&&(s.callbackPort=a),d&&(s.clientName=n.encode(["oauth","clientName"],d)),c&&(s.clientRegistration=c),u&&(s.callbackUrl=n.encode(["oauth","callbackUrl"],u)),p&&(s.scope=n.encode(["oauth","scope"],p)),h&&(s.authServerMetadataUrl=n.encode(["oauth","authServerMetadataUrl"],h)),t={url:r,...Object.keys(i).length>0?{headers:i}:{},...Object.keys(s).length>0?{oauth:s}:{}}}return void 0!==e.exposure&&(t.exposure=e.exposure),void 0!==e.toolExposure&&(t.toolExposure=e.toolExposure),!1===e.enabled&&(t.enabled=!1),void 0!==e.timeout&&(t.timeout=e.timeout),void 0!==e.description&&(t.description=e.description),{server:{name:e.name??"",...void 0!==e.originalName?{originalName:e.originalName}:{},config:t,fields:[...n.fields.values()],notes:e.notes,source:e.source,rawPi:e.rawPi,...e.scopeHint?{scopeHint:e.scopeHint}:{}}}}(e.draft);if("note"in n){a.push(n.note);continue}let r=n.server,i=r.name,s=!i;s&&(i=function(e){if("url"in e)return mr(e.url);let t=e.args??[],n=t.some(e=>/^mcp-remote(?:@|$)/.test(e))?t.find(e=>/^https?:\/\//i.test(e)):void 0;return n&&mr(n)||function(e,t){let n=e.split(/[\\/]/).pop()?.replace(/\.(?:cmd|exe|bat|ps1)$/i,"").toLowerCase()??"";switch(n){case"npx":case"bunx":case"pnpx":{let e=ms(t,new Set(["-p","--package","-c","--call"]));return e?h7(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?ms(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?h7(n):""}case"uvx":case"pipx":{let e=ms("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?h7(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?ms(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?mo(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?ms(t.slice(e+1),mi):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return mt(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return h7(t[e+1].replace(/_/g,"-"));let n=ms(t,new Set(["-X","-W"]));return n?mo(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=ms("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?mo(e):""}default:return mt(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let o=(t=i,h5.test(t))?i:i.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,48).replace(/[-_]+$/g,"")||"server";o!==i&&i&&(r.originalName=r.originalName??i,r.notes.push({code:"name-sanitized",params:{original:i,name:o}}));let l=h6(o,s?[...c,...u]:u);l!==o&&(r.notes.push({code:"name-deduplicated",params:{original:o,name:l}}),o=l),!s&&c.includes(o)&&r.notes.push({code:"name-taken",params:{name:o,suggestedName:h6(o,[...c,...u])}}),r.name=o;let p=mv(o,function(e){let t=fS(e),n=JSON.parse(JSON.stringify(e.config));t.has(hZ(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(hZ(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){a.push({code:"invalid-config",params:{server:o,...p}});continue}!function(e){let t=fS(e);for(let n of fA(e.config))t.has(hZ(n))||e.notes.push({code:"literal-secret",params:{field:hJ(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=h_(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=h_(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(o),d.push(r)}return 0===d.length?{ok:!1,notes:a.length>0?a:[{code:"no-servers-found"}]}:{ok:!0,servers:d,notes:a}}let fN=/^[A-Za-z_][A-Za-z0-9_]*$/;function fE(e,t,n){let[r,i]=t;if("command"===r||"url"===r||"cwd"===r){void 0!==n&&(e[r]=n);return}if("args"===r){e.args[i]=n??"";return}let s={...e[r]??{}};void 0===n?delete s[i]:s[i]=n,0===Object.keys(s).length?delete e[r]:e[r]=s}function fI(e){let t=fS(e);return fA(e.config).filter(e=>hG(e)&&!t.has(hZ(e)))}function f$(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let fT=/^(?:bearer|basic|token)\s+/i;function fM(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.parse(JSON.stringify(e.config)),i=new Map,s=[],o=new Map(fI(e).map(e=>[hJ(e),e])),l=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=o.get(e);r?fN.test(n)?l.push([r,n]):s.push({code:"field-reference-invalid",params:{field:e,problem:f$(t)}}):s.push({code:"field-reference-invalid",params:{field:e,problem:"target"}})}for(let n of e.fields){let e=t[n.id];if("object"==typeof e&&null!==e){let t=e.reference,r="string"==typeof t?t.trim():"";fN.test(r)?"select"!==n.kind&&n.targets.every(e=>hG(e.path)&&void 0===e.encoding)?i.set(n.id,{reference:r}):s.push({code:"field-reference-invalid",params:{field:n.id,problem:"target"}}):s.push({code:"field-reference-invalid",params:{field:n.id,problem:f$(t)}});continue}let r=("string"==typeof e?e:n.defaultValue??"").trim();""===r?n.optional?i.set(n.id,void 0):s.push({code:"field-required",params:{field:n.id}}):"select"===n.kind&&n.options&&!n.options.includes(r)?s.push({code:"field-invalid-option",params:{field:n.id}}):i.set(n.id,{text:r})}if(s.length>0)return{ok:!1,notes:s};let a=new Set,d=new Set;for(let t of e.fields)for(let e of t.targets){let n=i.get(t.id);"password"===t.kind&&void 0!==n&&"text"in n&&a.add(hJ(e.path));let s=hZ(e.path);if(d.has(s))continue;if(d.add(s),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){fE(r,e.path,void 0);continue}let o="";for(let t of e.parts){var c,u,p,h;o+="string"==typeof t?t:(c=i.get(t.field),u=e.path,p=""===o,h=e.encoding,"reference"in c?`$\{${c.reference}}`:"uri-component"===h?encodeURIComponent(c.text):hG(u)?hB(c.text,{atStart:p}):c.text)}fE(r,e.path,o)}for(let[e,t]of l){let n=function(e,t){let[n,r]=t,i=e[n];return void 0===r||"object"!=typeof i||null===i?void 0===r?i:void 0:i[r]}(r,e),i="headers"===e[0]&&"string"==typeof n?n.match(fT)?.[0]??"":"";fE(r,e,`${i}$\{${t}}`)}for(let e of fA(r))a.add(hJ(e));return{ok:!0,config:r,secretPaths:[...a]}}let fR=["command","args","env","cwd","url","headers","oauth"];function fA(e){let t=[];for(let n of function(e){if(!h$(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(h$(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&hT(i)&&""!==i&&(ho(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||hS(i,hf).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=h$(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&hT(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&hj(e.url,hv).masked&&t.push({kind:"url"}),"string"==typeof e.command&&hS(e.command,hv).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&hI(e.args.filter(e=>"string"==typeof e)).masked&&t.push({kind:"args"}),t}(e))switch(n.kind){case"env":t.push(["env",n.name]);break;case"header":t.push(["headers",n.name]);break;case"oauth-client-secret":t.push(["oauth","clientSecret"]);break;case"url":t.push(["url"]);break;case"command":t.push(["command"]);break;case"args":{let n="args"in e&&Array.isArray(e.args)?e.args.map(e=>"string"==typeof e?e:""):[];hI(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>fR.indexOf(e[0])-fR.indexOf(t[0]))}let fL="PI_WEB_PASSWORD";function fz(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fP(e){return fz(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function fW(e){if(!fz(e))return[];if(!("url"in e))return fP(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=fP(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=fz(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let fO={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function fF(e,t,n){let r=fC(e,{rawPi:t});if(!r.ok)return;let i=r.servers[Math.min(n,r.servers.length-1)],{config:s}=i,o="url"in s?["url",s.url]:["command",s.command,s.args??[]];return JSON.stringify([i.source,i.originalName??i.name,o])}function fD(e,t){let n={...e,...t},r=fF(e.text,e.rawPi,e.server);if(void 0!==r&&r===fF(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function fB(e){return hR[e.code]??"warning"}function fH(e,t){let n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=e.params??{},s={};for(let[e,t]of Object.entries(i))s[e]="string"==typeof t?u2(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(s.field=u2(e.label))}"invalid-config"===e.code&&(s.problem=t("tool-exposure"===(n=String(i.problem??"no-command-or-url"))&&void 0!==i.tool?"mcp.importProblem.tool-exposure.tool":"args"===n&&void 0!==i.index?"mcp.importProblem.args.index":`mcp.importProblem.${n}`,s)),"cli-option-wrong-transport"===e.code&&("stdio"===i.transport||"http"===i.transport)&&(s.transport=t(`mcp.transport.${i.transport}`));let o=t(function(e){let t=e.params??{};switch(e.code){case"field-reference-invalid":return`mcp.importNote.field-reference-invalid.${"target"===t.problem||"missing"===t.problem?t.problem:"name"}`;case"sse-transport":return void 0===t.suggestedUrl?"mcp.importNote.sse-transport":"mcp.importNote.sse-transport.suggested";case"timeout-unit-guessed":return`mcp.importNote.timeout-unit-guessed.${"milliseconds"===t.unit?"milliseconds":"seconds"}`;case"tool-filter-imported":return`mcp.importNote.tool-filter-imported.${"exclude"===t.mode?"exclude":"include"}`;default:return`mcp.importNote.${e.code}`}}(e),s);return"string"==typeof s.server?t("mcp.importNote.forServer",{server:s.server,note:o}):o}let f_={empty:"mcp.importField.reason.empty",input:"mcp.importField.reason.input",variable:"mcp.importField.reason.variable",home:"mcp.importField.reason.home","workspace-basename":"mcp.importField.reason.workspace-basename","unsupported-variable":"mcp.importField.reason.unsupported-variable","client-secret":"mcp.importField.reason.client-secret","registry-header":"mcp.importField.reason.registry-header","registry-variable":"mcp.importField.reason.registry-variable"},fU={url:"mcp.add.source.url","command-line":"mcp.add.source.command-line","pi-mcp-add":"mcp.add.source.pi-mcp-add","claude-mcp-add":"mcp.add.source.claude-mcp-add","claude-mcp-add-json":"mcp.add.source.claude-mcp-add-json","codex-mcp-add":"mcp.add.source.codex-mcp-add","gemini-mcp-add":"mcp.add.source.gemini-mcp-add","vscode-add-mcp":"mcp.add.source.vscode-add-mcp","mcp-servers-json":"mcp.add.source.mcp-servers-json","vscode-json":"mcp.add.source.vscode-json","zed-json":"mcp.add.source.zed-json","opencode-json":"mcp.add.source.opencode-json","server-object":"mcp.add.source.server-object","server-map":"mcp.add.source.server-map","registry-server-json":"mcp.add.source.registry-server-json","cursor-install-link":"mcp.add.source.cursor-install-link","vscode-install-link":"mcp.add.source.vscode-install-link","visual-studio-install-link":"mcp.add.source.visual-studio-install-link","copilot-app-install-link":"mcp.add.source.copilot-app-install-link"},fK=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),fq=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),fV=[{source:"url",text:"https://mcp.example.com/mcp"},{source:"command-line",text:"npx -y @modelcontextprotocol/server-everything"},{source:"pi-mcp-add",text:"pi mcp add docs --url https://mcp.example.com/mcp"},{source:"claude-mcp-add",text:"claude mcp add --transport http docs https://mcp.example.com/mcp"},{source:"claude-mcp-add-json",text:'claude mcp add-json docs \'{"type":"http","url":"https://mcp.example.com/mcp"}\''},{source:"codex-mcp-add",text:"codex mcp add fetch -- uvx mcp-server-fetch"},{source:"gemini-mcp-add",text:"gemini mcp add --transport http docs https://mcp.example.com/mcp"},{source:"vscode-add-mcp",text:`code --add-mcp '${fq}'`},{source:"mcp-servers-json",text:'{ "mcpServers": { "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] } } }'},{source:"vscode-json",text:'{ "servers": { "docs": { "type": "http", "url": "https://mcp.example.com/mcp" } } }'},{source:"zed-json",text:'{ "context_servers": { "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] } } }'},{source:"opencode-json",text:'{ "mcp": { "docs": { "type": "remote", "url": "https://mcp.example.com/mcp" } } }'},{source:"server-object",text:'{ "type": "http", "url": "https://mcp.example.com/mcp" }'},{source:"server-map",text:'{ "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] } }'},{source:"registry-server-json",text:'{ "name": "com.example/docs", "version": "1.0.0", "remotes": [{ "type": "streamable-http", "url": "https://mcp.example.com/mcp" }] }'},{source:"cursor-install-link",text:`cursor://anysphere.cursor-deeplink/mcp/install?name=fetch&config=${btoa(fK)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(fq)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(fq)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(fq)}`}];function fZ(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!(!r&&e.targets.every(e=>{let{parts:t}=e;return 1===t.length})))return[...new Set(e.targets.map(r=>{let{parts:i}=r;return i.map(r=>"string"==typeof r?u2(r):r.field===e.id?n:`‹${u2(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function fJ(e){return"select"!==e.kind&&e.targets.every(e=>hG(e.path)&&void 0===e.encoding)}let fG=/^[A-Za-z_][A-Za-z0-9_]*$/;function fY(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];let r=t.map(e=>e.replace(/[^A-Za-z0-9]+/g,"_")).join("_").replace(/_+/g,"_").replace(/^_|_$/g,"").toUpperCase();return fG.test(r)?r:void 0}let fX=/^(?:proxy-)?authorization$/i;function fQ(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return fG.test(t)?t:fY(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return fY(t,...n)??fY(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(fX.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===fL?void 0:n}function f0(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function f1(e,t){let n=e;for(let e of t)n=n.split(e).join(p9);return{text:n,masked:n!==e}}function f2(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function f4(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(pk);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function f8(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function f3(e,t,n){return{action:"add",text:e.text,values:t.values,...Object.keys(t.secretReferences).length>0?{secretReferences:{...t.secretReferences}}:{},server:t.server&&t.parsed.ok?t.parsed.servers.indexOf(t.server):0,name:t.name,scope:t.scope,rawPi:e.rawPi,...t.trustFolder?{trustFolder:!0}:{},...n&&n.length>0?{confirmHostEnv:[...n]}:{}}}function f5(e,t,n){switch(e.kind){case"trust-too-broad":return t(f9[e.breadth.kind],{path:n(e.breadth.path)});case"secret":return t(e.fixed?"mcp.add.projectBlocked.secretFixed":"mcp.add.projectBlocked.secret",{fields:e.fields.join(", ")});case"file-problem":return t("mcp.add.projectBlocked.file-problem",{path:n(e.path),reason:t(`mcp.fileProblem.${e.reason}`)});default:return t(f6[e.kind])}}let f6={"no-project":"mcp.add.projectBlocked.no-project","project-not-listed":"mcp.add.projectBlocked.project-not-listed","trust-unreadable":"mcp.add.projectBlocked.trust-unreadable","project-untrusted":"mcp.add.projectBlocked.project-untrusted","untrusted-decision":"mcp.add.projectBlocked.untrusted-decision","folder-not-fresh":"mcp.add.projectBlocked.folder-not-fresh"},f9={home:"mcp.add.projectBlocked.trust-too-broad.home",root:"mcp.add.projectBlocked.trust-too-broad.root","contains-home":"mcp.add.projectBlocked.trust-too-broad.contains-home","contains-agent-dir":"mcp.add.projectBlocked.trust-too-broad.contains-agent-dir","contains-folder":"mcp.add.projectBlocked.trust-too-broad.contains-folder","contains-project":"mcp.add.projectBlocked.trust-too-broad.contains-project","too-many-folders":"mcp.add.projectBlocked.trust-too-broad.too-many-folders"};function f7(e){return u2(eS(e))}function ge(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let gt=[{href:"https://glama.ai/mcp/servers",label:"glama.ai"},{href:"https://smithery.ai/servers",label:"smithery.ai"},{href:"https://mcp.so/",label:"mcp.so"},{href:"https://registry.modelcontextprotocol.io/",label:"MCP Registry"},{href:"https://github.com/mcp",label:"github.com/mcp"}],gn=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function gr(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,tn.s)();if(0===t.length)return null;let s={error:0,warning:1,info:2},o=[...t].sort((e,t)=>s[fB(e)]-s[fB(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:o.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${fB(e)}`,children:fH(e,i,n)},`${t}\0${e.code}`))})}let gi={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function gs(e){let{data:t,cwd:n,draft:s,busy:o,controlsBusy:l,failure:a,onDraftChange:d,onSubmit:c,onTrustProject:u}=e,{t:p}=(0,tn.s)(),h=(0,i.useId)(),m=(0,i.useId)(),f=(0,i.useMemo)(()=>(function e(t,n,r){let i,s=function(e,t){let n=e=>({kind:"blocked",block:e});if(!t)return n({kind:"no-project"});let r=e.project;if(!r)return n({kind:"project-not-listed"});let i=r.trust;if(!i||void 0!==i.decisionError)return n({kind:"trust-unreadable"});if(!0===i.decision)return{kind:"write"};if(!1===i.decision)return n({kind:"untrusted-decision"});if(i.requiresTrust)return n({kind:"project-untrusted",trustable:pN(r)});let s=r.trustFolder;return s?s.allowed?{kind:"trust-and-write",folder:r.cwd}:n("trust-too-broad"===s.reason?{kind:"trust-too-broad",breadth:s.breadth}:{kind:"folder-not-fresh"}):n({kind:"project-untrusted",trustable:!1})}(n,r),o=e=>fC(t.text,{rawPi:t.rawPi,takenNames:f8(n,e)}),l=o(t.scope??"global"),a=l.ok?l.servers[Math.min(t.server,l.servers.length-1)]:void 0,d=t.scope??(a?.scopeHint==="project"&&"write"===s.kind?"project":"global");d!==(t.scope??"global")&&(a=(l=o(d)).ok?l.servers[Math.min(t.server,l.servers.length-1)]:void 0);let c={parsed:l,name:t.name??"",scope:d,projectMode:s,..."blocked"===s.kind?{projectBlock:s.block}:{},values:{},pasteSecrets:[],secretReferences:{},fieldProblems:{},secretPaths:[],trustFolder:!1},u=pq(n.mcp);if(!a)return{...c,submitBlock:{kind:u?"mcp-off":"nothing"}};let p=t.name??a.name,h=function(e,t){let n={};for(let r of e.fields){let e=t.references[r.id];void 0!==e&&fJ(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(a,t),m=fI(a).map(hJ),f=Object.fromEntries(m.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),g=fM(a,h,f),x={};if(!g.ok)for(let e of g.notes){let t=e.params?.field;"field-required"===e.code||"string"!=typeof t||t in x||(x[t]=e)}let v=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={};for(let n of e.fields){let e=t[n.id];"object"==typeof e?r[n.id]=fG.test(e.reference.trim())?e:{reference:"VALUE"}:void 0!==e&&""!==e.trim()?r[n.id]=e:void 0!==n.defaultValue?r[n.id]=n.defaultValue:n.optional?r[n.id]=void 0:r[n.id]="select"===n.kind?n.options?.[0]??"x":"x"}let i=fM(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,fG.test(n.trim())?n:"VALUE"]})));return i.ok?i.secretPaths:[]}(a,h,f),b=function(e,t,n){let r=n?.ok?n.config:e.config,i=n?.ok?function(e,t){let n=new Set;for(let r of e.fields){let e=t[r.id];if("password"!==r.kind||"string"!=typeof e||""===e.trim())continue;let i=e.trim();n.add(i),n.add(i.replace(/\$/g,"$$$$")),n.add(encodeURIComponent(i))}return[...n].filter(e=>""!==e).sort((e,t)=>t.length-e.length)}(e,t):[],s=!1!==r.enabled,o={source:e.source,commandFields:fW(r).filter(e=>{let{value:t}=e;return hH(t)}).map(f2),variableReferences:fW(r).map(e=>({...f2(e),variables:h_(e.value)})).filter(e=>{let{variables:t}=e;return t.length>0}),...r.exposure?{exposure:r.exposure}:{},enabled:s,unfilled:!n?.ok&&e.fields.length>0};if("url"in r){let e=f1(r.url,i);return{...o,transport:"http",target:u2(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let l=f1(u3(r.command,r.args??[]),i);return{...o,transport:"stdio",target:l.text,...void 0!==r.cwd?{cwd:u2(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:l.masked}}(a,h,g),y=g.ok?mv(p,g.config):void 0,j="blocked"===s.kind?s.block:v.length>0?{kind:"secret",fields:v,fixed:!v.every(f0)}:f4("project",n),k=f8(n,d),w=n.files.find(e=>e.scope===d);if(u)i={kind:"mcp-off"};else if(h5.test(p))if(k.includes(p))i={kind:"name-taken",name:p,suggestedName:h6(p,k),...w?{path:w.path}:{}};else if(g.ok)if(y)i={kind:"config-invalid",note:{code:"invalid-config",params:"url"===y.problem?{...y,url:b.target}:y}};else if(void 0!==function(e,t){for(let{value:n,...r}of fW(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(fL):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===fL))return r}(g.config,{isCommandConfigValue:hH,getConfigValueEnvVarNames:h_}))i={kind:"web-password"};else if("project"===d&&j)i={kind:"scope",block:j};else{let e=f4(d,n);e&&(i={kind:"scope",block:e})}else{let e=e=>{let t=String(e.params?.field??"");return a.fields.find(e=>e.id===t)?.label??t},t=g.notes.filter(e=>"field-required"===e.code||"field-reference-invalid"===e.code&&e.params?.problem==="missing");i=t.length>0?{kind:"fields",fields:[...new Set(t.map(e))]}:{kind:"field-invalid",fields:[...new Set(g.notes.map(e))]}}else i={kind:"name-invalid"};return void 0===t.scope&&"project"===d&&j?e({...t,scope:"global"},n,r):{parsed:l,server:a,name:p,scope:d,projectMode:s,...j?{projectBlock:j}:{},values:h,pasteSecrets:m,secretReferences:f,fill:g,fieldProblems:x,secretPaths:v,preview:b,...i?{submitBlock:i}:{},trustFolder:"project"===d&&"trust-and-write"===s.kind}})(s,t,n),[s,t,n]),g=(0,i.useMemo)(()=>(function(e){let t=fC(e,{rawPi:!0});if(!t.ok)return!1;let n=fC(e,{rawPi:!1});return t.servers.some((e,t)=>e.rawPi&&!(n.ok&&n.servers[t]?.rawPi))})(s.text),[s.text]),{parsed:x,server:v,preview:b,projectBlock:y,submitBlock:j}=f,k=v?[...v.notes,...x.notes].filter(e=>"literal-secret"!==e.code||!f.pasteSecrets.includes(String(e.params?.field))):[],w=void 0!==s.name&&s.name!==v?.name?[]:k.filter(e=>gn.has(e.code)),S=k.filter(e=>!gn.has(e.code)),C=!o&&!l&&void 0===j,N=()=>{C&&c(f3(s,f))},E=e=>d({...s,...e}),I=t.files.find(e=>e.scope===f.scope)?.path??("project"===f.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),$=j&&(""!==s.text.trim()||"mcp-off"===j.kind)?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];switch(e.kind){case"mcp-off":return t("mcp.reason.mcp-off");case"nothing":return t("mcp.add.blocked.nothing");case"name-invalid":return t("mcp.add.nameInvalid");case"name-taken":return t("mcp.add.nameTaken",{name:u2(e.name),path:e.path?f7(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(u2).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(u2).join(", ")});case"config-invalid":return fH(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return f5(e.block,t,f7)}}(j,p,v?.fields):void 0,T=y?.kind==="project-untrusted"&&y.trustable&&u,M=b?"http"===b.transport?b.headerNames:b.envNames:[];return(0,r.jsxs)(cm,{title:p("mcp.add.title"),catalogs:gt,target:(0,r.jsxs)(cp,{value:f.scope,label:p("config.saveTo"),options:[{value:"global",label:ge("global",p)},{value:"project",label:ge("project",p),disabled:void 0!==y&&"project"!==f.scope}],path:f7(I),disabledReason:y?f5(y,p,f7):null,onChange:e=>E({scope:e}),children:[T&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(cj,{size:"small",onClick:u,children:p("mcp.trust.trustButton")})}),f.trustFolder&&"trust-and-write"===f.projectMode.kind&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:p("mcp.add.trustExplain",{path:f7(f.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:s.text,canSubmit:C,onValueChange:e=>d(fD(s,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===s.text.trim()?fV.map(e=>{let{source:t,text:n}=e;return{label:p(fU[t]),value:n}}):[],multiline:!0,children:[g&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:s.rawPi,onChange:e=>d(fD(s,{rawPi:e.target.checked}))}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:p("mcp.add.rawPi")}),s.rawPi&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.rawPiOn")})]})]}),!x.ok&&""!==s.text.trim()&&(0,r.jsx)(gr,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(cl,{label:p("mcp.add.serverLabel"),children:[(0,r.jsx)("select",{className:"mcp-add-input","aria-label":p("mcp.add.serverLabel"),value:String(x.servers.indexOf(v??x.servers[0])),onChange:e=>E({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:u2(e.name)},`${t}\0${e.name}`))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.serverCount",{count:x.servers.length})})]}),v&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cl,{label:p("config.name"),children:(0,r.jsx)("input",{id:m,className:"mcp-add-input","aria-label":p("config.name"),value:f.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>E({name:e.target.value})})}),(0,r.jsx)(gr,{notes:w,fields:v.fields}),j?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(cj,{size:"small",onClick:()=>E({name:j.suggestedName}),children:p("mcp.add.useName",{name:u2(j.suggestedName)})})})]}),v&&b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(co,{children:p("mcp.add.preview")}),(0,r.jsxs)(ca,{children:[(0,r.jsx)(cd,{label:p("mcp.add.readAs"),children:p(fU[b.source])}),(0,r.jsx)(cd,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${b.transport}`)}),(0,r.jsx)(cd,{label:"http"===b.transport?p("mcp.detail.url"):p("mcp.detail.command"),tone:"plain",mono:!0,children:b.target}),"stdio"===b.transport&&void 0!==b.cwd&&(0,r.jsx)(cd,{label:p("mcp.detail.cwd"),mono:!0,children:b.cwd}),M.length>0&&(0,r.jsx)(cd,{label:"http"===b.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(go,{names:M})}),b.commandFields.length>0&&(0,r.jsx)(cd,{label:p("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.server.commandFields")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:b.commandFields.map(e=>{let t=u9(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})]})}),b.variableReferences.length>0&&(0,r.jsx)(cd,{label:p("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("http"===b.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:pt(b.variableReferences).map(e=>{let{variable:t,field:n}=e,i=u9(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:u2(t),field:p(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[b.unfilled&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.previewUnfilled")}),b.masked&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.server.masked")})]}),(0,r.jsx)(gr,{notes:S,fields:v.fields}),v.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(co,{children:p("mcp.add.fields")}),v.fields.map(e=>{var t;let n;return(0,r.jsx)(gl,{field:e,fields:v.fields,draft:s,suggestedName:(t=f.name,(n=e.targets[0])?fQ(hJ(n.path),t):void 0),problem:f.fieldProblems[e.id],onDraftChange:d},e.id)})]}),f.pasteSecrets.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(co,{children:p("mcp.add.secrets")}),f.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(ga,{label:e,draft:s,suggestedName:fQ(e,f.name),stored:f.fill?.ok?(t=f.fill.config,void 0!==(i="oauth.clientSecret"===(n=e)?"url"in t?t.oauth?.clientSecret:void 0:n.startsWith("headers.")?"url"in t?t.headers?.[n.slice(8)]:void 0:n.startsWith("env.")&&"command"in t?t.env?.[n.slice(4)]:void 0)&&hf(i)?i:void 0):void 0,problem:f.fieldProblems[e],onDraftChange:d},e)})]})]}),(0,r.jsx)(cj,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":o||void 0,"aria-describedby":$?h:void 0,onClick:N,children:o?p("mcp.add.adding"):f.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),$&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${j?.kind==="scope"?"is-warning":"is-dim"}`,children:$}),v&&!j&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.afterAdd")}),a&&(0,r.jsxs)("div",{role:"alert",className:"mcp-add-failure",children:[(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[p("mcp.add.failed")," ",function(e,t){if(e.timedOut)return t("mcp.actionTimedOut");if("trust-too-broad"===e.reason&&e.breadth)return t(f9[e.breadth.kind],{path:f7(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(f0)?"mcp.add.projectBlocked.secret":"mcp.add.projectBlocked.secretFixed",{fields:e.fields.join(", ")});if("name-taken"===e.reason&&e.name)return t("mcp.add.nameTaken",{name:u2(e.name),path:e.path?f7(e.path):"mcp.json"});let n=e.reason?gi[e.reason]:void 0;return n?t(n,{error:u2(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):u2(e.error)}(a,p)]}),a.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:f7(a.trust?.decisionPath??n??"")})}),a.notes&&a.notes.length>0&&(0,r.jsx)(gr,{notes:a.notes,fields:v?.fields}),"name-taken"===a.reason&&a.suggestedName&&j?.kind!=="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(cj,{size:"small",onClick:()=>E({name:a.suggestedName}),children:p("mcp.add.useName",{name:u2(a.suggestedName)})})}),"host-env-confirm"===a.reason&&a.names&&a.names.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.hostEnv.body",{names:a.names.map(u2).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(cj,{variant:"danger",size:"small",disabled:o||l||void 0!==j,onClick:()=>c(f3(s,f,a.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function go(e){let{names:t}=e,{t:n}=(0,tn.s)();return(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function gl(e){let t,{field:n,fields:s,draft:o,suggestedName:l,problem:a,onDraftChange:d}=e,{t:c}=(0,tn.s)(),u=(0,i.useId)(),p=a?{"aria-invalid":!0,"aria-describedby":u}:{},h=fJ(n),m=h?o.references[n.id]:void 0,f=void 0!==m,g=u2(n.label),x=o.values[n.id]??n.defaultValue??"",v=f_[n.reason],b=n.optional&&1===(t=new Set(n.targets.map(e=>{let{path:t}=e;return"headers"===t[0]?t[1]:void 0}))).size?[...t][0]:void 0,y=f?m&&!a?fZ(n,s,"${"+m+"}",!0):void 0:fZ(n,s,`‹${c("mcp.add.field.slot")}›`),j=e=>d({...o,values:{...o.values,[n.id]:e}}),k=e=>{let t={...o.references};void 0===e?delete t[n.id]:t[n.id]=e,d({...o,references:t})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)(cl,{label:g,children:f?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:g}),value:m,placeholder:l??"GITHUB_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>k(e.target.value)}):"select"===n.kind?(0,r.jsxs)("select",{className:"mcp-add-input","aria-label":g,value:x,...p,onChange:e=>j(e.target.value),children:[!n.options?.includes(x)&&(0,r.jsx)("option",{value:"",children:c("mcp.add.field.choose")}),(n.options??[]).map(e=>(0,r.jsx)("option",{value:e,children:u2(e)},e))]}):(0,r.jsx)("input",{className:"mcp-add-input",type:"password"===n.kind?"password":"text","aria-label":g,value:x,autoComplete:"off",placeholder:n.placeholder?u2(n.placeholder):void 0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>j(e.target.value)})}),a&&(0,r.jsx)("span",{id:u,className:"mcp-config-line is-error",children:fH(a,c,[n])}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:u2(n.description)}),v&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:c(v)}),f?(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:y?c("mcp.add.field.storedAsVariable",{value:y}):c("mcp.add.field.variableHint")}):(0,r.jsxs)(r.Fragment,{children:[y&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:c("mcp.add.field.storedAs",{value:y})}),n.optional&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:b?c("mcp.add.field.optionalHeader",{name:u2(b)}):c("mcp.add.field.optional")})]})]}),h&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:f,onChange:e=>k(e.target.checked?l??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("mcp.add.field.useVariable")})]})]})}function ga(e){let{label:t,draft:n,suggestedName:s,stored:o,problem:l,onDraftChange:a}=e,{t:d}=(0,tn.s)(),c=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=u2(t),m=e=>{let r={...n.secretReferences};void 0===e?delete r[t]:r[t]=e,a({...n,secretReferences:r})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)("span",{className:"mcp-config-lines",children:(0,r.jsxs)("span",{className:"mcp-config-line",children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:h})," ",d("mcp.add.secret.holds")]})}),(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:p,onChange:e=>m(e.target.checked?s??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(cl,{label:d("mcp.add.field.variableName",{field:h}),children:(0,r.jsx)("input",{className:"mcp-add-input","aria-label":d("mcp.add.field.variableName",{field:h}),value:u,placeholder:s??"API_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...l?{"aria-invalid":!0,"aria-describedby":c}:{},onChange:e=>m(e.target.value)})}),l&&(0,r.jsx)("span",{id:c,className:"mcp-config-line is-error",children:fH(l,d)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==o?d("mcp.add.secret.storedAs",{value:u2(o)}):d("mcp.add.field.variableHint"):d("mcp.add.secret.asPasted")})]})}let gd=new Set(["done","failed","cancelled","expired"]);function gc(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!gd.has(t))}let gu={"mcp-off":"mcp.signIn.blocked.mcp-off","project-untrusted":"mcp.signIn.blocked.project-untrusted","trust-unreadable":"mcp.signIn.blocked.trust-unreadable",invalid:"mcp.signIn.blocked.invalid","web-password":"mcp.test.blocked.web-password"},gp={"mcp-off":"mcp.signIn.blocked.mcp-off","project-untrusted":"mcp.signIn.blocked.project-untrusted","trust-unreadable":"mcp.signIn.blocked.trust-unreadable","server-invalid":"mcp.signIn.blocked.invalid","web-password":"mcp.test.blocked.web-password","entry-not-object":"mcp.signIn.refused.file","server-missing":"mcp.signIn.refused.file",unparsable:"mcp.signIn.refused.file","invalid-shape":"mcp.signIn.refused.file","link-dangling":"mcp.signIn.refused.file","link-outside":"mcp.signIn.refused.file","not-a-file":"mcp.signIn.refused.file","too-large":"mcp.signIn.refused.file","too-many-servers":"mcp.signIn.refused.file","invalid-request":"mcp.signIn.refused.invalid-request"},gh={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},gm={"connect-failed":"mcp.signIn.failed.connect-failed","queue-timed-out":"mcp.signIn.failed.queue-timed-out","sign-in-failed":"mcp.signIn.failed.sign-in-failed",internal:"mcp.signIn.failed.internal"};function gf(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,gd.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function gg(e){return"sign-in-unknown"===e.reason}async function gx(e,t,n,r){var i;let s,o;try{s=await n(e,{...t,cache:"no-store",signal:r})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{o=await s.json()}catch{return{ok:!1,error:{error:`HTTP ${s.status}`}}}return s.ok&&null!==(i=o)&&"object"==typeof i&&"string"==typeof i.flowId&&"string"==typeof i.phase&&"string"==typeof i.name&&("global"===i.scope||"project"===i.scope)&&"number"==typeof i.expiresInMs?{ok:!0,data:o}:{ok:!1,error:pL(o,s.status)}}function gv(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},o=t.method??"GET";return pz(r=>gx(e,t,n,r),()=>({ok:!1,error:{error:`${o} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,s)}function gb(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function gy(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"mcp.signIn.requestTimedOut";if(e.timedOut)return t(n);let r=e.reason?gp[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function gj(e){let{server:t,run:n,block:s,signOutBlock:o,controlsBusy:l,signingOut:a,onSignIn:d,onSignOut:c,onPaste:u,onCancel:p}=e,{t:h}=(0,tn.s)(),m=(0,i.useId)(),f=(0,i.useId)(),g=(0,i.useId)(),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=gc(n),y=(0,i.useRef)(b);if((0,i.useEffect)(()=>{let e=y.current;y.current=b,!e&&b?eB(document,v.current):e&&!b&&eB(document,x.current)},[b]),!t.usesOAuth)return void 0===t.authProvider&&t.headerNames.some(e=>"authorization"===e.toLowerCase())?null:(0,r.jsx)(cd,{label:h("mcp.detail.signIn"),children:void 0!==t.authProvider?h("mcp.signIn.provider",{provider:u2(t.authProvider)}):h("mcp.signIn.header")});let j=n?.flow,k=n?.starting===!0,w=void 0!==j&&(j.scope!==t.scope||j.name!==t.name),S=(t.oauthStateStored??t.signedIn)!==!1,C=k||a||void 0!==s,N=l||k||void 0!==o,E=j?.phase==="finishing";return(0,r.jsx)(cd,{label:h("mcp.detail.signIn"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:h(!0===t.signedIn?"mcp.signIn.signedIn":!1===t.signedIn?t.oauthStateStored?"mcp.signIn.registrationOnly":"mcp.signIn.notSignedIn":"mcp.signIn.unknown")}),j&&b&&w&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.shared",{name:u2(j.name)})}),j&&b&&("authorize"===j.phase?(0,r.jsx)(gk,{flow:j,pasting:n?.pasting===!0,pasteError:n?.pasteError,onPaste:e=>u(t,j.flowId,e)},j.flowId):(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(gh[j.phase]??"mcp.signIn.phase.connecting")})),j&&b&&E&&(0,r.jsx)("span",{id:g,className:"mcp-config-line is-dim",children:h("mcp.signIn.phase.noCancel")}),j&&!b&&!n?.gone&&(0,r.jsx)(gw,{flow:j,shared:w}),n?.gone&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-warning",children:h("mcp.signIn.gone")}),n?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.requestFailed")," ",gy(n.error,h)]}),b&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.cancelFailed")," ",gy(n.cancelError,h,"mcp.signIn.cancelTimedOut")]}),n?.signOutError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.signOutFailed")," ",gy(n.signOutError,h,"mcp.actionTimedOut")]}),n?.signedOut&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(n.signedOut.removed?"mcp.signIn.signedOutDone":"mcp.signIn.signedOutNothing")}),s&&(0,r.jsx)("span",{id:m,className:"mcp-config-line is-dim",children:h(gu[s])}),!s&&o&&S&&!b&&(0,r.jsx)("span",{id:f,className:"mcp-config-line is-dim",children:h(gu[o])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[b&&j?(0,r.jsx)(cj,{ref:v,size:"small",disabled:n?.cancelling===!0||E,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":E?g:void 0,onClick:()=>p(t,j.flowId),children:h(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(cj,{ref:x,size:"small",variant:"primary",disabled:C,"aria-busy":k||void 0,"aria-describedby":s?m:void 0,onClick:()=>d(t),children:h(k?"mcp.signIn.starting":"mcp.signIn.button")}),S&&!b&&(0,r.jsx)(cj,{size:"small",disabled:N,"aria-busy":a||void 0,"aria-describedby":o?s?m:f:void 0,onClick:()=>c(t),children:h(a?"mcp.signIn.signingOut":"mcp.signIn.signOut")})]}),!s&&!b&&S&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.replaces")}),S&&!o&&!b&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.signOutExplain")})]})})}function gk(e){let{flow:t,pasting:n,pasteError:s,onPaste:o}=e,{t:l}=(0,tn.s)(),[a,d]=(0,i.useState)(""),c=(0,i.useRef)(null),u=(0,i.useRef)(n);(0,i.useEffect)(()=>{let e=u.current;u.current=n,e&&!n&&eB(document,c.current)},[n]);let p=function(e){if(void 0!==e)try{let t=new URL(e);return"https:"===t.protocol||"http:"===t.protocol?t.href:void 0}catch{return}}(t.authorizationUrl);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cP,{message:l("mcp.signIn.authorize.message"),hint:p?(0,r.jsxs)(r.Fragment,{children:[l("mcp.signIn.authorize.link")," ",(0,r.jsx)("a",{href:p,target:"_blank",rel:"noopener noreferrer",children:u2(p)})]}):(0,r.jsxs)(r.Fragment,{children:[l("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(t.authorizationUrl??"")})]}),value:a,placeholder:l("mcp.signIn.paste.placeholder"),inputLabel:l("mcp.signIn.paste.label"),submitLabel:l(n?"mcp.signIn.paste.checking":"mcp.signIn.paste.submit"),disabled:n,plainEnterSubmits:!1,inputRef:c,onValueChange:d,onSubmit:()=>o(a)}),s&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[l("mcp.signIn.paste.refused")," ",gy(s,l,"mcp.signIn.paste.timedOut"),"redirect-denied"===s.reason&&s.error&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(s.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.redirect",{url:u2(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.signIn.authorize.wait")})]})}function gw(e){let{flow:t,shared:n}=e,{t:i}=(0,tn.s)(),s=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];switch(e.phase){case"done":{if(t)return e.alreadySignedIn?"mcp.signIn.shared.already":"mcp.signIn.shared.done";if(e.alreadySignedIn)return"mcp.signIn.done.already";let n=e.result;if(n&&"needs-auth"===n.state)return"mcp.signIn.done.needsAuthAfter";if(n&&"failed"===n.state)return"mcp.signIn.done.failedAfter";if(!n)return"mcp.signIn.done.notConnected";return e.refreshed?"mcp.signIn.done.refreshed":"mcp.signIn.done.signedIn"}case"failed":if(t&&"connect-failed"===e.failure)return"mcp.signIn.shared.connect-failed";return gm[e.failure??"internal"];case"cancelled":return"mcp.signIn.cancelled";case"expired":return"mcp.signIn.expired";default:return}}(t,n);if(!s)return null;let o=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return"done"===e.phase?!t&&e.result&&"connected"!==e.result.state?"warning":"on":"failed"===e.phase?"error":"expired"===e.phase?"warning":"off"}(t,n);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{role:"status",className:"error"===o?"mcp-config-line is-error":"warning"===o?"mcp-config-line is-warning":"mcp-config-line",children:i(s,{name:u2(t.name)})}),t.error&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.test.error")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(t.error)})]})]})}function gS(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function gC(e){return u2(eS(e))}function gN(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:gC(r.path)}):t(n)}function gE(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function gI(e,t){return e.timedOut?t("mcp.actionTimedOut"):gE(e,t)}function g$(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function gT(e){let{cwd:t,onClose:n,embedded:s=!1,trust:o,onTrustProject:l,onProjectTrustChanged:a}=e,[d,c]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(()=>dA("mcp",t)),[f,g]=(0,i.useState)({saving:!1,error:null}),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[E,I]=(0,i.useState)({}),$=(0,i.useRef)(0),T=(0,i.useRef)(null),M=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(new Map),[L,z]=(0,i.useState)({}),P=(0,i.useRef)(L);P.current=L;let[W,O]=(0,i.useState)(0),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(fO),_=(0,i.useRef)(B);_.current=B;let[U,K]=(0,i.useState)(null),[q,V]=(0,i.useState)(null),Z=(0,i.useRef)(!0),J=(0,i.useRef)(d);J.current=d;let G=(0,i.useCallback)(async()=>{let e=++$.current;T.current?.abort();let n=new AbortController;T.current=n,p(!0);let r=await pD(t,void 0,n.signal);if(e===$.current){if(p(!1),!r.ok)return void c({state:"failed",error:r.error});c({state:"loaded",data:r.data,...r.projectError?{projectError:r.projectError}:{}}),m(e=>pC(pw(r.data,!!t),e))}},[t]),Y=uh(o);(0,i.useEffect)(()=>(G(),()=>{$.current+=1,T.current?.abort()}),[G,Y]);let X=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,g({saving:!0,error:null,target:"preference"});let n=await p_(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"preference"}),n.ok&&c(e=>{var t,r;let i;return"loaded"===e.state?{...e,data:(t=e.data,r=n.preference,i={...t.codemode,preference:r},delete i.preferenceError,{...t,codemode:i})}:e}),G())},[G]),Q=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,g({saving:!0,error:null,target:"mode"});let n=await pU(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"mode"}),n.ok&&c(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.mode;if(!n)return e;let r={settingsPath:n.settingsPath,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,mode:r}}}(e.data,n.mode)}:e),G())},[G]),ee=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,g({saving:!0,error:null,target:"inlineBudget"});let n=await pK(e,void 0,t.signal);M.current===t&&(M.current=null,g({saving:!1,error:n.ok?null:n.error,target:"inlineBudget"}),n.ok&&c(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.inlineBudget;if(!n)return e;let r={settingsPath:n.settingsPath,default:n.default,max:n.max,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,inlineBudget:r}}}(e.data,n.inlineBudget)}:e),G())},[G]);(0,i.useEffect)(()=>{let e=A.current;return Z.current=!0,()=>{Z.current=!1,M.current?.abort(),M.current=null,R.current?.abort(),R.current=null,e.clear()}},[]);let et=(0,i.useCallback)(async e=>{let n=pi(e);if(A.current.has(n))return;let r={};A.current.set(n,r),I(e=>({...e,[n]:{...e[n],running:!0,startedAt:Date.now(),error:void 0,queueTimedOut:void 0,configKey:void 0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,o=await p6({scope:e.scope,name:e.name},s);if(A.current.get(n)!==r)return;A.current.delete(n),I(t=>({...t,[n]:function(e,t,n){let r=e?.signedOutAt,i={...e?.startedAt!==void 0?{startedAt:e.startedAt}:{},...void 0!==r?{signedOutAt:r}:{}};if(void 0!==r&&(e?.startedAt??0)<=r)return{running:!1,...i};let s=e?.response?{response:e.response}:{};return t.ok?t.data.result.queueTimedOut?{running:!1,...i,...s,queueTimedOut:!0,configKey:t.data.configKey}:{running:!1,...i,response:t.data}:{running:!1,...i,...s,error:t.error,...void 0!==n?{configKey:n}:{}}}(t[n],o,e.configKey)}));let l=J.current,a="loaded"===l.state?l.data.servers.find(e=>pi(e)===n):void 0;(o.ok?a?.configKey===o.data.configKey:void 0===o.error.reason||o.error.timedOut)||G()},[t,G]),en=(0,i.useCallback)((e,n)=>{$.current+=1,T.current?.abort(),p(!1),c(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),m(r=>pC(pw(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=pi(e),r=P.current[n];if(r?.starting||gc(r))return;z(e=>({...e,[n]:{starting:!0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,o=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3;return gv("/api/mcp/sign-in",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:e.scope,name:e.name,...t?{cwd:t}:{}})},n,r,i,{abortAtDeadline:!1})}({scope:e.scope,name:e.name},s);Z.current&&(z(e=>({...e,[n]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return e.ok?gf({},e.data,t):{error:e.error}}(o)})),o.ok||void 0===o.error.reason||o.error.timedOut||G())},[t,G]),ei=(0,i.useCallback)(async(e,t,n)=>{let r=pi(e);z(e=>e[r]?.flow?.flowId===t?{...e,[r]:{...e[r],pasting:!0,pasteError:void 0}}:e);let i=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3;return gv(gb(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);Z.current&&z(e=>{let n=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,pasting:!1,version:(e.version??0)+1};return n.ok?{...gf(i,n.data,r),pasteError:void 0}:gg(n.error)?{...i,gone:!0}:{...i,pasteError:n.error}}(e[r],t,i);return void 0===n||n===e[r]?e:{...e,[r]:n}})},[]),es=(0,i.useCallback)(async(e,t)=>{let n=pi(e);z(e=>e[n]?.flow?.flowId===t?{...e,[n]:{...e[n],cancelling:!0}}:e);let r=await function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return gv(gb(e),{method:"DELETE"},t,n,r)}(t);Z.current&&z(e=>{let i=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,cancelling:!1,cancelError:void 0,version:(e.version??0)+1};return n.ok?gf(i,n.data,r):gg(n.error)?{...i,gone:!0}:{...i,cancelError:n.error}}(e[n],t,r);return void 0===i||i===e[n]?e:{...e,[n]:i}})},[]),eo=Object.entries(L).flatMap(e=>{let[t,n]=e;return gc(n)&&n.flow?[`${t}\x01${n.flow.flowId}`]:[]}).join("\x02");(0,i.useEffect)(()=>{if(!eo)return;let e=new AbortController,t=setTimeout(async()=>{for(let t of eo.split("\x02")){let[n,r]=t.split("\x01"),i=P.current[n]?.version??0,s=await function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return gv(gb(e),{},t,n,r)}(r,void 0,e.signal);if(e.signal.aborted)return;z(e=>{let t=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now(),i=arguments.length>4?arguments[4]:void 0;return e?.flow&&e.flow.flowId===t&&(void 0===i||(e.version??0)===i)?n.ok?gf(e,n.data,r):gg(n.error)||void 0!==e.deadlineAt&&r>e.deadlineAt+5e3?{...e,gone:!0}:e:e}(e[n],r,s,Date.now(),i);return void 0===t||t===e[n]?e:{...e,[n]:t}})}O(e=>e+1)},1e3);return()=>{clearTimeout(t),e.abort()}},[eo,W]);let el=(0,i.useRef)(L);(0,i.useEffect)(()=>{let e=el.current;el.current=L,Object.keys(L).some(t=>{var n,r;return n=e[t],r=L[t],gc(n)&&!gc(r)})&&G()},[L,G]);let ea=(0,i.useCallback)(async(e,n,r)=>{R.current?.abort();let i=new AbortController;R.current=i,v(n);let s=J.current,o="loaded"===s.state&&s.data.project?t:null,l=await pX(e,o,void 0,i.signal);if(R.current===i)return R.current=null,v(null),l.ok?en(l.data,r?.(l.data)):G(),l},[en,t,G]),ed=(0,i.useCallback)(async(e,t)=>{let n=pi(e),r=g$();y(null),k(null);let i=await ea({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),ec=(0,i.useCallback)(async(e,t)=>{let n=pi(e),r=g$();y(null),k(null);let i=await ea({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),eu=(0,i.useCallback)(async(e,t)=>{let n=pi(e),r=g$();y(null),k(null);let i=await ea({action:"set-exposure",scope:e.scope,name:e.name,exposure:t},`exposure:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),ep=(0,i.useCallback)(async e=>{let t=pi(e),n=g$();y(null),k(null);let r=await ea({action:"remove",scope:e.scope,name:e.name},`remove:${t}`);if(!r)return;if(!r.ok){y({key:t,failure:r.error}),N({control:n});return}let i=r.data.undo;i&&S({...i,undoing:!1})},[ea]),eh=(0,i.useCallback)(async()=>{if(!w)return;let e=g$();y(null),k(null),S({...w,undoing:!0,error:void 0});let t=await ea({action:"undo",token:w.token},"undo",e=>e.restored?pi(e.restored):void 0);t&&(S(e=>e?.token!==w.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||N({control:e}))},[ea,w]),em=(0,i.useCallback)(async e=>{let t=pi(e),n=g$();y(null),k(null),z(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await ea({action:"sign-out",scope:e.scope,name:e.name},`sign-out:${t}`);if(r){if(z(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();I(n=>{let r=function(e,t){if(e)return{running:e.running,...void 0!==e.startedAt?{startedAt:e.startedAt}:{},signedOutAt:t}}(n[t],e);return r?{...n,[t]:r}:n})}N({control:n})}},[ea]),ef=(0,i.useCallback)(async e=>{let n=g$(),r=_.current;y(null),k(null),K(null);let i=await ea(e,"add",e=>e.added?pi(e.added):void 0);if(!i)return;let s=_.current!==r;if(!i.ok){s||K(i.error),i.error.trust&&t&&a?.(t,i.error.trust),N({control:n});return}let{added:o,trust:l,trustedFolder:d}=i.data;if(D(!1),s||H(fO),N({control:null,toSelectedRow:!0}),!o)return;V({...o,key:pi(o),...d&&t?{trustedFolder:t}:{}}),l&&t&&a?.(t,l);let c=i.data.servers.find(e=>pi(e)===pi(o));c&&!p0(c,i.data)&&et(c)},[t,a,ea,et]),eg=w?.token,ex=w?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===eg||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===eg?null:e),ex);return()=>clearTimeout(e)},[eg,ex]);let ev=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:up(t,n,e=>e.enabled).filter(n?pG:pJ),keptOff:n?t.filter(e=>!e.enabled&&pJ(e)&&!pG(e)).length:0},s=g$();if(y(null),k(i>0?{scope:e,keptOff:i,failures:[],total:0}:null),0===r.length)return;let o=await ea({action:"set-enabled",enabled:n,servers:r.map(e=>{let{scope:t,name:n}=e;return{scope:t,name:n}})},`group:${e}`);if(!o)return;if(N({control:s}),!o.ok)return void k({scope:e,keptOff:i,failures:[],total:r.length,error:o.error});let l=o.data.results??[],a=l.filter(e=>void 0!==e.reason).map(e=>({name:e.name,failure:{error:e.error??"",reason:e.reason}}));k(a.length>0||i>0?{scope:e,keptOff:i,failures:a,total:l.length}:null)},[ea]);return(0,i.useEffect)(()=>{h&&dL("mcp",h,t)},[t,h]),(0,r.jsx)(gM,{cwd:t,load:d,selected:h,refreshing:u,embedded:s,codemodeSave:f,busy:x,actionError:b,groupStatus:j,undo:w,focusBack:C,tests:E,signIns:L,adding:F,addDraft:B,addFailure:U,added:q,onAddOpen:()=>{D(!0),V(null),y(null)},onAddDraftChange:e=>{_.current=e,H(e),K(null)},onAddSubmit:e=>void ef(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void em(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void es(e,t),onSelect:e=>{m(e),y(null),D(!1),V(t=>t?.key===e?t:null)},onRefresh:()=>void G(),onCodemodeChange:e=>void X(e),onCodemodeModeChange:e=>void Q(e),onCodemodeInlineBudgetSave:e=>void ee(e),onServerSwitch:(e,t)=>void ed(e,t),onServerSwitchInProject:(e,t)=>void ec(e,t),onExposureChange:(e,t)=>void eu(e,t),onGroupSwitch:(e,t,n)=>void ev(e,t,n),onRemove:e=>void ep(e),onUndo:()=>void eh(),onTrustProject:l,onClose:n})}function gM(e){var t,n,s,o;let l,a,d,{cwd:c,load:u,selected:p,refreshing:h,embedded:m,codemodeSave:f={saving:!1,error:null},busy:g=null,actionError:x=null,groupStatus:v=null,undo:b=null,focusBack:y=null,tests:j={},signIns:k={},adding:w=!1,addDraft:S=fO,addFailure:C=null,added:N=null,onAddOpen:E=()=>{},onAddDraftChange:I=()=>{},onAddSubmit:$=()=>{},onSelect:T,onRefresh:M,onCodemodeChange:R,onCodemodeModeChange:A=()=>{},onCodemodeInlineBudgetSave:L=()=>{},onServerSwitch:z=()=>{},onServerSwitchInProject:P=()=>{},onExposureChange:W=()=>{},onGroupSwitch:O=()=>{},onRemove:F=()=>{},onUndo:D=()=>{},onTest:B=()=>{},onSignIn:H=()=>{},onSignOut:_=()=>{},onSignInPaste:U=()=>{},onSignInCancel:K=()=>{},onTrustProject:q,onClose:V}=e,{t:Z}=(0,tn.s)(),J=(0,i.useId)(),G=(0,i.useId)(),Y="loaded"===u.state?(t=u.data,l=!1,a=t.servers.map(e=>{var t;let n=j[pi(e)]?.response;if(!n||n.configKey!==e.configKey||e.status&&("test"===(t=e.status).origin?t.testedAt:t.closedAt??t.updatedAt)>=n.result.testedAt)return e;l=!0;let r={...n.result,origin:"test"};return{...e,status:r}}),l?{...t,servers:a}:t):void 0,X=Y?pw(Y,!!c):[],Q=Y?{mcpAvailable:Y.mcp.available,projectServersLoad:ps(Y.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>pi(e)===p),en=N?ee.find(e=>pi(e)===N.key):void 0,er=Y?function(e){if(!e.available)return"builtin-disabled"===e.reason?e.settingsPath?{key:"mcp.unavailable.builtin-disabled",params:{path:e.settingsPath}}:{key:"mcp.unavailable.builtin-disabled-unknown"}:{key:"operator-disabled"===e.reason?"mcp.unavailable.operator-disabled":"mcp.unavailable.internals-unavailable"}}(Y.mcp):void 0,ei=er?void 0:Y?.hostInactive,es=Y?.files.find(e=>"project"===e.scope),eo=Y?function(e,t){if(!e||!t||!t.exists&&0===t.problems.length)return;let{trust:n}=e;return n?n.requiresTrust||!1===n.decision?!0===n.decision?n.inherited&&n.decisionPath?{kind:"inherited",key:"mcp.trust.trustedThrough",params:{path:n.decisionPath}}:void 0:!1===n.decision&&n.inherited&&n.decisionPath?{kind:"untrusted",key:"mcp.trust.untrustedThrough",params:{path:n.decisionPath}}:{kind:"untrusted",key:"mcp.trust.untrusted"}:void 0:{kind:"untrusted",key:"mcp.trust.unreadable"}}(Y.project,es):void 0,el=q&&pN(Y?.project)?q:void 0,ea=eo?.kind==="untrusted"&&void 0!==el,ed=(0,i.useRef)(null),ec=(0,i.useRef)(null),eu=(0,i.useRef)(ea);(0,i.useEffect)(()=>{let e=eu.current;eu.current=ea,e&&!ea&&eB(document,ed.current??ec.current)},[ea]);let ep=(0,i.useRef)(null),eh=b?.token,em=(0,i.useRef)(eh);(0,i.useEffect)(()=>{let e=em.current;em.current=eh,void 0!==eh&&eh!==e?eB(document,ep.current):void 0!==e&&void 0===eh&&eB(document,ed.current??ec.current)},[eh]);let ef=Y?[...Y.files].sort((e,t)=>e.scope===t.scope?0:"global"===e.scope?-1:1).flatMap(e=>e.problems.map(t=>({file:e,problem:t}))):[],eg=pS(ee),ex=Y?.files.find(e=>"global"===e.scope),ev=Y?function(e){let t=e.files.find(e=>"project"===e.scope);if(t?.autoEnableCodemode!==void 0&&ps(e.project))return t.autoEnableCodemode?{value:!0,path:t.path}:{value:!1,path:t.path};let n=e.files.find(e=>"global"===e.scope);return n?.autoEnableCodemode!==void 0?n.autoEnableCodemode?{value:!0,path:n.path}:{value:!1,path:n.path}:{value:!0}}(Y):void 0,eb=Y?(n=ee.length,s=Y.files,n>0?"mcp.selectItem":s.some(e=>e.problems.some(pk))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ey=null!==g||h||f.saving,ej=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ey&&ej.current!==y)if(ej.current=y,y.toSelectedRow)eB(document,ed.current??ec.current);else{var e,t,n;e=document,t=y.control,n=ed.current??ec.current,t&&eB(e,t.isConnected&&!t.disabled?t:n)}},[y,ey]);let ek=e=>Y?pV(e,Y):void 0,ew=!!Y&&pq(Y.mcp),eC=X.find(e=>"project"===e.scope)?.servers??[],eN=ek("project"),eE=eo?.kind==="untrusted"?[gN(eo,Z),eN&&"mcp-off"!==eN&&eC.length>0?Z(pZ[eN]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(d2,{embedded:m,title:Z("settings.mcp"),subtitle:c?eS(c):void 0,closeLabel:Z("i18n.close"),onClose:V,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(cf,{id:J,children:[gN(er,Z),ew&&(0,r.jsxs)(r.Fragment,{children:[" ",Z(pZ["mcp-off"])]}),Y&&!Y.mcp.available&&Y.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(Y.mcp.detail)})]})]}),ei&&(0,r.jsx)(cf,{children:Z("mcp.hostInactive",{path:gC(ei.cwd),owner:gC(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(cf,{children:Z("mcp.projectNotListed",{reason:gE(u.projectError,Z)})}),eo?.kind==="untrusted"&&(0,r.jsx)(cg,{id:G,message:eE,trustLabel:Z("mcp.trust.trustButton"),onTrust:el}),eo?.kind==="inherited"&&(0,r.jsx)(cf,{children:gN(eo,Z)}),b&&(0,r.jsxs)(cf,{action:b.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(cj,{ref:ep,size:"small",onClick:D,disabled:b.undoing||ey,children:b.undoing?Z("mcp.undoing"):Z("mcp.undo")}),children:[Z("mcp.removed",{name:u2(b.name),path:gC(b.path)}),b.error&&(0,r.jsxs)(r.Fragment,{children:[" ",Z("mcp.undoFailed")," ",gI(b.error,Z)]})]}),N&&Y&&en&&(0,r.jsx)(gR,{added:N,cwd:c,server:en,testing:j[N.key]?.running===!0,signIn:k[N.key],signingOut:g===`sign-out:${N.key}`,signInBlock:en?p0(en,Y):void 0,onSignIn:H})]}),(0,r.jsxs)(d4,{children:[(0,r.jsxs)(d8,{children:[(0,r.jsx)(d3,{children:"loading"===u.state?(0,r.jsx)("div",{className:"config-sidebar-message",children:Z("i18n.loading")}):"failed"===u.state?(0,r.jsxs)("div",{role:"alert",className:"config-sidebar-message is-error",children:[Z("mcp.loadFailed")," ",gE(u.error,Z)]}):Y&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(gA,{codemode:Y.codemode,active:!w&&p===pr,rowRef:ed,onSelect:T})}),X.map(e=>{let t=ek(e.scope);return(0,r.jsx)(gL,{group:e,context:Q,selected:w?null:p,selectedRowRef:ed,block:t,blockNoticeId:"mcp-off"===t?er?J:void 0:t&&eo?.kind==="untrusted"?G:void 0,busy:g,controlsBusy:ey,status:v?.scope===e.scope?v:null,onSelect:T,onGroupSwitch:O},e.scope)})]}):null}),Y&&(0,r.jsx)(cw,{ref:ec,active:w,onClick:E,children:Z("mcp.add.action")})]}),(0,r.jsx)(cv,{children:(0,r.jsx)(ct,{className:"is-fill",children:Y&&Q&&ev&&eb?w?(0,r.jsx)(gs,{data:Y,cwd:c,draft:S,busy:"add"===g,controlsBusy:ey,failure:C,onDraftChange:I,onSubmit:$,onTrustProject:el}):p===pr?(0,r.jsx)(gq,{codemode:Y.codemode,autoEnable:ev,save:f,serverBusy:null!==g,onChange:R,onModeChange:A,onInlineBudgetSave:L}):et?(0,r.jsx)(gW,{server:et,context:Q,codemode:Y.codemode,toolSearchDisabled:Y.toolSearchDisabled,autoEnable:ev,block:ek(et.scope),inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!ps(t.project))return;let n=t.files.find(e=>"project"===e.scope);if(!n||n.problems.some(e=>"auto-enable-codemode-invalid"!==e.reason))return;let r=t.servers.find(t=>"project"===t.scope&&t.name===e.name);return r?r.override?{kind:"override",key:pi(r),keys:r.override.keys,applies:!0===e.overriddenByProject}:void 0:{kind:"switch"}}(et,Y),inProjectBlock:ek("project"),savedWhileOff:!Y.mcp.available&&!ew,busy:g,controlsBusy:ey,actionError:x?.key===pi(et)?x.failure:null,test:(o=j[pi(et)],o&&void 0!==o.configKey&&o.configKey!==et.configKey?{running:o.running,...o.response?{response:o.response}:{}}:o),testBlock:p0(et,Y),signIn:k[pi(et)],signInBlock:p0(et,Y),signOutBlock:(d=pV(et.scope,Y))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:z,onSwitchInProject:P,onShowServer:e=>{T(e),requestAnimationFrame(()=>eB(document,ed.current??ec.current))},onExposureChange:W,onRemove:F,onTest:B,onSignIn:H,onSignOut:_,onSignInPaste:U,onSignInCancel:K},pi(et)):(0,r.jsx)(cx,{children:"mcp.empty"===eb?Z(eb,{globalPath:gC(ex?.path??"~/.pi/agent/mcp.json")}):Z(eb)}):null})})]}),(0,r.jsxs)(cb,{status:ef.length>0?(0,r.jsx)(cy,{tone:ef.some(e=>{let{problem:t}=e;return pk(t)})?"error":"warning",summary:1===ef.length?Z("mcp.footer.fileProblem"):Z("mcp.footer.fileProblems",{count:ef.length}),details:ef.map(e=>{let{file:t,problem:n}=e,i=pn(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:gC(t.path)})," ",Z(`mcp.fileProblem.${n.reason}`),i&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:i})]})]})})}):(0,r.jsx)(cy,{summary:eg.total>0?Z("mcp.serverCount",{enabled:eg.enabled,total:eg.total}):""}),children:[!m&&(0,r.jsx)(cj,{onClick:V,children:Z("i18n.close")}),(0,r.jsx)(cj,{variant:"secondary",onClick:M,disabled:ey,children:Z("i18n.refresh")})]})]})}function gR(e){let{added:t,cwd:n,server:i,testing:s,signIn:o,signingOut:l,signInBlock:a,onSignIn:d}=e,{t:c}=(0,tn.s)(),u=u2(t.name),p="project"===t.scope&&n?u2(eC(t.path,n)):gC(t.path),h=i.status,m=!s&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,f=o?.starting===!0||gc(o);return(0,r.jsxs)(cf,{action:!m||f||l||a?void 0:(0,r.jsx)(cj,{size:"small",variant:"primary",onClick:()=>d(i),children:c("mcp.signIn.button")}),children:[void 0===t.trustedFolder?c("mcp.add.added",{name:u,path:p}):t.trustedFolder===n?c("mcp.add.addedTrustedHere",{name:u,path:p}):c("mcp.add.addedTrusted",{name:u,path:p,folder:gC(t.trustedFolder)}),s&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.testing")]}),m&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.needsSignIn")]})]})}function gA(e){let{codemode:t,active:n,rowRef:i,onSelect:s}=e,{t:o}=(0,tn.s)(),l=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",a=o(pM[l]);return(0,r.jsxs)(d7,{ref:n?i:void 0,active:n,"aria-label":o("mcp.codemode.rowLabel",{state:a}),onClick:()=>s(pr),children:[(0,r.jsx)(cS,{...pm(pR(l))}),(0,r.jsx)(ce,{className:"is-grow",children:o("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${pR(l)}`,children:a})]})}function gL(e){var t;let n,i,{group:s,context:o,selected:l,selectedRowRef:a,block:d,blockNoticeId:c,busy:u,controlsBusy:p,status:h,onSelect:m,onGroupSwitch:f}=e,{t:g}=(0,tn.s)(),{enabled:x,total:v}=pS(s.servers),b=(t=s.servers).some(e=>e.enabled&&pJ(e))&&t.every(e=>e.enabled||!pG(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(pk)?"mcp.group.fileProblem":"mcp.group.empty":"mcp.group.notListed"}(s),j=h?(n=h.keptOff>0?g("mcp.groupKeptOff",{count:h.keptOff}):void 0,i=h.error?`${g("mcp.actionFailed")} ${gI(h.error,g)}`:h.failures.length>0?[g("mcp.bulkFailed",{count:h.failures.length,total:h.total}),...h.failures.map(e=>{let{name:t,failure:n}=e;return`${u2(t)}: ${gI(n,g)}`})].join("\n"):void 0,{...n?{note:n}:{},...i?{error:i}:{}}):void 0;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(d5,{aside:v>0?(0,r.jsx)(d6,{enabled:x,total:v,checked:b,disabled:p||void 0!==d,loading:u===`group:${s.scope}`,describedBy:d?c:void 0,label:g(b?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:gS(s.scope,g)}),onChange:e=>f(s.scope,s.servers,e)}):void 0,children:gS(s.scope,g)}),j&&(0,r.jsx)(d9,{note:j.note,error:j.error}),y&&(0,r.jsx)("div",{className:"mcp-sidebar-group-empty",children:g(y)}),s.servers.map(e=>{let t=pi(e),n=pl(e,o),i=ph(n),s=pp[n],d=u2(e.name);return(0,r.jsxs)(d7,{ref:l===t?a:void 0,active:l===t,"aria-label":g("mcp.rowLabel",{name:d,state:g(pc(n,e.status))}),onClick:()=>m(t),children:[(0,r.jsx)(cS,{...pm(i)}),(0,r.jsx)(ce,{className:`is-grow${"on"===i?"":" is-muted"}`,children:d}),s&&(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${i}`,children:g(s)})]},t)})]})}function gz(e){let{fields:t}=e,{t:n}=(0,tn.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=u9(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function gP(e){let{names:t}=e;return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(e)},e))})}function gW(e){let{server:t,context:n,codemode:s,toolSearchDisabled:o,autoEnable:l,block:a,inProject:d,inProjectBlock:c,savedWhileOff:u,busy:p,controlsBusy:h,actionError:m,test:f,testBlock:g,signIn:x,signInBlock:v,signOutBlock:b,onSwitch:y,onSwitchInProject:j,onShowServer:k,onExposureChange:w,onRemove:S,onTest:C,onSignIn:N,onSignOut:E,onSignInPaste:I,onSignInCancel:$}=e,{t:T}=(0,tn.s)(),M=(0,i.useId)(),R=(0,i.useId)(),A=pl(t,n),L=u5(t),z=t.status,P=z?.origin==="test"&&"connected"===z.state&&z.toolCount>0?z:void 0,W=void 0===t.invalidError,O="http"===t.transport||void 0===t.transport&&void 0!==t.url,F=!O&&("stdio"===t.transport||void 0!==t.command),D=t.exposure?function(e,t,n){if("codemode"===e){var r;return r=t.codemode,"unavailable"===r.sandbox.state?{key:"mcp.exposure.sandboxUnavailable"}:r.builtinDisabled?{key:"mcp.exposure.builtinDisabled"}:n.value||"always"===pE(r)?void 0:{key:"mcp.exposure.autoEnableOff",params:{path:n.path}}}if("deferred"!==e||!t.toolSearchDisabled)return;let i=t.toolSearchDisabled.settingsPath;return i?{key:"mcp.exposure.toolSearchDisabled",params:{path:i}}:{key:"mcp.exposure.toolSearchDisabledUnknown"}}(t.exposure,{codemode:s,toolSearchDisabled:o},l):void 0,B=(0,i.useId)(),H=(0,i.useId)(),_=pi(t),U=u2(t.name),K=!t.enabled&&void 0!==t.webPasswordField,q=!0===t.notAnObject,V=a?T(`mcp.reason.${a}`):q?T("mcp.reason.entry-not-object"):K?T("mcp.reason.web-password"):u?T("mcp.write.savedWhileOff"):void 0;return(0,r.jsxs)(ct,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(cn,{children:[(0,r.jsxs)(cr,{children:[(0,r.jsx)(cc,{scope:t.scope,children:gS(t.scope,T)}),(0,r.jsx)(cs,{children:U})]}),(0,r.jsxs)(ci,{children:[(0,r.jsx)(gU,{server:t,test:f,testBlock:g,describedBy:R,onTest:C}),(0,r.jsx)(cj,{variant:"danger",size:"small",disabled:h||void 0!==a,"aria-describedby":a?M:void 0,onClick:()=>S(t),children:p===`remove:${_}`?T("i18n.removing"):T("i18n.remove")}),(0,r.jsx)(ck,{checked:t.enabled,disabled:h||void 0!==a||q||K,loading:p===`switch:${_}`,describedBy:V?M:void 0,label:T(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:U}),onChange:e=>y(t,e)})]})]}),V&&(0,r.jsx)("div",{id:M,className:"config-detail-heading-note",children:V})]}),m&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[T("mcp.actionFailed")," ",gI(m,T)]}),(0,r.jsxs)(ca,{children:[(0,r.jsx)(gK,{server:t,state:A,test:f,testBlock:g,testBlockId:R}),void 0!==t.description&&(0,r.jsx)(cd,{label:T("mcp.detail.description"),tone:"plain",children:u2(t.description)}),void 0!==L?(0,r.jsx)(cd,{label:O?T("mcp.detail.url"):T("mcp.detail.command"),tone:"plain",mono:!0,className:"mcp-config-code",children:L}):t.transport&&(0,r.jsx)(cd,{label:T("mcp.detail.transport"),children:T(`mcp.transport.${t.transport}`)}),F&&void 0!==t.cwd&&(0,r.jsx)(cd,{label:T("mcp.detail.cwd"),mono:!0,className:"mcp-config-code",children:u2(t.cwd)}),F&&t.envNames.length>0&&(0,r.jsx)(cd,{label:T("mcp.detail.env"),children:(0,r.jsx)(gP,{names:t.envNames})}),O&&t.headerNames.length>0&&(0,r.jsx)(cd,{label:T("mcp.detail.headers"),children:(0,r.jsx)(gP,{names:t.headerNames})}),W&&t.commandFields.length>0&&(0,r.jsx)(cd,{label:T("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:T("mcp.server.commandFields")}),(0,r.jsx)(gz,{fields:t.commandFields})]})}),W&&t.variableReferences.length>0&&(0,r.jsx)(cd,{label:T("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:T(u7(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:pt(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=u9(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:T("mcp.server.variableIn",{variable:t,field:T(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),O&&W&&(0,r.jsx)(gj,{server:t,run:x,block:v,signOutBlock:b,controlsBusy:h,signingOut:p===`sign-out:${_}`,onSignIn:N,onSignOut:E,onPaste:I,onCancel:$}),(t.exposure||P)&&(0,r.jsx)(cd,{label:T("mcp.detail.exposure"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[t.exposure&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-exposure-choice",children:[(0,r.jsx)("select",{className:"mcp-add-input mcp-exposure-select","aria-label":T("mcp.exposure.label",{name:U}),"aria-describedby":[B,a?M:null].filter(Boolean).join(" "),value:t.exposure,disabled:h||void 0!==a,onChange:e=>{let n=e.target.value;n!==t.exposure&&w(t,n)},children:py.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?T("mcp.exposure.optionDefault",{label:T(pj[e])}):T(pj[e])},e))}),p===`exposure:${_}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:T("i18n.saving")})]}),(0,r.jsx)("span",{id:B,className:"mcp-config-line",children:T(pb[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:T("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),D&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:gN(D,T)})]}),P&&(0,r.jsx)(g_,{status:P,serverExposure:t.exposure})]})}),d&&(0,r.jsx)(cd,{label:T("mcp.detail.inProject"),tone:"plain",children:(0,r.jsx)("span",{className:"mcp-config-lines",children:"override"===d.kind?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line",children:d.applies?T("mcp.inProject.overridden",{keys:d.keys.join(", ")}):T("mcp.inProject.refused")}),(0,r.jsx)("span",{children:(0,r.jsx)(cj,{size:"small",onClick:()=>k(d.key),children:T("mcp.inProject.show")})})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(0,r.jsx)(cj,{size:"small",disabled:h||void 0!==c||K,"aria-describedby":[H,c||K?M:null].filter(Boolean).join(" "),onClick:()=>j(t,!t.enabled),children:p===`in-project:${_}`?T("i18n.saving"):T(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,r.jsx)("span",{id:H,className:"mcp-config-line is-dim",children:T("mcp.inProject.saved")})]})})}),(0,r.jsx)(cd,{label:T("mcp.detail.file"),tone:"dim",mono:!0,className:"mcp-config-code",children:gC(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[u6(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.hiddenCharacters")}),!t.validated&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.replacesGlobal")}),t.override&&(0,r.jsx)("p",{className:"mcp-config-line",children:gN(pe(t.override.keys),T)}),t.shadowedByProject&&"replaced"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.overriddenByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:T("mcp.server.masked")})]})]})}function gO(e){let{error:t,stderr:n}=e,{t:i}=(0,tn.s)();return(0,r.jsxs)(r.Fragment,{children:[t&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.test.error")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(t)})]}),n&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.stderr")}),(0,r.jsx)("pre",{className:"mcp-test-output",children:n.split(/\r?\n/).map(u2).join("\n")})]})]})}function gF(e){let{status:t,showState:n,entryCwd:i}=e;return"session"===t.origin?(0,r.jsx)(gH,{status:t,showState:n}):(0,r.jsx)(gB,{status:t,showState:n,entryCwd:i})}function gD(e){let{view:t}=e,{t:n}=(0,tn.s)();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`mcp-config-state is-${t.tone}`,children:n(t.key)})," "]})}function gB(e){let{status:t,showState:n,entryCwd:i}=e,{t:s,locale:o}=(0,tn.s)(),l=pf(t.testedAt,o),a=t.serverInfo;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(gD,{view:t.timedOut?{key:p2.timedOut,tone:"error"}:{key:p2[t.state],tone:ph(t.state)}}),s((t.afterSignIn?p8:p4)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:p3(t.durationMs),time:l})]}),(0,r.jsx)(gO,{error:t.error,stderr:t.stderr}),a&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.serverInfo",{name:u2(a.title??a.name),version:u2(a.version)})}),t.resources&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.resources")}),void 0!==t.cwd&&t.cwd!==i&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.ranIn",{path:gC(t.cwd)})}),void 0!==t.queuedMs&&t.queuedMs>=500&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.queued",{seconds:p3(t.queuedMs)})})]})}function gH(e){let{status:t,showState:n}=e,{t:i,locale:s}=(0,tn.s)(),o=pf(t.updatedAt,s),l=void 0===t.closedAt?void 0:pf(t.closedAt,s);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(gD,{view:void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:pg[t.state],tone:pv[t.state]}}),i(void 0!==t.closedAt?"mcp.session.summary.closed":px[t.state],{path:gC(t.cwd),time:o,...void 0===l?{}:{closedTime:l}})]}),void 0!==t.conflict&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.session.conflictOwner")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:gC(t.conflict)})]}),(0,r.jsx)(gO,{error:t.error,stderr:t.stderr})]})}function g_(e){let{status:t,serverExposure:n}=e,{t:i}=(0,tn.s)(),s=t.toolCount-t.tools.length;return(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("ul",{className:"mcp-test-tools",children:t.tools.map((e,t)=>(0,r.jsxs)("li",{className:"mcp-test-tool",children:[(0,r.jsxs)("span",{className:"mcp-config-chips",children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(e.name)}),e.readOnly&&(0,r.jsx)("span",{className:"mcp-test-tool-tag",children:i("mcp.test.readOnly")}),e.exposure!==(n??"codemode")&&(0,r.jsx)("span",{className:"mcp-test-tool-tag",children:i(pj[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:u2(e.description)})]},`${t}\0${e.name}`))}),s>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.moreTools",{count:s})})]})}function gU(e){let{server:t,test:n,testBlock:s,describedBy:o,onTest:l}=e,{t:a}=(0,tn.s)(),d=(0,i.useRef)(null),c=n?.running===!0,u=(0,i.useRef)(c);return(0,i.useEffect)(()=>{let e=u.current;u.current=c,e&&!c&&eB(document,d.current)},[c]),(0,r.jsx)(cj,{ref:d,size:"small",disabled:c||void 0!==s,"aria-busy":c||void 0,"aria-describedby":s?o:void 0,onClick:()=>l(t),children:a(c?"mcp.test.testing":"mcp.test.button")})}function gK(e){let{server:t,state:n,test:i,testBlock:s,testBlockId:o}=e,{t:l}=(0,tn.s)(),a=t.status,d=pu[n],c="invalid"===s&&"invalid"===n?"state":"web-password"===s&&void 0!==t.webPasswordField?"password":void 0;return(0,r.jsx)(cd,{label:l("i18n.status"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:`mcp-config-state is-${ph(n)}`,children:l(pc(n,a))}),"invalid"===n&&(0,r.jsxs)("span",{id:"state"===c?o:void 0,className:"mcp-config-line is-warning",children:[l("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(t.invalidError??"")})]}),t.webPasswordField&&(0,r.jsxs)("span",{id:"password"===c?o:void 0,className:"mcp-config-line is-warning",children:[l("mcp.server.webPassword")," ",(0,r.jsx)(gz,{fields:[t.webPasswordField]})]}),a?(0,r.jsx)(gF,{status:a,showState:po(a)!==n,entryCwd:t.cwd}):!s&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.test.never")}),d&&(0,r.jsx)("span",{className:"mcp-config-line",children:l(d)}),i?.queueTimedOut&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-error",children:l("mcp.test.queueTimedOut")}),i?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[l("mcp.test.requestFailed")," ",function(e,t){if(e.timedOut)return t("mcp.test.requestTimedOut");let n=e.reason?p1[e.reason]:void 0;return n?t(n):gE(e,t)}(i.error,l)]}),s&&!c&&(0,r.jsx)("span",{id:o,className:"mcp-config-line is-dim",children:l(pQ[s])}),!s&&t.commandFields.length>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:l("mcp.test.serial")})]})})}function gq(e){let{codemode:t,autoEnable:n,save:i,serverBusy:s,onChange:o,onModeChange:l,onInlineBudgetSave:a}=e,{t:d}=(0,tn.s)(),c=t.sandbox,u=t.preference,p=i.saving||s,h=void 0===i.target||"preference"===i.target?i:{saving:!1,error:null},m=function(e,t){if("automatic"===pE(e)&&!t.value)return{key:"mcp.codemode.autoEnableOff",params:{path:t.path}}}(t,n),f="unavailable"===t.sandbox.state?{key:"mcp.codemode.alwaysUnavailable.sandbox"}:t.globalBuiltinSettingsPath?{key:"mcp.codemode.alwaysUnavailable.builtin",params:{path:t.globalBuiltinSettingsPath}}:void 0,g=function(e){if(!e.builtinDisabled)return;let t=e.builtinSettingsPath;return t?e.globalBuiltinSettingsPath?{key:"mcp.codemode.builtinDisabled",params:{path:t}}:{key:"mcp.codemode.builtinDisabledProject",params:{path:t}}:{key:"mcp.codemode.builtinDisabledUnknown"}}(t),x=function(e){let t=e.projectOverride;if(t)return{key:pI[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(ct,{children:[(0,r.jsx)(cn,{children:(0,r.jsx)(cr,{children:(0,r.jsx)(cs,{children:d("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:d("mcp.codemode.intro")}),(0,r.jsxs)(ca,{children:[(0,r.jsx)(cd,{label:d("mcp.codemode.mode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[u?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cu,{value:u,label:d("mcp.codemode.title"),options:[{value:"automatic",label:d(pM.automatic),disabled:p},{value:"always",label:d(pM.always),disabled:p||void 0!==f}],disabledReason:f?gN(f,d):null,onChange:e=>{e!==u&&o(e)},children:h.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("always"===u?"mcp.codemode.alwaysDescription":"mcp.codemode.automaticDescription")})]}):(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.saveFailed")," ",(0,r.jsx)(gV,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:gN(x,d)}),m&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:gN(m,d)})]})}),t.mode?(0,r.jsx)(gZ,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:l}):void 0!==t.modeError&&(0,r.jsx)(cd,{label:d("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(gJ,{budget:t.inlineBudget,save:i,waiting:p,onSave:a}):void 0!==t.inlineBudgetError&&(0,r.jsx)(cd,{label:d("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(t.inlineBudgetError)})]})}),(0,r.jsx)(cd,{label:d("mcp.codemode.sandbox"),tone:"plain",children:"unavailable"===c.state?(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.sandbox.unavailable")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(c.error)})]}):(0,r.jsx)("span",{className:"mcp-config-line",children:d("available"===c.state?"mcp.codemode.sandbox.available":"mcp.codemode.sandbox.not-checked")})}),g&&(0,r.jsx)(cd,{label:d("mcp.codemode.builtin"),tone:"error",children:gN(g,d)})]})]})}function gV(e){let{error:t}=e,{t:n}=(0,tn.s)();return t.timedOut?(0,r.jsx)(r.Fragment,{children:n("mcp.codemode.saveTimedOut")}):t.reason&&"internal"!==t.reason?(0,r.jsx)(r.Fragment,{children:n(`mcp.reason.${t.reason}`)}):(0,r.jsx)("code",{className:"mcp-config-chip",children:u2(t.error)})}function gZ(e){let{mode:t,codemode:n,save:i,waiting:s,onChange:o}=e,{t:l}=(0,tn.s)(),a="mode"===i.target,d=function(e){let t=e.mode;if(!t)return[];let n=[];void 0!==t.invalid&&n.push({key:"mcp.codemode.toolMode.invalid",params:{path:t.settingsPath,value:t.invalid}});let r=t.projectOverride;return r&&n.push({key:pT[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===pE(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(cd,{label:l("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(cu,{value:t.value,label:l("mcp.codemode.toolMode"),options:[{value:"on",label:l("mcp.codemode.toolMode.on"),disabled:s},{value:"only",label:l("mcp.codemode.toolMode.only"),disabled:s}],onChange:e=>{(e!==t.value||void 0!==t.invalid)&&o(e)},children:a&&i.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:l("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:l(p$[t.value])}),d.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:gN(e,l)},e.key)),a&&i.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[l("mcp.codemode.toolMode.saveFailed")," ",(0,r.jsx)(gV,{error:i.error})]})]})})}function gJ(e){let t,n,{budget:s,save:o,waiting:l,onSave:a}=e,{t:d}=(0,tn.s)(),c=(0,i.useRef)(null),u=(0,i.useId)(),p=void 0===s.value?"":String(s.value),[h,m]=(0,i.useState)(p);(0,i.useEffect)(()=>{m(p)},[p]);let f=function(e,t){let n=e.trim();if(""===n)return{ok:!0,value:null};if(!/^\d+$/.test(n))return{ok:!1};let r=Number(n);return r<=t?{ok:!0,value:r}:{ok:!1}}(h,s.max),g=!!f.ok&&(null===f.value?void 0!==s.value||void 0!==s.invalid:f.value!==s.value),x="inlineBudget"===o.target,v=x&&o.saving,b=(0,i.useRef)(v);(0,i.useEffect)(()=>{let e=b.current;b.current=v,e&&!v&&eB(document,c.current)},[v]);let y=(t=[],void 0!==s.invalid&&t.push({key:"mcp.codemode.inlineBudget.invalid",params:{path:s.settingsPath,value:s.invalid,default:String(s.default)}}),(n=s.projectOverride)&&t.push(void 0!==n.value?{key:"mcp.codemode.inlineBudget.projectOverride",params:{path:n.settingsPath,value:String(n.value)}}:{key:"mcp.codemode.inlineBudget.projectOverrideDefault",params:{path:n.settingsPath,default:String(s.default)}}),t);return(0,r.jsx)(cd,{label:d("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsxs)("form",{className:"mcp-codemode-budget",onSubmit:e=>{e.preventDefault(),f.ok&&g&&!l&&a(f.value)},children:[(0,r.jsx)("input",{ref:c,className:"mcp-add-input mcp-codemode-budget-input",inputMode:"numeric","aria-label":d("mcp.codemode.inlineBudget"),"aria-describedby":u,"aria-invalid":!f.ok||void 0,value:h,placeholder:String(s.default),readOnly:l,autoComplete:"off",spellCheck:!1,onChange:e=>m(e.target.value)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.unit")}),(0,r.jsx)(cj,{type:"submit",size:"small",disabled:!g||l,children:d("mcp.codemode.inlineBudget.save")}),v&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})]}),!f.ok&&(0,r.jsx)("span",{className:"mcp-config-line is-error",children:d("mcp.codemode.inlineBudget.invalidDraft",{max:String(s.max)})}),(0,r.jsx)("span",{id:u,className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.description",{default:String(s.default)})}),y.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:gN(e,d)},e.key)),x&&o.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.inlineBudget.saveFailed")," ",(0,r.jsx)(gV,{error:o.error})]})]})})}let gG=[{kind:"ui",label:"settings.uiFontFamily",placeholder:"settings.uiFontPlaceholder",reset:"settings.resetUiFont",weightLabel:"settings.uiFontWeight"},{kind:"mono",label:"settings.monoFontFamily",placeholder:"settings.monoFontPlaceholder",reset:"settings.resetMonoFont",weightLabel:"settings.monoFontWeight"}];function gY(){let{t:e}=(0,tn.s)(),t=ob();return(0,r.jsx)("div",{className:"settings-font-rows",children:gG.map(n=>{let{kind:i,label:s,placeholder:o,reset:l,weightLabel:a}=n,d=t[`${i}Weight`],c=s7.findIndex(e=>e.value===d);return(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option settings-font-row",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header settings-font-header",children:[(0,r.jsx)("label",{htmlFor:`settings-font-${i}`,children:e(s)}),(0,r.jsx)("input",{id:`settings-font-${i}`,className:`settings-font-input${"mono"===i?" is-mono":""}`,type:"text",value:t[i],placeholder:e(o),maxLength:500,"aria-describedby":"settings-typography-description",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:e=>t.setFontPreference(i,e.target.value)}),(0,r.jsx)("output",{htmlFor:`settings-font-${i}-weight`,title:`${e(a)}: ${d}`,children:e(s7[c].label)}),(0,r.jsx)(cj,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(l),"aria-label":e(l),disabled:!t[i]&&400===d,onClick:()=>t.resetFontPreference(i),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:`settings-font-${i}-weight`,type:"range",min:s7[0].value,max:s7[s7.length-1].value,step:100,value:d,"aria-label":e(a),"aria-valuetext":`${d} ${e(s7[c].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}let gX={granted:"settings.notificationsOn",default:"settings.notificationsOff",denied:"settings.notificationsBlocked",unsupported:"settings.notificationsUnsupported"};function gQ(e){let{section:t,size:n=16,strokeWidth:i=1.8}=e,s={width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"settings-section-icon"};return"general"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"M20 7h-9M14 17H5"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"3"}),(0,r.jsx)("circle",{cx:"17",cy:"17",r:"3"})]}):"models"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("path",{d:"M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 15h3M1 9h3M1 15h3"})]}):"skills"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"m12 2-10 5 10 5 10-5-10-5Z"}),(0,r.jsx)("path",{d:"m2 12 10 5 10-5M2 17l10 5 10-5"})]}):"agents"===t?(0,r.jsxs)("svg",{...s,className:"settings-section-icon is-agent",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}):"mcp"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"7",rx:"2"}),(0,r.jsx)("rect",{x:"3",y:"14",width:"18",height:"7",rx:"2"}),(0,r.jsx)("path",{d:"M7 6.5h.01M7 17.5h.01M11 6.5h6M11 17.5h6"})]}):(0,r.jsx)("svg",{...s,children:(0,r.jsx)("path",{d:"M9 7V2M15 7V2M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0ZM12 19v3"})})}function g0(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:s,onQuoteSelectionChange:o}=e,{locale:l,setLocale:a,supportedLocales:d,t:c}=(0,tn.s)(),{preference:u,setThemePreference:p}=(0,aF.D)(),{width:h,setWidth:m,fontSize:f,setFontSize:g}=s9(),x=sV(),v=tt(),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(!1),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(!1),[E,I]=(0,i.useState)(null),[$,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(null),[A,L]=(0,i.useState)(null),[z,P]=(0,i.useState)(!1),[W,O]=(0,i.useState)(null),F=A?A.supported?A.enabled&&A.failure?{kind:"failed",reason:A.failure}:null:{kind:"unavailable",reason:A.unsupportedReason??""}:null,[D,B]=(0,i.useState)(!1),[H,_]=(0,i.useState)(!1),[U,K]=(0,i.useState)(null),[q,V]=(0,i.useState)(null),[Z,J]=(0,i.useState)(!1),[G,Y]=(0,i.useState)(!1),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(!1),[ei,es]=(0,i.useState)(!1),[eo,el]=(0,i.useState)("");(0,i.useEffect)(()=>{N(ib()),V(uo()),uc().then(J),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>er(e?.enabled===!0)).catch(()=>{})},[]),(0,i.useEffect)(()=>{if("u"<typeof navigator||!navigator.permissions)return;let e=!1,t=null;return navigator.permissions.query({name:"notifications"}).then(n=>{e||(t=n,n.onchange=()=>{V(uo()),_(!1)})}).catch(()=>{}),()=>{e=!0,t&&(t.onchange=null)}},[]);let ea=async()=>{es(!0),el("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{el(c("auth.logoutFailed"))}finally{es(!1)}};(0,i.useEffect)(()=>{let e=!1;return fetch("/api/tools/settings").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||y(n)}).catch(t=>{e||S(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/cache-miss-notices").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||I(!0===n.enabled)}).catch(t=>{e||R(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/sleep-inhibit").then(async t=>{let n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);e||L(n)}).catch(t=>{e||O(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let ed=async e=>{P(!0),O(null);try{let t=await fetch("/api/sleep-inhibit",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);L(n)}catch(e){O(e instanceof Error?e.message:String(e))}finally{P(!1)}},ec=async e=>{T(!0),R(null);try{let r=await fetch("/api/cache-miss-notices",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);I(!0===i.enabled),t&&n()}catch(e){R(e instanceof Error?e.message:String(e))}finally{T(!1)}},eu=async e=>{k(!0),S(null);try{let r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);y(i),t&&(await lw(t,{type:"reload"}),n())}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(!1)}},ep=async()=>{if(!D&&!H){K(null);try{if(!("Notification"in window))throw Error("unsupported or not permitted");if("default"===Notification.permission){_(!0);try{await Notification.requestPermission()}finally{_(!1)}let e=uo();V(e),"granted"===e&&Z&&uu(l);return}if(B(!0),!await uu(l))throw Error("unsupported or not permitted");K({kind:"ok",message:c("settings.pushRegistered")})}catch(e){K({kind:"error",message:`${c("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{B(!1)}}},eh=async()=>{if(!G){Y(!0),Q(null),et(null);try{let e=await fetch("/api/app-update?refresh=1"),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);Q(t)}catch(e){et(e instanceof Error?e.message:String(e))}finally{Y(!1)}}};return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.appearance")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":c("settings.appearance"),className:"settings-theme-options",children:dS.F$.map(e=>{let t=u===e.id;return(0,r.jsxs)("label",{className:"settings-theme-option","data-system":"auto"===e.id||void 0,"data-wide":"contrast-light"===e.id||"contrast-dark"===e.id||"zenburn"===e.id||void 0,children:[(0,r.jsx)("input",{type:"radio",name:"theme",value:e.id,checked:t,onChange:()=>p(e.id),className:"sr-only"}),"auto"===e.id?(0,r.jsxs)("span",{className:"settings-theme-swatch settings-theme-system","aria-hidden":"true",children:[(0,r.jsx)("span",{"data-theme":"light",className:"settings-theme-chip"}),(0,r.jsx)("span",{"data-theme":"dark",className:"settings-theme-chip"}),(0,r.jsx)("span",{className:"settings-theme-system-name",children:c(e.label)})]}):(0,r.jsx)("span",{className:"settings-theme-swatch","aria-hidden":"true",children:(0,r.jsx)("span",{"data-theme":e.id,className:"settings-theme-fill",children:(0,r.jsx)("span",{className:"settings-theme-name",children:c(e.label)})})}),(0,r.jsx)("span",{className:"sr-only",children:c(e.label)})]},e.id)})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.typography")}),(0,r.jsx)("p",{id:"settings-typography-description",className:"settings-general-description",children:c("settings.fontDescription")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsx)(gY,{}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-font-size",children:c("settings.chatContentFontSize")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[f,"px"]}),(0,r.jsx)(cj,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentFontSize"),"aria-label":c("settings.resetChatContentFontSize"),disabled:14===f,onClick:()=>g(14),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-font-size",type:"range",min:12,max:24,step:1,value:f,onChange:e=>g(Number(e.target.value))})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-width",children:c("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(cj,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentWidth"),"aria-label":c("settings.resetChatContentWidth"),disabled:820===h,onClick:()=>m(820),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-width",type:"range",min:820,max:2e3,step:10,value:h,onChange:e=>m(Number(e.target.value))})]})]})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.chat")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.thinkingExpandedDefault")}),(0,r.jsx)(ck,{checked:C,label:c("settings.thinkingExpandedDefault"),onChange:e=>{!function(e){try{window.localStorage.setItem(ix,String(e))}catch{return}window.dispatchEvent(new Event(iv))}(e),N(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.quoteSelection")}),(0,r.jsx)(ck,{checked:s,label:c("settings.quoteSelection"),onChange:o})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":c("settings.enterSendMode"),children:[(0,r.jsx)("span",{children:c("settings.enterSendMode")}),(0,r.jsxs)("div",{className:"settings-send-mode-options",children:[(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"enter-send-mode",value:"enter",checked:"enter"===x,onChange:()=>sq("enter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.enterSendModeEnter")})]}),(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"enter-send-mode",value:"ctrlEnter",checked:"ctrlEnter"===x,onChange:()=>sq("ctrlEnter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.enterSendModeCtrlEnter")})]})]})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.cacheMissNotices")}),(0,r.jsx)(ck,{checked:!0===E,loading:null===E&&!M||$,label:c("settings.cacheMissNotices"),describedBy:"settings-cache-miss-notices-description",onChange:e=>void ec(e)})]})]}),(0,r.jsx)("p",{id:"settings-cache-miss-notices-description",className:"settings-general-description",children:c("settings.cacheMissNoticesDescription")}),M&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:M})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("hotkeys.dialogTitle")}),(0,r.jsx)("div",{style:{maxWidth:420,marginTop:8},children:(0,r.jsx)(lu,{enterSendMode:x,idPrefix:"settings-hotkeys-section"})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.sidebar")}),(0,r.jsx)("div",{className:"settings-chat-options",children:(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":c("settings.filesPlacement"),"aria-describedby":"settings-files-placement-description",children:[(0,r.jsx)("span",{children:c("settings.filesPlacement")}),(0,r.jsxs)("div",{className:"settings-send-mode-options",children:[(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"files-placement",value:"below",checked:"below"===v,onChange:()=>te("below"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.filesPlacementBelow")})]}),(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"files-placement",value:"tab",checked:"tab"===v,onChange:()=>te("tab"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.filesPlacementTab")})]})]})]})}),(0,r.jsx)("p",{id:"settings-files-placement-description",className:"settings-general-description",children:c("settings.filesPlacementDescription")})]}),b?.isWindows&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.shellTool")}),(0,r.jsx)("p",{className:"settings-general-description",children:c("settings.shellToolDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.usePowerShell")}),(0,r.jsx)(ck,{checked:b.powerShellEnabled,loading:j,label:c("settings.usePowerShell"),onChange:e=>void eu(e)})]}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.power")}),(0,r.jsx)("div",{className:"settings-chat-options",children:(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.preventSleep")}),(0,r.jsx)(ck,{checked:A?.enabled===!0&&A.supported,disabled:A?.supported===!1,loading:null===A&&!W||z,label:c("settings.preventSleep"),describedBy:F?"settings-prevent-sleep-description settings-prevent-sleep-note":"settings-prevent-sleep-description",onChange:e=>void ed(e)})]})}),(0,r.jsx)("p",{id:"settings-prevent-sleep-description",className:"settings-general-description",children:c("settings.preventSleepDescription")}),F&&(0,r.jsx)("p",{id:"settings-prevent-sleep-note",role:"failed"===F.kind?"alert":"status",className:"settings-general-error",style:"failed"===F.kind?void 0:{color:"var(--text-dim)"},children:c("failed"===F.kind?"settings.preventSleepFailed":"settings.preventSleepUnavailable",{reason:F.reason})}),W&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:W})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.pushPermission")}),(0,r.jsx)("p",{className:"settings-general-description",children:c("settings.pushPermissionDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:q?c(gX[q]):""}),("default"===q||"granted"===q&&Z)&&(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:D||H,onClick:()=>void ep(),children:H?c("settings.notificationsWaiting"):D?c("settings.pushRegisterLoading"):c("default"===q?"settings.notificationsEnable":"settings.pushRegister")})]}),H&&(0,r.jsx)("p",{role:"status",className:"settings-general-description",children:c("settings.notificationsWaitingHint")}),U&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===U.kind?{color:"var(--accent)"}:void 0,children:U.message})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":c("common.language"),className:"settings-language-options",children:d.map(e=>{let t=l===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>a(e.id),className:"settings-language-option",children:[(0,r.jsx)("span",{className:"settings-language-radio",children:t&&(0,r.jsx)("span",{className:"settings-language-radio-dot"})}),(0,r.jsx)("span",{className:"settings-language-label",children:e.label}),(0,r.jsx)("span",{className:"settings-language-code",children:e.id})]},e.id)})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.updates")}),(0,r.jsx)("p",{className:"settings-general-description",children:c("settings.updatesDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.updatesCurrent",{version:"1.6.1"})}),(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:G||X?.disabled===!0,onClick:()=>void eh(),children:G?c("settings.updatesChecking"):c("settings.updatesCheck")})]}),X&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:{color:X.disabled?"var(--text-dim)":"var(--accent)"},children:X.disabled?c("settings.updatesDisabled"):X.updateAvailable?(0,r.jsx)("a",{href:X.releaseUrl,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"underline"},children:c("appUpdate.releaseNotes",{version:X.latestVersion})}):c("settings.updatesUpToDate",{version:X.currentVersion})}),ee&&(0,r.jsxs)("p",{role:"alert",className:"settings-general-error",children:[c("settings.updatesFailed")," ",ee]})]}),en&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(cj,{variant:"secondary",disabled:ei,onClick:()=>void ea(),children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M10 17l5-5-5-5M15 12H3M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"})}),ei?c("auth.loggingOut"):c("auth.logOut")]}),eo&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:eo})]})]})}function g1(e){let{cwd:t,sessionId:n,initialSection:s,onClose:o,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:d,projectTrust:c,onOpenTrustDialog:u,onProjectTrustChanged:p}=e,{t:h}=(0,tn.s)(),[m,f]=(0,i.useState)(s),[g,x]=(0,i.useState)(()=>new Set([m])),v=[{id:"general",label:h("settings.general")},{id:"models",label:h("common.models")},{id:"skills",label:h("common.skills")},{id:"agents",label:h("common.agents")},{id:"plugins",label:h("common.plugins")},{id:"mcp",label:h("settings.mcp")}].map(e=>({...e,requiresProject:dI(e.id)})),b=dI(m);(0,i.useEffect)(()=>dR(s),[s]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||eF(e)||(e.preventDefault(),o())},e.addEventListener("keydown",t,!1),()=>e.removeEventListener("keydown",t,!1)},[o]);let y=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>(function(e,t){let{restoreTextEntry:n=!0}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=e.activeElement,i=!!(r&&t&&t.contains(r)),s=r&&r!==e.body&&!i?r:null;return t&&!i&&t.focus({preventScroll:!0}),()=>{if(!s||!s.isConnected||!n&&function(e){if(e.isContentEditable)return!0;let t=e.tagName?.toUpperCase();return"TEXTAREA"===t||"INPUT"===t&&!["button","checkbox","color","file","hidden","image","radio","range","reset","submit"].includes((e.type??"text").toLowerCase())}(s))return;let r=e.activeElement;r&&r!==e.body&&!(t&&t.contains(r))||"function"==typeof s.focus&&s.focus({preventScroll:!0})}})(document,y.current,{restoreTextEntry:!window.matchMedia?.("(pointer: coarse)").matches}),[]),(0,i.useEffect)(()=>{!t&&b&&(f("general"),x(e=>new Set(e).add("general")),dR("general"))},[t,b]);let j=e=>{x(t=>new Set(t).add(e)),f(e),dR(e)},k=(e,t)=>g.has(e)?(0,r.jsx)("div",{hidden:m!==e,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{ref:y,role:"dialog","aria-modal":"true","aria-label":h("settings.title"),tabIndex:-1,onClick:e=>{e.target===e.currentTarget&&o()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{className:"settings-dialog-header",children:[(0,r.jsx)("strong",{className:"settings-dialog-title",children:h("settings.title")}),(0,r.jsx)("select",{"aria-label":h("settings.title"),value:m,onChange:e=>j(e.target.value),className:"settings-mobile-section-picker",children:v.map(e=>(0,r.jsx)("option",{value:e.id,disabled:e.requiresProject&&!t,children:e.label},e.id))}),(0,r.jsx)("nav",{"aria-label":h("settings.title"),className:"settings-section-tabs",children:v.map(e=>{let n=m===e.id,i=e.requiresProject&&!t;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?h("settings.projectRequired"):e.label,"aria-current":n?"page":void 0,onClick:()=>j(e.id),children:[(0,r.jsx)(gQ,{section:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id)})}),(0,r.jsx)("button",{type:"button",onClick:o,title:h("i18n.close"),"aria-label":h("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{className:"settings-dialog-main",children:[k("general",(0,r.jsx)(g0,{sessionId:n,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:d})),k("models",(0,r.jsx)(ui,{embedded:!0,cwd:t,onClose:o})),t&&k("skills",(0,r.jsx)(uC,{embedded:!0,cwd:t,trust:c,onClose:o},t)),t&&k("agents",(0,r.jsx)(uO,{embedded:!0,cwd:t,sessionId:n,trust:c,onClose:o,onReloaded:l},t)),t&&k("plugins",(0,r.jsx)(uX,{embedded:!0,cwd:t,sessionId:n,trust:c,onClose:o,onReloaded:l},t)),k("mcp",(0,r.jsx)(gT,{embedded:!0,cwd:t,trust:c,onTrustProject:u,onProjectTrustChanged:p,onClose:o},t??""))]})]})})}let g2="project-trust-mcp-status";function g4(e){let{cwd:t,busy:n,error:s,onCancel:o,onConfirm:l,onStatus:a}=e,[d,c]=(0,i.useState)({state:"loading"}),u=(0,i.useRef)(a);return(0,i.useEffect)(()=>{u.current=a},[a]),(0,i.useEffect)(()=>{let e=!0,n=!1;c({state:"loading"});let r=new AbortController,i=window.setTimeout(()=>{n=!0,r.abort()},1e4);return fetch(`/api/project-trust?cwd=${encodeURIComponent(t)}`,{signal:r.signal,cache:"no-store"}).then(async t=>{let n=await t.json();if(!e)return;let r=function(e,t,n){let r=Array.isArray(n.mcpServers)?{mcpServers:n.mcpServers,...n.mcpFile?{mcpFile:n.mcpFile}:{},...void 0!==n.mcpError?{mcpError:n.mcpError}:{}}:void 0;if(e&&!n.error&&r&&"boolean"==typeof n.requiresTrust){let e;return{state:"loaded",listing:r,status:(e={requiresTrust:n.requiresTrust,trusted:n.trusted,decision:n.decision,inherited:n.inherited},void 0!==n.decisionPath&&(e.decisionPath=n.decisionPath),void 0!==n.decisionError&&(e.decisionError=n.decisionError),e)}}return"trust-unreadable"===n.reason&&r?{state:"loaded",listing:r,statusError:n.error??`HTTP ${t}`}:{state:"failed",error:n.error??`HTTP ${t}`,reason:n.reason}}(t.ok,t.status,n);c(r),"loaded"===r.state&&r.status&&u.current?.(r.status)}).catch(t=>{e&&c(n?{state:"failed",timedOut:!0}:{state:"failed",error:t instanceof Error?t.message:String(t)})}).finally(()=>window.clearTimeout(i)),()=>{e=!1,window.clearTimeout(i),r.abort()}},[t]),(0,r.jsx)(g8,{cwd:t,busy:n,error:s,listing:d,onCancel:o,onConfirm:l})}function g8(e){let{cwd:t,busy:n,error:s,listing:o,onCancel:l,onConfirm:a}=e,{t:d}=(0,tn.s)(),c="loading"===o.state,u="loaded"===o.state?function(e){if(e){if(!e.requiresTrust)return"mcp.reason.trust-not-required";if(e.trusted)return"trust.alreadyTrusted"}}(o.status):void 0,p=(0,i.useRef)(null),h=(0,i.useRef)(n),m=(0,i.useRef)(l);return(0,i.useEffect)(()=>{h.current=n,m.current=l},[n,l]),(0,i.useEffect)(()=>eD(document,p.current,()=>{h.current||m.current()}),[]),(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{n||e.target!==e.currentTarget||l()},children:(0,r.jsxs)("div",{ref:p,role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-description",tabIndex:-1,className:"project-trust-dialog",children:[(0,r.jsxs)("div",{className:"project-trust-body",children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"project-trust-icon",children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"project-trust-title",className:"project-trust-title",children:d("trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-description",className:"project-trust-text",children:d("trust.dialogBody")}),(0,r.jsx)("code",{className:"project-trust-path",children:u2(t)}),u&&(0,r.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:d(u)}),"loaded"===o.state&&void 0!==o.statusError&&(0,r.jsxs)("div",{className:"project-trust-mcp-failed",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:d("mcp.reason.trust-unreadable")}),(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:u2(o.statusError)})]}),(0,r.jsx)(g5,{listing:o})]})]}),s&&(0,r.jsx)(g3,{error:s}),(0,r.jsxs)("div",{className:"project-trust-footer",children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:l,disabled:n,children:d(u?"trust.close":"trust.cancel")}),!u&&(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:a,disabled:n||c,"aria-busy":n||void 0,"aria-describedby":c?g2:void 0,children:d(n?"trust.trusting":"trust.trustProject")})]})]})})}function g3(e){let{error:t}=e,{t:n}=(0,tn.s)(),i=void 0!==t.reason&&"internal"!==t.reason;return(0,r.jsxs)("div",{role:"alert",className:"project-trust-error",children:[n(i?`mcp.reason.${t.reason}`:"trust.trustFailed"),!i&&(0,r.jsx)("code",{className:"project-trust-error-detail",children:u2(t.error)})]})}function g5(e){let{listing:t}=e,{t:n}=(0,tn.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:g2,role:"status",className:"project-trust-mcp-status",children:n("trust.mcp.loading")});if("failed"===t.state||void 0!==t.listing.mcpError||!t.listing.mcpFile){let e;e="failed"===t.state?t.reason&&"internal"!==t.reason?n(`mcp.reason.${t.reason}`):t.error:t.listing.mcpError;let i="failed"===t.state&&t.timedOut;return(0,r.jsxs)("div",{className:"project-trust-mcp-failed",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n(i?"trust.mcp.timedOut":"trust.mcp.loadFailed")}),e&&(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:u2(e)})]})}let{mcpFile:i,mcpServers:s}=t.listing;return i.exists||0!==i.problems.length?(0,r.jsxs)("section",{className:"project-trust-mcp","aria-labelledby":"project-trust-mcp-title",children:[(0,r.jsx)("div",{id:"project-trust-mcp-title",className:"project-trust-mcp-title",children:n("trust.mcp.title")}),s.length>0&&(0,r.jsx)("p",{className:"project-trust-mcp-intro",children:n("trust.mcp.intro")}),(0,r.jsx)(g6,{file:i}),0===s.length&&0===i.problems.length&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.none")}),s.some(e=>!e.validated)&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.unchecked")}),s.length>0&&(0,r.jsx)("ul",{className:"project-trust-mcp-list",children:s.map(e=>(0,r.jsx)(xe,{server:e},e.name))})]}):null}function g6(e){let{file:t}=e,{t:n}=(0,tn.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=pn(e,t.realPath);return(0,r.jsxs)("div",{className:"project-trust-mcp-problem",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n(`mcp.fileProblem.${e.reason}`)}),i&&(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:i})]},e.reason)})})}function g9(e){let{fields:t}=e,{t:n}=(0,tn.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=u9(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function g7(e){let{server:t}=e,{t:n}=(0,tn.s)();return(0,r.jsx)(r.Fragment,{children:pt(t.variableReferences).map(e=>{let{variable:t,field:i}=e,s=u9(i);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n("mcp.server.variableIn",{variable:t,field:n(s.key,s.params)})},`${t}\0${i.kind}\0${i.name??""}`)})})}function xe(e){let t,{server:n}=e,{t:i}=(0,tn.s)(),s=u5(n),o=void 0===n.invalidError;return(0,r.jsxs)("li",{className:"project-trust-mcp-server",children:[(0,r.jsxs)("div",{className:"project-trust-mcp-server-head",children:[(0,r.jsx)("span",{className:"project-trust-mcp-server-name",children:u2(n.name)}),n.transport&&(0,r.jsx)("span",{className:"project-trust-mcp-tag",children:i(`mcp.transport.${n.transport}`)})]}),void 0!==s&&(0,r.jsx)("code",{className:"project-trust-mcp-target",children:s}),void 0!==n.cwd&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("trust.mcp.cwd",{path:u2(n.cwd)})}),u6(n)&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.hiddenCharacters")}),void 0!==n.invalidError&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:u2(n.invalidError)})]}),n.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.webPassword")," ",(0,r.jsx)(g9,{fields:[n.webPasswordField]})]}),!n.enabled&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("mcp.server.disabled")}),o&&n.commandFields.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.commandFields")," ",(0,r.jsx)(g9,{fields:n.commandFields})]}),o&&n.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i(u7(n))," ",(0,r.jsx)(g7,{server:n})]}),n.replacesGlobal&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.replacesGlobal")}),n.override&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i((t=pe(n.override.keys)).key,t.params)}),n.masked&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-dim",children:i("mcp.server.masked")})]})}function xt(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function xn(e){let t=e,n=t.branchPreview,r=xt(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&xt(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function xr(e){if(e.length>1)return!0;let t=[...e];for(;t.length>0;){let e=t.pop();if(e.children.length>1)return!0;for(let n of e.children)t.push(n)}return!1}function xi(e){let{node:t,activePathIds:n,depth:i,isLast:s,parentLines:o,onSelect:l}=e,{node:a,skipped:d,branchPreview:c,labelEntry:u}=xn(t),p=n.has(a.entry.id),h=n.has(t.entry.id)||n.has(a.entry.id),m=c?.text??function(e){if("message"===e.type&&xt(e)){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(u),f=c?c.role??null:xt(u)?u.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:l?"pointer":"default"},onClick:l?()=>l(a.entry.id):void 0,children:[o.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:s?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:p?"var(--accent)":h?"var(--text-muted)":"var(--border)",border:p?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),f&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===f?"var(--accent)":"var(--text-dim)",background:"user"===f?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===f?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===f?"U":"A"}),d>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",d]}),(0,r.jsx)("span",{style:{fontSize:11,color:p?"var(--text)":h?"var(--text-muted)":"var(--text-dim)",fontWeight:p?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:m})]}),a.children.map((e,t)=>(0,r.jsx)(xi,{node:e,activePathIds:n,depth:i+1,isLast:t===a.children.length-1,parentLines:[...o,!s],onSelect:l},e.entry.id))]})}function xs(e){let{tree:t,activeLeafId:n,onLeafChange:s,inline:o,containerRef:l,open:a,onToggle:d,hasSession:c,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:m}=(0,tn.s)(),[f,g]=(0,i.useState)(!1),x=void 0!==a?a:f,v=(0,i.useRef)(null),[b,y]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!x||!o)return;let e=l?.current??v.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();y({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[x,o,l]);let j=(0,i.useMemo)(()=>(function(e,t){if(!t)return new Set;let n=e.map(e=>({node:e,path:[e.entry.id]}));for(;n.length>0;){let{node:e,path:r}=n.pop();if(e.entry.id===t||e.compressedEntryIds?.includes(t))return new Set(r);for(let t of e.children)n.push({node:t,path:[...r,t.entry.id]})}return new Set})(t,n),[t,n]),k=(0,i.useCallback)(e=>{s(e)},[s]),w=h?void 0:k,S=h&&(0,r.jsx)("div",{style:{padding:"2px 0 4px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:m("i18n.branchesLockedWhileRunning")}),C=c?xr(t)?null:m("i18n.noBranches"):m("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=xn(e[0]).node;return t.children.length>1?t.children:[]}(t),E=!C&&N.length>0,I=o?x:E,$=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:I?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),T=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return o?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:v,onClick:()=>d?d():g(e=>!e),style:{display:p?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:x?"var(--bg-selected)":"none",border:"none",borderTop:x?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:x?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=x?"var(--text)":"var(--text-muted)"},title:m("i18n.branches"),"aria-label":m("i18n.branches"),"aria-pressed":x,children:[$,!u&&(0,r.jsx)("span",{children:m("i18n.branches")})]}),x&&b&&(0,r.jsx)("div",{style:{position:"fixed",top:b.top,left:b.left,width:b.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:E?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(xi,{node:e,activePathIds:j,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[$,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:m("i18n.branches")}),T]}),x&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:E?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(xi,{node:e,activePathIds:j,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C??m("i18n.noBranches")})})]})}function xo(e){let{systemPrompt:t,tools:n,loading:s,messageSummary:o,contextUsage:l,onSelectTab:a}=e,{t:d}=(0,tn.s)(),c=o??af,u=(0,i.useMemo)(()=>(function(e){let{systemPrompt:t,tools:n,messageSummary:r,contextUsage:i}=e,s=r??af,o=t?Math.ceil(t.length/4):0,l=(n??[]).filter(e=>e.active&&!e.declarationHidden),a=l.map(e=>({name:e.name,tokens:function(e){let t=(e.name?.length??0)+(e.description?.length??0);if(void 0!==e.parameters)try{t+=JSON.stringify(e.parameters).length}catch{}return Math.ceil(t/4)}(e)})).sort((e,t)=>t.tokens-e.tokens||e.name.localeCompare(t.name)),d=a.reduce((e,t)=>e+t.tokens,0),c=[{id:"system",color:"#3b82f6",estimatedTokens:o,alwaysShow:!0},{id:"tools",color:"#8b5cf6",estimatedTokens:d,alwaysShow:!0},{id:"compaction",color:"#14b8a6",estimatedTokens:s.compactionTokens,alwaysShow:!1},{id:"user",color:"#10b981",estimatedTokens:s.userTokens,alwaysShow:!0},{id:"assistant",color:"#f59e0b",estimatedTokens:s.assistantTextTokens,alwaysShow:!0},{id:"thinking",color:"#ec4899",estimatedTokens:s.assistantThinkingTokens,alwaysShow:!1},{id:"toolTraffic",color:"#f97316",estimatedTokens:s.toolTrafficTokens,alwaysShow:!0}].filter(e=>e.alwaysShow||e.estimatedTokens>0),u=c.reduce((e,t)=>e+t.estimatedTokens,0),p=i?.tokens!==null&&i?.tokens!==void 0&&Number.isFinite(i.tokens)&&i.tokens>0?Math.round(i.tokens):null,h=p??u,m=i?.contextWindow!==null&&i?.contextWindow!==void 0&&Number.isFinite(i.contextWindow)&&i.contextWindow>0?Math.round(i.contextWindow):null,f=null!==m?Math.max(0,m-h):null,g=null!==m&&m>0?Math.min(100,h/m*100):null,x=null!==p&&u>0?p/u:1;return{categories:c.map(e=>{let t=null!==p&&u>0?Math.round(e.estimatedTokens*x):e.estimatedTokens,n=u>0?e.estimatedTokens/u:0;return{id:e.id,color:e.color,estimatedTokens:e.estimatedTokens,tokens:t,shareOfUsed:n,percentOfWindow:null!==m&&m>0?t/m*100:null}}),estimatedTokens:u,reportedTokens:p,usedTokens:h,contextWindow:m,freeTokens:f,usedPercent:g,systemPromptTokens:o,toolsTokens:d,activeToolCount:l.length,toolDeclarations:a,toolTrafficByTool:s.toolTrafficByTool}})({systemPrompt:t,tools:n,messageSummary:c,contextUsage:l}),[t,n,c,l]),p=e=>{switch(e){case"system":return d("context.category.system");case"tools":return d("context.category.tools",{count:u.activeToolCount});case"compaction":return d("context.category.compaction");case"user":return d("context.category.user",{count:c.userCount});case"assistant":return d("context.category.assistant",{count:c.assistantCount});case"thinking":return d("context.category.thinking");case"toolTraffic":return d("context.category.toolTraffic",{count:c.toolCallCount})}},h=null!==u.contextWindow&&u.contextWindow>0,m=null!==u.reportedTokens&&u.estimatedTokens>0;return(0,r.jsxs)("div",{style:{padding:"10px 14px 14px",fontSize:12},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:12,flexWrap:"wrap",marginBottom:8},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:6},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:15,fontWeight:600,color:"var(--text)"},children:u.usedTokens.toLocaleString()}),h&&(0,r.jsxs)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["/ ",u.contextWindow.toLocaleString()," tokens",null!==u.usedPercent&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)"},children:["(",u.usedPercent.toFixed(1),"%)"]})]}),!h&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"tokens"})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[null!==u.freeTokens&&(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[d("context.free"),": ",u.freeTokens.toLocaleString()]}),(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:4,background:"var(--bg)",border:"1px solid var(--border)",color:"var(--text-dim)"},children:m?d("context.scaledBadge"):d("context.estimatedBadge")})]})]}),(0,r.jsx)("div",{role:"img","aria-label":d("context.title"),style:{display:"flex",height:12,borderRadius:6,overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",marginBottom:12},children:u.categories.map(e=>{let t=h?Math.max(0,Math.min(100,e.percentOfWindow??0)):Math.max(0,Math.min(100,100*e.shareOfUsed));return t<=0?null:(0,r.jsx)("div",{title:`${p(e.id)}: ${e.tokens.toLocaleString()} tokens`,style:{width:`${t}%`,minWidth:3*(e.tokens>0),background:e.color,transition:"width 0.2s ease"}},e.id)})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,paddingBottom:10,borderBottom:"1px solid var(--border)"},children:[u.categories.map(e=>{let t=h?e.percentOfWindow:100*e.shareOfUsed,n=a&&("system"===e.id||"tools"===e.id);return(0,r.jsxs)("div",{onClick:n?()=>a(e.id):void 0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"3px 6px",borderRadius:4,cursor:n?"pointer":"default"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{width:8,height:8,borderRadius:2,background:e.color,flexShrink:0}}),(0,r.jsx)("span",{style:{color:"var(--text)",textDecoration:n?"underline":"none",textDecorationColor:"var(--border)",textUnderlineOffset:3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p(e.id)}),s&&("system"===e.id||"tools"===e.id)&&0===e.tokens&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:"…"})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:[(0,r.jsx)("span",{style:{color:"var(--text)"},children:e.tokens.toLocaleString()}),null!==t&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",minWidth:44,textAlign:"right"},children:t<.1&&t>0?"<0.1%":`${t.toFixed(1)}%`})]})]},e.id)}),null!==u.freeTokens&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"3px 6px"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{width:8,height:8,borderRadius:2,border:"1px solid var(--border)",background:"var(--bg)",flexShrink:0}}),(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:d("context.free")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:u.freeTokens.toLocaleString()}),null!==u.usedPercent&&(0,r.jsxs)("span",{style:{color:"var(--text-dim)",minWidth:44,textAlign:"right"},children:[Math.max(0,100-u.usedPercent).toFixed(1),"%"]})]})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(210px, 1fr))",gap:12,marginTop:10},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:600,textTransform:"uppercase",letterSpacing:.5,color:"var(--text-dim)",marginBottom:6},children:d("context.topToolDefs")}),0===u.toolDeclarations.length?(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:11},children:s?d("tools.loading"):d("tools.noTools")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:u.toolDeclarations.slice(0,6).map(e=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.name,children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",flexShrink:0},children:["~",e.tokens.toLocaleString()]})]},e.name))})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:600,textTransform:"uppercase",letterSpacing:.5,color:"var(--text-dim)",marginBottom:6},children:d("context.topToolTraffic")}),0===u.toolTrafficByTool.length?(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:11},children:d("context.noToolTraffic")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:u.toolTrafficByTool.slice(0,6).map(e=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsxs)("span",{style:{color:"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.name,children:[e.name," ",(0,r.jsxs)("span",{style:{color:"var(--text-dim)"},children:["(",d("context.toolCallsCount",{count:e.calls}),")"]})]}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",flexShrink:0},children:["~",e.tokens.toLocaleString()]})]},e.name))})]})]})]})}function xl(e){let{loading:t,prompt:n,translate:i}=e;return(0,r.jsxs)("section",{className:"system-prompt-panel","aria-label":i("system.prompt"),children:[(0,r.jsx)("div",{className:"system-prompt-scroll",children:n?(0,r.jsx)("div",{className:"system-prompt-text",children:n}):(0,r.jsx)("div",{className:"system-prompt-empty",children:i(""===n?"system.empty":t?"system.loading":"system.load")})}),(0,r.jsx)("style",{children:`
82
+ .system-prompt-panel {
83
+ display: flex;
84
+ height: min(600px, 75dvh);
85
+ min-height: 220px;
86
+ flex-direction: column;
87
+ background: var(--bg-panel);
88
+ border-bottom: 1px solid var(--border);
89
+ }
90
+ .system-prompt-scroll {
91
+ min-height: 0;
92
+ flex: 1;
93
+ overflow: auto;
94
+ padding: 12px 16px;
95
+ }
96
+ .system-prompt-text {
97
+ color: var(--text-muted);
98
+ font-family: var(--font-mono);
99
+ font-size: 12px;
100
+ line-height: 1.6;
101
+ overflow-wrap: anywhere;
102
+ white-space: pre-wrap;
103
+ }
104
+ .system-prompt-empty {
105
+ padding: 10px 0;
106
+ color: var(--text-muted);
107
+ font-size: 12px;
108
+ font-style: italic;
109
+ }
110
+ `})]})}function xa(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function xd(e){let{children:t}=e;return(0,r.jsx)("div",{className:"tool-definitions-empty",children:t})}function xc(e){let{loading:t,tools:n,translate:s}=e,o=(0,i.useMemo)(()=>n?.filter(e=>e.active&&!e.declarationHidden)??null,[n]),[l,a]=(0,i.useState)(null);(0,i.useEffect)(()=>{a(e=>o?.some(t=>t.name===e)?e:o?.[0]?.name??null)},[o]);let d=o?.find(e=>e.name===l)??o?.[0]??null,c=d?function(e){if(!e||!e.properties||"object"!=typeof e.properties)return[];let t=e.properties,n=new Set(Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[]);return Object.entries(t).map(e=>{let[t,r]=e,i=r&&"object"==typeof r?r:{};return{name:t,type:function e(t){let n=Array.isArray(t.anyOf)?t.anyOf:Array.isArray(t.oneOf)?t.oneOf:null;if(n)return n.map(t=>t&&"object"==typeof t?e(t):"unknown").filter((e,t,n)=>n.indexOf(e)===t).join(" | ");if(void 0!==t.const)return xa(t.const);if(Array.isArray(t.enum)&&t.enum.length>0&&void 0===t.type)return[...new Set(t.enum.map(e=>null===e?"null":typeof e))].join(" | ");let r=t.type,i=Array.isArray(r)?r.filter(e=>"string"==typeof e).join(" | "):"string"==typeof r?r:"string"==typeof t.$ref?t.$ref.split("/").pop()??"object":"unknown";if("array"===i){let n=t.items,r=n&&"object"==typeof n?e(n):"unknown";return`${r}[]`}return i}(i),description:"string"==typeof i.description?i.description:void 0,required:n.has(t),allowedValues:Array.isArray(i.enum)?i.enum.map(xa).join(", "):void 0,defaultValue:void 0===i.default?void 0:xa(i.default)}})}(d.parameters):[];return(0,r.jsxs)("div",{className:"tool-definitions-panel",children:[(0,r.jsx)("nav",{className:"tool-definitions-sidebar","aria-label":s("tools.title"),children:(0,r.jsx)("div",{className:"tool-definitions-list",children:o&&o.length>0?o.map(e=>{let t=e.name===d?.name;return(0,r.jsx)("button",{type:"button",className:`tool-definitions-item${t?" selected":""}`,"aria-pressed":t,onClick:()=>a(e.name),children:(0,r.jsx)("code",{children:e.name})},e.name)}):o?(0,r.jsx)(xd,{children:s("tools.noTools")}):(0,r.jsx)(xd,{children:t?s("tools.loading"):s("tools.load")})})}),(0,r.jsx)("section",{className:"tool-definition-detail","aria-label":s("tools.details"),children:d?(0,r.jsxs)("div",{className:"tool-definition-scroll",children:[d.description&&(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsx)("div",{className:"tool-definition-section-label",children:s("tools.description")}),(0,r.jsx)("div",{className:"tool-definition-description",children:d.description})]}),(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsxs)("div",{className:"tool-definition-section-label",children:[(0,r.jsx)("span",{children:s("tools.parameters")}),(0,r.jsx)("span",{children:s("tools.parameterCount",{count:c.length})})]}),c.length>0?(0,r.jsx)("div",{className:"tool-definition-fields",children:c.map(e=>(0,r.jsxs)("div",{className:"tool-definition-field",children:[(0,r.jsxs)("div",{className:"tool-definition-field-name",children:[(0,r.jsx)("code",{children:e.name}),(0,r.jsx)("span",{className:e.required?"required":void 0,children:s(e.required?"tools.required":"tools.optional")})]}),(0,r.jsxs)("div",{className:"tool-definition-field-value",children:[(0,r.jsx)("code",{className:"tool-definition-type",children:e.type}),e.description&&(0,r.jsx)("div",{children:e.description}),e.allowedValues&&(0,r.jsxs)("div",{className:"tool-definition-meta",children:[s("tools.allowedValues"),": ",(0,r.jsx)("code",{children:e.allowedValues})]}),void 0!==e.defaultValue&&(0,r.jsxs)("div",{className:"tool-definition-meta",children:[s("tools.defaultValue"),": ",(0,r.jsx)("code",{children:e.defaultValue})]})]})]},e.name))}):(0,r.jsx)("div",{className:"tool-definition-no-parameters",children:s("tools.noParameters")})]}),d.promptGuidelines&&d.promptGuidelines.length>0&&(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsx)("div",{className:"tool-definition-section-label",children:s("tools.guidelines")}),(0,r.jsx)("ul",{className:"tool-definition-guidelines",children:d.promptGuidelines.map((e,t)=>(0,r.jsx)("li",{children:e},`${d.name}:${t}`))})]})]}):(0,r.jsx)(xd,{children:o?s("tools.noTools"):t?s("tools.loading"):s("tools.load")})}),(0,r.jsx)("style",{children:`
111
+ .tool-definitions-panel {
112
+ display: grid;
113
+ grid-template-columns: clamp(112px, 26%, 220px) minmax(0, 1fr);
114
+ height: min(600px, 75dvh);
115
+ min-height: 240px;
116
+ overflow: hidden;
117
+ background: var(--bg-panel);
118
+ border-bottom: 1px solid var(--border);
119
+ }
120
+ .tool-definitions-sidebar,
121
+ .tool-definition-detail {
122
+ display: flex;
123
+ min-width: 0;
124
+ min-height: 0;
125
+ flex-direction: column;
126
+ }
127
+ .tool-definitions-sidebar {
128
+ border-right: 1px solid var(--border);
129
+ background: color-mix(in srgb, var(--bg-panel) 94%, var(--bg));
130
+ }
131
+ .tool-definitions-list,
132
+ .tool-definition-scroll {
133
+ min-height: 0;
134
+ flex: 1;
135
+ overflow: auto;
136
+ }
137
+ .tool-definitions-item {
138
+ display: flex;
139
+ width: 100%;
140
+ min-height: 38px;
141
+ align-items: center;
142
+ padding: 8px 12px;
143
+ border: none;
144
+ border-bottom: 1px solid var(--border);
145
+ background: transparent;
146
+ color: var(--text-muted);
147
+ cursor: pointer;
148
+ text-align: left;
149
+ }
150
+ .tool-definitions-item:hover {
151
+ background: var(--bg-hover);
152
+ color: var(--text);
153
+ }
154
+ .tool-definitions-item.selected {
155
+ background: var(--bg-selected);
156
+ box-shadow: inset 2px 0 0 var(--accent);
157
+ color: var(--text);
158
+ }
159
+ .tool-definitions-item code {
160
+ max-width: 100%;
161
+ color: inherit;
162
+ font-size: 11px;
163
+ font-weight: 600;
164
+ overflow-wrap: anywhere;
165
+ }
166
+ .tool-definition-scroll {
167
+ padding: 14px 16px 20px;
168
+ }
169
+ .tool-definition-section + .tool-definition-section {
170
+ margin-top: 18px;
171
+ }
172
+ .tool-definition-section-label {
173
+ display: flex;
174
+ align-items: center;
175
+ justify-content: space-between;
176
+ gap: 8px;
177
+ margin-bottom: 7px;
178
+ color: var(--text-dim);
179
+ font-size: 11px;
180
+ font-weight: 600;
181
+ }
182
+ .tool-definition-section-label > span:last-child {
183
+ font-weight: 400;
184
+ white-space: nowrap;
185
+ }
186
+ .tool-definition-description {
187
+ color: var(--text-muted);
188
+ font-size: 12px;
189
+ line-height: 1.55;
190
+ overflow-wrap: anywhere;
191
+ white-space: pre-wrap;
192
+ }
193
+ .tool-definition-fields {
194
+ border-top: 1px solid var(--border);
195
+ }
196
+ .tool-definition-field {
197
+ display: grid;
198
+ grid-template-columns: minmax(88px, 0.75fr) minmax(0, 1.5fr);
199
+ gap: 12px;
200
+ padding: 9px 0;
201
+ border-bottom: 1px solid var(--border);
202
+ font-size: 11px;
203
+ line-height: 1.45;
204
+ }
205
+ .tool-definition-field-name {
206
+ display: flex;
207
+ min-width: 0;
208
+ flex-direction: column;
209
+ gap: 3px;
210
+ color: var(--text);
211
+ }
212
+ .tool-definition-field-name code {
213
+ overflow-wrap: anywhere;
214
+ }
215
+ .tool-definition-field-name span {
216
+ color: var(--text-dim);
217
+ font-size: 10px;
218
+ }
219
+ .tool-definition-field-name span.required {
220
+ color: var(--accent);
221
+ }
222
+ .tool-definition-field-value {
223
+ min-width: 0;
224
+ color: var(--text-muted);
225
+ overflow-wrap: anywhere;
226
+ }
227
+ .tool-definition-type {
228
+ display: block;
229
+ margin-bottom: 3px;
230
+ color: var(--text);
231
+ }
232
+ .tool-definition-meta {
233
+ margin-top: 4px;
234
+ color: var(--text-dim);
235
+ }
236
+ .tool-definition-meta code {
237
+ color: var(--text-muted);
238
+ }
239
+ .tool-definition-no-parameters {
240
+ padding: 2px 0 10px;
241
+ color: var(--text-dim);
242
+ font-size: 11px;
243
+ }
244
+ .tool-definition-guidelines {
245
+ margin: 0;
246
+ padding-left: 18px;
247
+ color: var(--text-muted);
248
+ font-size: 11px;
249
+ line-height: 1.5;
250
+ }
251
+ .tool-definitions-empty {
252
+ padding: 14px 12px;
253
+ color: var(--text-muted);
254
+ font-size: 12px;
255
+ font-style: italic;
256
+ overflow-wrap: anywhere;
257
+ }
258
+ @media (max-width: 640px) {
259
+ .tool-definitions-panel {
260
+ grid-template-columns: 112px minmax(0, 1fr);
261
+ }
262
+ .tool-definitions-item {
263
+ padding: 8px 10px;
264
+ }
265
+ .tool-definition-scroll {
266
+ padding: 12px;
267
+ }
268
+ .tool-definition-field {
269
+ grid-template-columns: minmax(74px, 0.7fr) minmax(0, 1.3fr);
270
+ gap: 9px;
271
+ }
272
+ }
273
+ `})]})}let xu=["overview","context","system","tools"],xp={overview:"session.overview",context:"context.tab",system:"system.prompt",tools:"tools.title"};function xh(e){let{children:t,systemPrompt:n,tools:s,systemInfoLoading:o,onOpenSystemInfo:l,translate:a,messageSummary:d,contextUsage:c,initialTab:u="overview"}=e,[p,h]=(0,i.useState)(u),m=(0,i.useRef)({}),f=(0,i.useRef)(l);f.current=l,(0,i.useEffect)(()=>{h(u),"overview"!==u&&f.current()},[u]);let g=e=>{h(e),"overview"!==e&&l()},x=e=>{let t=xu.indexOf(p),n="ArrowRight"===e.key?(t+1)%xu.length:"ArrowLeft"===e.key?(t+xu.length-1)%xu.length:"Home"===e.key?0:"End"===e.key?xu.length-1:null;null!==n&&(e.preventDefault(),g(xu[n]),m.current[xu[n]]?.focus())};return(0,r.jsxs)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",boxShadow:"0 10px 28px rgba(0,0,0,0.10)"},children:[(0,r.jsx)("div",{className:"session-info-tabs",role:"tablist","aria-label":a("session.title"),children:xu.map(e=>(0,r.jsx)("button",{ref:t=>{m.current[e]=t},type:"button",role:"tab",id:`session-info-tab-${e}`,"aria-selected":p===e,"aria-controls":"session-info-panel",tabIndex:p===e?0:-1,className:"session-info-tab",onClick:()=>g(e),onKeyDown:x,children:a(xp[e])},e))}),(0,r.jsxs)("div",{id:"session-info-panel",role:"tabpanel","aria-labelledby":`session-info-tab-${p}`,children:["overview"===p&&(0,r.jsx)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:t}),"context"===p&&(0,r.jsx)("div",{style:{borderBottom:"1px solid var(--border)",maxHeight:"65vh",overflowY:"auto"},children:(0,r.jsx)(xo,{systemPrompt:n,tools:s,loading:o,messageSummary:d,contextUsage:c,onSelectTab:e=>g(e)})}),"system"===p&&(0,r.jsx)(xl,{loading:o,prompt:n,translate:a}),"tools"===p&&(0,r.jsx)(xc,{loading:o,tools:s,translate:a})]}),(0,r.jsx)("style",{children:`
274
+ @keyframes session-info-pop {
275
+ 0% {
276
+ opacity: 0;
277
+ transform: translateY(-24px);
278
+ filter: blur(6px);
279
+ box-shadow: 0 2px 8px rgba(0,0,0,0);
280
+ }
281
+ 55% {
282
+ opacity: 1;
283
+ transform: translateY(0);
284
+ filter: blur(0);
285
+ background: color-mix(in srgb, var(--accent) 8%, var(--bg-panel));
286
+ box-shadow: 0 18px 44px rgba(37,99,235,0.16);
287
+ }
288
+ 100% {
289
+ opacity: 1;
290
+ transform: translateY(0);
291
+ filter: blur(0);
292
+ background: var(--bg-panel);
293
+ box-shadow: 0 10px 28px rgba(0,0,0,0.10);
294
+ }
295
+ }
296
+ @keyframes session-info-light-wash {
297
+ 0% {
298
+ opacity: 0;
299
+ transform: translateX(-110%) skewX(-16deg);
300
+ }
301
+ 24% {
302
+ opacity: 0.42;
303
+ }
304
+ 100% {
305
+ opacity: 0;
306
+ transform: translateX(115%) skewX(-16deg);
307
+ }
308
+ }
309
+ .session-info-popover {
310
+ position: relative;
311
+ overflow: hidden;
312
+ transform-origin: top right;
313
+ animation: session-info-pop 360ms ease-out both;
314
+ will-change: transform, opacity, filter, background, box-shadow;
315
+ }
316
+ .session-info-popover::after {
317
+ content: "";
318
+ position: absolute;
319
+ top: 0;
320
+ bottom: 0;
321
+ left: 0;
322
+ width: 44%;
323
+ pointer-events: none;
324
+ background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--accent) 24%, transparent), transparent);
325
+ animation: session-info-light-wash 620ms ease-out both;
326
+ }
327
+ @media (prefers-reduced-motion: reduce) {
328
+ .session-info-popover,
329
+ .session-info-popover::after {
330
+ animation: none;
331
+ }
332
+ }
333
+ /* 页签:面板自己的分区用下划线(同轨迹检查器的页签),和顶栏上顶线的「对话 | 轨迹」分出层级。 */
334
+ .session-info-tabs {
335
+ display: flex;
336
+ flex: none;
337
+ box-sizing: border-box;
338
+ height: 34px;
339
+ padding: 0 8px;
340
+ gap: 1px;
341
+ overflow-x: auto;
342
+ overflow-y: hidden;
343
+ border-bottom: 1px solid var(--border);
344
+ scrollbar-width: none;
345
+ white-space: nowrap;
346
+ }
347
+ .session-info-tabs::-webkit-scrollbar {
348
+ display: none;
349
+ }
350
+ .session-info-tab {
351
+ position: relative;
352
+ flex: none;
353
+ padding: 0 10px;
354
+ border: 0;
355
+ background: transparent;
356
+ color: var(--text-muted);
357
+ cursor: pointer;
358
+ font: inherit;
359
+ font-size: 12px;
360
+ }
361
+ @media (hover: hover) {
362
+ .session-info-tab:hover {
363
+ background: var(--bg-hover);
364
+ color: var(--text);
365
+ }
366
+ }
367
+ .session-info-tab[aria-selected='true'] {
368
+ color: var(--accent);
369
+ }
370
+ .session-info-tab[aria-selected='true']::after {
371
+ content: "";
372
+ position: absolute;
373
+ right: 10px;
374
+ bottom: 0;
375
+ left: 10px;
376
+ height: 2px;
377
+ border-radius: 1px 1px 0 0;
378
+ background: var(--accent);
379
+ }
380
+ .session-info-tab:focus-visible {
381
+ outline: 1px solid var(--accent);
382
+ outline-offset: -1px;
383
+ }
384
+ `})]})}function xm(e){let{usage:t,style:n}=e,{locale:i,t:s}=(0,tn.s)(),o=lK(t.cost);return(0,r.jsxs)("span",{title:function(e,t,n){let{tokens:r}=e;return[`${t("session.totalActive")}: ${lV(e.totalActiveMs)}`,`${t("session.input")}: ${r.input.toLocaleString(n)}`,`${t("session.output")}: ${r.output.toLocaleString(n)}`,...r.cacheRead>0?[`${t("session.cacheRead")}: ${r.cacheRead.toLocaleString(n)}`]:[],...r.cacheWrite>0?[`${t("session.cacheWrite")}: ${r.cacheWrite.toLocaleString(n)}`]:[],`${t("session.total")}: ${r.total.toLocaleString(n)}`,...e.cost>0?[`${t("session.cost")}: $${e.cost.toFixed(4)}`]:[],`${t("session.toolCalls")}: ${e.toolCalls.toLocaleString(n)}`].join("\n")}(t,s,i),style:{display:"flex",alignItems:"center",gap:10,minWidth:0,color:"var(--text-dim)",fontSize:11,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap",...n},children:[t.totalActiveMs>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:3},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]}),lV(t.totalActiveMs)]}),t.tokens.total>0&&(0,r.jsx)("span",{children:s("agentSwitcher.tokens",{count:lU(t.tokens.total)})}),o&&(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:o})]})}function xf(e){return!!(e&&(e.tokens.total>0||e.totalActiveMs>0))}function xg(e){return e.name||e.firstMessage||e.id.slice(0,12)}function xx(e,t){let n=new Date(e).getTime();if(!Number.isFinite(n))return"";let r=Math.round((n-Date.now())/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:"auto"});if(60>Math.abs(r))return i.format(r,"second");let s=Math.round(r/60);if(60>Math.abs(s))return i.format(s,"minute");let o=Math.round(s/60);return 24>Math.abs(o)?i.format(o,"hour"):i.format(Math.round(o/24),"day")}function xv(e){let{status:t}=e;return"running"===t||"starting"===t?(0,r.jsxs)("svg",{className:"animate-spin",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):"failed"===t?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"m9 9 6 6M15 9l-6 6"})]}):"aborted"===t||"interrupted"===t?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M9 9h6v6H9z"})]}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"m8 12 3 3 5-6"})]})}function xb(e){let{session:t,main:n,selected:i,running:s,usage:o,onSelect:a,tabShown:d,onToggleTab:c,onNewSideChat:u,newSideChatPending:p}=e,{locale:h,t:m}=(0,tn.s)(),f=t.relation?.kind==="subagent"?t.relation:null,g=t.relation?.kind==="side",x=s?"running":f?.status??"completed",v=n?m("agentSwitcher.main"):g?l(t,m("agentSwitcher.sideChat")):f?.description||xg(t),b=g?m("agentSwitcher.sideChat"):f?.profile??m("agentSwitcher.subagent"),y=o?.model?.modelId,j=o?.thinkingLevel&&"off"!==o.thinkingLevel?o.thinkingLevel:void 0,k=n?xg(t):g?xx(t.modified,h):b,w=n?k:[b,o?.model?`${o.model.provider}/${o.model.modelId}`:void 0,j,xx(t.modified,h)].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("div",{style:{display:"flex",borderBottom:"1px solid var(--border)",borderLeft:i?"2px solid var(--accent)":"2px solid transparent",background:i?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":i,onClick:a,className:i?"bg-transparent":"bg-transparent hover:bg-bg-hover",style:{flex:1,minWidth:0,minHeight:56,display:"grid",gridTemplateColumns:"28px minmax(0, 1fr) auto",alignItems:"center",gap:9,padding:"7px 12px",border:"none",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{width:28,height:28,display:"grid",placeItems:"center",color:n?"var(--text-muted)":"var(--accent)"},children:n?(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,r.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}):g?(0,r.jsx)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"})}):(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:i?600:500},title:v,children:v}),(0,r.jsxs)("span",{style:{display:"flex",alignItems:"baseline",gap:4,marginTop:2,minWidth:0,whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},title:w,children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flexShrink:y&&!n?0:1,maxWidth:y&&!n?"40%":void 0},children:k}),!n&&y&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:y})]}),!n&&j&&(0,r.jsxs)("span",{style:{flexShrink:0},children:["\xb7 ",j]})]}),xf(o)&&(0,r.jsx)(xm,{usage:o,style:{marginTop:3}})]}),(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",gap:6,color:(n||g)&&!s?"var(--text-dim)":"running"===x||"starting"===x?"var(--accent)":"completed"===x?"#16a34a":"failed"===x?"#dc2626":"aborted"===x?"#d97706":"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},children:(n||g)&&!s?i?m("agentSwitcher.current"):null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(xv,{status:x}),(0,r.jsx)("span",{children:m(`agentSwitcher.status.${x}`)})]})})]}),u&&(0,r.jsx)(xy,{title:m("sideChat.new"),disabled:p,onClick:u,children:(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}),(0,r.jsx)("path",{d:"M13 8.5v7M9.5 12h7"})]})}),c&&(0,r.jsx)(xy,{title:m(i?"agentSwitcher.openInMainChat":d?g?"sideChat.closeTab":"subagent.closeTab":g?"sideChat.openTab":"subagent.openTab"),pressed:d,disabled:i,onClick:c,children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"M15 4v16"}),d&&(0,r.jsx)("path",{d:"M15 4h4a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-4z",fill:"currentColor"})]})})]})}function xy(e){let{title:t,pressed:n,disabled:i,onClick:s,children:o}=e,l=i?"cursor-not-allowed text-text-dim opacity-40":n?"cursor-pointer text-accent hover:bg-bg-hover":"cursor-pointer text-text-muted hover:bg-bg-hover hover:text-text";return(0,r.jsx)("button",{type:"button",onClick:s,title:t,"aria-label":t,"aria-pressed":n,disabled:i,className:`bg-transparent ${l}`,style:{width:36,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",flexShrink:0},children:o})}function xj(e){let{rootSession:t,subagents:n,selectedSessionId:s,runningSessionIds:o,onSelectSession:l,openSubagentTabIds:a,onToggleSubagentTab:d,onNewSideChat:u}=e,{t:p}=(0,tn.s)(),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)(null),b=async()=>{g(!0),v(null);try{v(await u())}catch(e){v(e instanceof Error?e.message:String(e))}finally{g(!1)}},y=(0,i.useMemo)(()=>[...n].sort((e,t)=>{let n=o.has(e.id);return n!==o.has(t.id)?n?-1:1:t.modified.localeCompare(e.modified)}),[o,n]),j=h.trim().toLowerCase(),k=j?y.filter(e=>{let t=e.relation?.kind==="subagent"?e.relation:null,n=e.relation?.kind==="side"?p("agentSwitcher.sideChat"):null;return[t?.description,t?.profile,n,e.name,e.firstMessage].some(e=>e?.toLowerCase().includes(j))}):y,w=c(n,o),S=(0,i.useMemo)(()=>[t.id,...n.map(e=>e.id)],[t.id,n]),C=S.filter(e=>o.has(e)).join(","),N=function(e,t){let[n,r]=(0,i.useState)({}),s=e.join(",");return(0,i.useEffect)(()=>{let e=s?s.split(","):[];if(0===e.length)return;let n=new AbortController,i=!1,o=async()=>{if(!i){i=!0;try{let t=await fetch("/api/sessions/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:e}),signal:n.signal,cache:"no-store"});if(!t.ok)return;let i=await t.json();!n.signal.aborted&&i.stats&&r(i.stats)}catch{}finally{i=!1}}};if(o(),!t)return()=>n.abort();let l=setInterval(()=>{"visible"===document.visibilityState&&o()},3e3);return()=>{clearInterval(l),n.abort()}},[s,t]),n}(S,C),E=(0,i.useMemo)(()=>{let e=S.map(e=>N[e]).filter(xf);if(0===e.length)return null;let t={tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,toolCalls:0,totalActiveMs:0};for(let n of e)t.tokens.input+=n.tokens.input,t.tokens.output+=n.tokens.output,t.tokens.cacheRead+=n.tokens.cacheRead,t.tokens.cacheWrite+=n.tokens.cacheWrite,t.tokens.total+=n.tokens.total,t.cost+=n.cost,t.toolCalls+=n.toolCalls,t.totalActiveMs+=n.totalActiveMs;return t},[S,N]);return(0,r.jsx)("div",{role:"listbox","aria-label":p("agentSwitcher.title"),style:{background:"var(--bg-panel)",borderLeft:"1px solid var(--border)",borderRight:"1px solid var(--border)",borderBottom:"1px solid var(--border)",borderRadius:"0 0 6px 6px",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",overflow:"hidden"},children:(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{minHeight:44,display:"flex",alignItems:"center",gap:8,padding:"7px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("strong",{style:{fontSize:12,fontWeight:600},children:p("agentSwitcher.title")}),n.length>0&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:1===n.length?p("agentSwitcher.countOne",{count:n.length}):p("agentSwitcher.count",{count:n.length})}),(0,r.jsxs)("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:10,minWidth:0},children:[E&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0,overflow:"hidden"},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},title:p("agentSwitcher.totalUsageHint"),children:p("agentSwitcher.totalUsage")}),(0,r.jsx)(xm,{usage:E})]}),w>0&&(0,r.jsx)("span",{style:{color:"var(--accent)",fontSize:11,whiteSpace:"nowrap"},children:p("agentSwitcher.runningCount",{count:w})})]})]}),n.length>8&&(0,r.jsx)("div",{style:{padding:8,borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{type:"search",value:h,onChange:e=>m(e.target.value),placeholder:p("agentSwitcher.search"),"aria-label":p("agentSwitcher.search"),style:{width:"100%",height:32,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(58dvh, 480px)",overflowY:"auto"},children:[(0,r.jsx)(xb,{session:t,main:!0,selected:t.id===s,running:o.has(t.id),usage:N[t.id],onSelect:()=>l(t),onNewSideChat:b,newSideChatPending:f}),x&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 12px",borderBottom:"1px solid var(--border)",color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:x}),k.map(e=>(0,r.jsx)(xb,{session:e,selected:e.id===s,running:o.has(e.id),usage:N[e.id],onSelect:()=>l(e),tabShown:a.has(e.id),onToggleTab:()=>{let t=e.relation?.kind==="subagent"?e.relation:null;e.relation?.kind==="side"?d(e.id,p("sideChat.title"),!0):d(e.id,t?.description||t?.profile||xg(e))}},e.id)),n.length>0&&0===k.length&&(0,r.jsx)("div",{style:{padding:"22px 12px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:p("agentSwitcher.noMatches")})]})]})})}let xk={idle:"debug.stream.state.idle",connecting:"debug.stream.state.connecting",connected:"debug.stream.state.connected",retrying:"debug.stream.state.retrying"},xw={ready_timeout:"debug.stream.error.readyTimeout",startup_error:"debug.stream.error.startup",error:"debug.stream.error.error",stale:"debug.stream.error.stale"},xS={visible:"debug.stream.reattach.visible",activity:"debug.stream.reattach.activity"},xC={agent:"debug.page.source.agent","file-watch":"debug.page.source.fileWatch",terminal:"debug.page.source.terminal"},xN={connecting:"debug.page.source.connecting",open:"debug.page.source.open"},xE={reply:"debug.lease.outcome.reply",unanswered:"debug.lease.outcome.unanswered",error:"debug.lease.outcome.error"},xI={alive:"debug.state.alive",closing:"debug.state.closing",none:"debug.state.none"},x$={timeout:"debug.poll.timeout",http:"debug.poll.http",network:"debug.poll.network",invalid:"debug.poll.invalid"},xT={starting:"agentSwitcher.status.starting",queued:"debug.run.status.queued",running:"agentSwitcher.status.running",completed:"agentSwitcher.status.completed",failed:"agentSwitcher.status.failed",aborted:"agentSwitcher.status.aborted",interrupted:"agentSwitcher.status.interrupted",unknown:"debug.unknown"},xM={released:"debug.stream.close.released",grace_end:"debug.stream.close.graceEnd",send_failed:"debug.stream.close.sendFailed",set_tools:"debug.stream.close.setTools",rebuilt:"debug.stream.close.rebuilt",deselected:"debug.stream.close.deselected",stuck:"debug.stream.close.stuck",replaced:"debug.stream.close.replaced"};function xR(e,t,n){return Object.prototype.hasOwnProperty.call(t,e)?n(t[e]):e}function xA(e){return Number.isFinite(e)?Math.max(0,e):0}function xL(e){return String(e).padStart(2,"0")}function xz(e,t){let n=xA(e);return n<1e3?t("debug.duration.ms",{count:Math.floor(n)}):n<6e4?t("debug.duration.seconds",{count:Math.floor(n/1e3)}):n<36e5?t("debug.duration.minutesSeconds",{minutes:Math.floor(n/6e4),seconds:xL(Math.floor(n%6e4/1e3))}):n<864e5?t("debug.duration.hoursMinutes",{hours:Math.floor(n/36e5),minutes:xL(Math.floor(n%36e5/6e4))}):t("debug.duration.daysHours",{days:Math.floor(n/864e5),hours:Math.floor(n%864e5/36e5)})}function xP(e,t){return t("debug.time.ago",{time:xz(e,t)})}function xW(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"floor",r=Math[n](xA(e)/1e3);return r<60?t("debug.duration.seconds",{count:r}):xz(1e3*r,t)}function xO(e,t){return e>0?t("debug.time.in",{time:xW(e,t,"ceil")}):t("debug.time.due")}function xF(e,t){return e>0?t("debug.time.in",{time:xz(e,t)}):t("debug.time.due")}function xD(e){return e.length>8?e.slice(0,8):e}function xB(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function xH(e){return"number"==typeof e&&Number.isFinite(e)}function x_(e){var t;return xB(e)&&"string"==typeof e.sessionId&&"string"==typeof e.state&&xH(e.eventStreams)&&(null===(t=e.nextIdleCheckAt)||xH(t))}function xU(e,t){try{return e()}catch{return t}}function xK(e){if(!e)return{client:null,failed:!1};try{return{client:e()??null,failed:!1}}catch{return{client:null,failed:!0}}}function xq(e,t){return e?.sessionId??t}let xV={sessionId:null,reply:null,receivedAt:null,roundTripMs:null,failure:null,requests:0,failures:0,consecutiveFailures:0},xZ=e=>e.filter(Boolean).join(" \xb7 ");function xJ(e,t,n){return null===e?n("debug.holder.none"):`${n(e===t?"debug.holder.thisPage":"debug.holder.otherPage")} ${xD(e)}`}function xG(e,t){let n=e.filter(e=>null!==e.holder&&e.holder===t);return[...n,...e.filter(e=>!n.includes(e))]}let xY={running:"debug.overlay.running",awaiting:"debug.overlay.awaiting",alive:"debug.state.alive",closing:"debug.state.closing",none:"debug.state.none",starting:"debug.server.starting"};function xX(e){return e.awaitingInput?"awaiting":e.running?"running":e.state}function xQ(e,t){return null===e.label?"—":"agent"===e.kind?t?.(e.label)??xD(e.label):q(e.label)}function x0(e,t){if(!(t>0))return null;let n=e/t;return Number.isFinite(n)?Math.min(1,Math.max(0,n)):0}function x1(e,t){if(!e||"connected"!==e.state||!e.watchdogArmed)return null;let n=e.staleAfterMs;return null!==n&&n>0&&null!==e.lastSeenAt?{ageMs:Math.max(0,t-e.lastSeenAt),staleAfterMs:n}:null}function x2(e,t){return t>0?e>=t?"error":e>=t/2?"warning":"dim":"dim"}let x4={poll:[],running:[]};function x8(e){let t=xA(e);return{ms:t,tone:t>=2e3?"warning":"dim",failed:!1}}function x3(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:30,r=[...e,t];return r.length>n?r.slice(r.length-n):r}function x5(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:-1/0}function x6(e,t){return e===t?0:t>e?1:-1}class x9 extends i.Component{static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e){console.error("Debug panel failed:",e)}render(){return this.state.failed?(0,r.jsx)("div",{role:"status",style:{padding:"10px 16px",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",color:"var(--text-muted)",fontSize:12},children:this.props.fallback}):this.props.children}constructor(...e){super(...e),this.state={failed:!1}}}function x7(e){let{readerRef:t,selectedSessionId:n,sessions:s,onClose:o}=e,{t:l}=(0,tn.s)(),a=(0,i.useRef)(n);a.current=n;let d=(0,i.useRef)(o);d.current=o;let c=(0,i.useRef)(null),u=(0,i.useRef)(!1),p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(xV),[b,y]=(0,i.useState)(x4),[j,k]=(0,i.useState)(!1),[w,S]=(0,i.useState)(null),C=(0,i.useRef)({page:f,server:x,samples:b});C.current={page:f,server:x,samples:b},(0,i.useEffect)(()=>{let e=h.current;if(!e)return;let t=null,n=n=>{if("mouse"!==n.pointerType)return;let r=n.target instanceof Element?n.target.closest("[title]"):null,i=r&&e.contains(r)?r:null;i!==t&&(t=i,S(i?C.current:null))},r=()=>{t=null,S(null)};return e.addEventListener("pointerover",n),e.addEventListener("pointerleave",r),()=>{e.removeEventListener("pointerover",n),e.removeEventListener("pointerleave",r)}},[]),(0,i.useEffect)(()=>{var e;let n,r,i,s,o,l,d,h,f;u.current=!1;let x=(r=(e={fetch:(e,t)=>fetch(e,t),sessionId:()=>xq(xK(t.current).client,a.current),isVisible:()=>"visible"===document.visibilityState,onReading:e=>{v(e);let t=function(e){if(e.failure){let t="timeout"===e.failure.kind;return{ms:5e3*!!t,tone:t?"warning":"error",failed:!0}}return null===e.roundTripMs?null:x8(e.roundTripMs)}(e);t&&y(e=>({...e,poll:x3(e.poll,t)}))}}).now??(()=>Date.now()),i=e.setTimeout??((e,t)=>setTimeout(e,t)),s=e.clearTimeout??(e=>clearTimeout(e)),o=!1,l=null,d=xV,h=async t=>{let a=new AbortController,c={sessionId:t,controller:a,startedAt:r()};l=c,n=t;let u=!1,p=i(()=>{u=!0,a.abort()},5e3),h=null,m=null;try{var f,g;let n=await e.fetch(t?`/api/agent/debug?session=${encodeURIComponent(t)}`:"/api/agent/debug",{cache:"no-store",signal:a.signal});if(n.ok){let e=null;try{e=await n.json()}catch(e){if(a.signal.aborted)throw e}(f=e,xB(f)&&xH(f.now)&&xB(g=f.server)&&xH(g.startedAt)&&xB(g.wrappers)&&xB(g.eventStreams)&&xH(g.sseTotal)&&Array.isArray(g.pages)&&xB(g.terminals)&&Array.isArray(f.sessions)&&f.sessions.every(x_)&&(null===f.session||function(e){if(!xB(e)||"string"!=typeof e.sessionId)return!1;let t=e.wrapper,n=e.subagents,r=e.mcp;return(null===t||xB(t)&&"string"==typeof t.state&&xB(t.run)&&xB(t.idle))&&(null===e.lifecycle||xB(e.lifecycle))&&(null===e.providers||Array.isArray(e.providers))&&Array.isArray(e.eventStreams)&&xB(n)&&Array.isArray(n.runs)&&Array.isArray(n.notifications)&&(null===r||xB(r)&&Array.isArray(r.servers))}(f.session)))?h=e:m={kind:"invalid",status:n.status}}else m={kind:"http",status:n.status}}catch{m={kind:u?"timeout":"network",status:null}}finally{s(p),l===c&&(l=null)}if(o||a.signal.aborted&&!u||e.sessionId()!==t)return;let x=r(),v=d.sessionId===t;d=h?{sessionId:t,reply:h,receivedAt:x,roundTripMs:Math.max(0,x-c.startedAt),failure:null,requests:d.requests+1,failures:d.failures,consecutiveFailures:0}:{sessionId:t,reply:v?d.reply:null,receivedAt:v?d.receivedAt:null,roundTripMs:v?d.roundTripMs:null,failure:{...m??{kind:"invalid",status:null},at:x},requests:d.requests+1,failures:d.failures+1,consecutiveFailures:d.consecutiveFailures+1},e.onReading(d)},{poll:f=()=>{if(o||!e.isVisible())return;let t=e.sessionId();if(l){if(l.sessionId===t)return;l.controller.abort()}h(t)},sync(){o||(l?l.sessionId:n)!==e.sessionId()&&f()},inFlightSince:()=>l?.startedAt??null,dispose(){o=!0,l?.controller.abort(),l=null}});c.current=x;let b=()=>{let e=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),{client:r,failed:i}=xK(e);return{at:n,client:r,clientFailed:i,sources:xU(eZ,[]),visibility:xU(eY,null),protocol:xU(e0,null),runningPoll:xU(eQ,null),pollInFlightSince:t}}(t.current,x.inFlightSince());g(e);let n=e.runningPoll?.last??null;if(n&&n.at!==m.current){m.current=n.at;let e=n&&"aborted"!==n.outcome?"error"===n.outcome?{ms:xA(n.durationMs),tone:"error",failed:!0}:x8(n.durationMs):null;e&&y(t=>({...t,running:x3(t.running,e)}))}};b(),x.poll();let j=window.setInterval(()=>{"visible"===document.visibilityState&&(b(),x.sync())},1e3),k=window.setInterval(()=>x.poll(),2e3),w=()=>{"visible"===document.visibilityState&&(b(),x.poll())};return document.addEventListener("visibilitychange",w),()=>{u.current=!0,x.dispose(),c.current=null,window.clearInterval(j),window.clearInterval(k),document.removeEventListener("visibilitychange",w),p.current&&clearTimeout(p.current)}},[t]),(0,i.useEffect)(()=>{c.current?.sync()},[n]),(0,i.useEffect)(()=>{var e,t,n;let r=(e=document,t=()=>h.current,n=e=>d.current(e),r=>{var i;if(i=null!==e.querySelector('[aria-modal="true"]'),"Escape"!==r.key||r.defaultPrevented||r.cancelBubble||r.isComposing||229===r.keyCode||i)return;r.preventDefault();let s=e.activeElement;n(!!(s&&t()?.contains(s)))});return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[]);let N=w??{page:f,server:x,samples:b};return(0,r.jsx)(ve,{page:N.page,server:N.server,samples:N.samples,selectedSessionId:n,sessions:s,copied:j,onCopy:()=>{let e={client:f,server:x.reply};(0,ia.D)(JSON.stringify(e,null,2)).then(()=>{u.current||(p.current&&clearTimeout(p.current),k(!0),p.current=setTimeout(()=>k(!1),1400))},()=>{})},t:l,sectionRef:h})}function ve(e){var t;let n,{page:s,server:o,samples:l=x4,selectedSessionId:a,sessions:d,copied:c,onCopy:u,t:p,sectionRef:h}=e,m=s?.at??o.receivedAt??0,f=s?.client??null,x=xq(f,a),v=o.reply,b=v&&null!==o.receivedAt?(t=v.now,n=Math.max(0,m-o.receivedAt),{remaining:e=>e-t-n,age:e=>t-e+n}):null,y=v?.session&&v.session.sessionId===x?v.session:null,j=f?.pageId??null,k=(0,i.useMemo)(()=>new Map(d.map(e=>[e.id,e])),[d]),w=(0,i.useMemo)(()=>e=>{let t=k.get(e);return t?nq(t):null},[k]),S=(0,i.useMemo)(()=>v?function(e,t,n){let r=e=>{let n=e,r=new Set([e.id]);for(let i=0;i<32;i++){let i=n.relation;if(i?.kind!=="subagent")break;let s=t.get(i.parentSessionId);if(!s)break;if(r.has(s.id))return e;r.add(s.id),n=s}return n},i=new Map,s=[];for(let n of e){let e=t.get(n.sessionId);if(!e){s.push(n);continue}let o=r(e),l=i.get(o.id);l||(l={root:o,summary:null,subagents:[]},i.set(o.id,l)),o.id===e.id?l.summary=n:l.subagents.push({info:e,summary:n})}let o=null===n?void 0:t.get(n),l=o?r(o).id:null,a=(e,t)=>x6(x5(e.root),x5(t.root)),d=(e,t)=>Number(t.root.id===l)-Number(e.root.id===l),c=new Map;for(let e of i.values()){let t=g(e.root),n=c.get(t);n||(n={key:t,name:q(e.root.projectRoot??e.root.cwd),families:[]},c.set(t,n)),n.families.push(e)}let u=e=>Math.max(...e.families.map(e=>x5(e.root))),p=e=>e.families.some(e=>e.root.id===l),h=[...c.values()].sort((e,t)=>Number(p(t))-Number(p(e))||x6(u(e),u(t))).map(e=>{let t=[];for(let r of[...e.families].sort(a).sort(d))for(let{info:e,summary:i}of(t.push({id:r.root.id,depth:0,info:r.root,summary:r.summary,current:r.root.id===n,placeholder:null===r.summary}),[...r.subagents].sort((e,t)=>x6(x5(e.info),x5(t.info)))))t.push({id:e.id,depth:1,info:e,summary:i,current:e.id===n,placeholder:!1});return{key:e.key,name:e.name,rows:t}});if(s.length>0){let e=null!==n&&!o&&s.some(e=>e.sessionId===n),t=(e,t)=>e<t?-1:+(e>t),r={key:"\0unlisted",name:null,rows:[...s].sort((e,r)=>Number(r.sessionId===n)-Number(e.sessionId===n)||t(xD(e.sessionId),xD(r.sessionId))||t(e.sessionId,r.sessionId)).map(e=>({id:e.sessionId,depth:0,info:null,summary:e,current:e.sessionId===n,placeholder:!1}))};e?h.unshift(r):h.push(r)}return h}(v.sessions,k,x):null,[v,k,x]),C=s?function(e){let{page:t,server:n,detail:r,t:i,titleOf:s}=e,o=t.at,l=[],a=(e,t,n)=>{l.push({id:e,tone:t,text:xZ(n)})},d=n.failure;d?a("poll","timeout"===d.kind?"warning":"error",[i(x$[d.kind],{status:d.status??"?"}),xP(o-d.at,i)]):null!==t.pollInFlightSince&&o-t.pollInFlightSince>=2e3&&a("poll","warning",[i("debug.poll.inFlight",{time:xz(o-t.pollInFlightSince,i)})]),t.clientFailed&&a("reader","error",[i("debug.stream.readerFailed")]);let c=t.runningPoll?.last??null;c?.outcome==="error"&&a("runningPoll","warning",[i("debug.page.runningPoll"),i("debug.page.poll.error"),null!==c.httpStatus&&`HTTP ${c.httpStatus}`,xP(o-c.at,i)]);let u=t.sources.filter(e=>"open"===e.state).length;"http/1.1"===t.protocol&&u>=5&&a("pool",u>=6?"error":"warning",[i("debug.issue.pool",{count:u})]);let p=t.client,h=p?.connection??null,m=h?.sessionId??null;for(let e of t.sources)"connecting"===e.state&&0!==e.errors&&("agent"!==e.kind||null===m||e.label!==m)&&a("source","warning",[i(xC[e.kind]),xQ(e,s),i("debug.page.source.connecting"),i("debug.page.sourceCounts",{opens:e.opens,errors:e.errors})]);if(h){let e=null!==h.retryDueAt&&i("debug.stream.retryDue",{time:xF(h.retryDueAt-o,i)}),t=h.lastError;t&&"connected"!==h.state&&!(h.lastClose&&h.lastClose.at>=t.at)?a("stream","error",[xR(t.reason,xw,i),t.message,xP(o-t.at,i),e]):"retrying"===h.state&&a("stream","warning",[i(xk.retrying),e]);let n=x1(h,o),r=n?x2(n.ageMs,n.staleAfterMs):"dim";n&&"dim"!==r&&a("streamSilent",r,[`${i("debug.stream.lastData")} ${xP(n.ageMs,i)}`])}let f=p?.pageId??null,g=null!==n.receivedAt?n.receivedAt-(n.roundTripMs??0):null;for(let e of(r&&f&&h&&null!==g&&"connected"===h.state&&h.sessionId===r.sessionId&&null!==h.connectedAt&&h.connectedAt<g&&!r.eventStreams.some(e=>e.holder===f)&&a("noServerStream","warning",[i("debug.issue.noServerStream")]),r?.eventStreams??[]))e.droppedEvents>0&&a("dropped","warning",[xJ(e.holder,f,i),i("debug.server.dropped",{count:e.droppedEvents})]);let x=p?.lease??null;if(x){let e=x.last;null!==x.inFlightSince&&o-x.inFlightSince>=2e3?a("lease","warning",[i("debug.section.lease"),i("debug.lease.inFlight",{time:xz(o-x.inFlightSince,i)})]):e?.outcome==="error"?a("lease","error",[i("debug.section.lease"),i(xE.error),null!==e.httpStatus&&`HTTP ${e.httpStatus}`,xP(o-e.at,i)]):e?.outcome==="unanswered"&&a("lease","warning",[i("debug.section.lease"),i(xE.unanswered),xP(o-e.at,i)])}let v=r?.wrapper??null;for(let e of(v&&!v.stale&&"failed"===v.extensions&&a("extensions","error",[i("debug.server.extensions"),i("debug.server.extensions.failed")]),r?.providers??[]))"error"===e.active&&a("provider","error",[e.name,i("debug.server.providerError")]);for(let e of r?.mcp?.servers??[])(e.hasError||"failed"===e.state||"conflict"===e.state)&&a("mcp","error",[`MCP ${e.name}`,xR(e.state,pg,i)]);return l.sort((e,t)=>Number("error"===t.tone)-Number("error"===e.tone))}({page:s,server:o,detail:y,t:p,titleOf:w}):[],N=null===s?{kind:"reading",tone:"dim",count:0}:s.visibility?.state==="hidden"?{kind:"hidden",tone:"dim",count:0}:C.length>0?{kind:"issues",tone:C.some(e=>"error"===e.tone)?"error":"warning",count:C.length}:null===o.receivedAt?{kind:"waiting",tone:"dim",count:0}:{kind:"ok",tone:"ok",count:0},E={t:p,now:m,clock:b,myHolder:j,titleOf:w};return(0,r.jsxs)("section",{ref:h,className:"debug-panel","aria-label":p("debug.panelLabel"),children:[(0,r.jsxs)("div",{className:"debug-panel-header",children:[(0,r.jsx)("span",{className:"debug-panel-heading",title:p("debug.readOnly"),children:p("debug.title")}),(0,r.jsx)(vp,{verdict:N,t:p}),(0,r.jsx)("button",{type:"button",className:"debug-panel-copy",onClick:u,title:p("debug.copyTitle"),children:p(c?"debug.copied":"debug.copyJson")})]}),null!==s&&(0,r.jsxs)("div",{className:"debug-panel-scroll",children:[C.length>0&&(0,r.jsx)(vh,{issues:C}),(0,r.jsxs)("div",{className:"debug-cols",children:[(0,r.jsx)(vg,{page:s,samples:l,reply:v,ctx:E}),(0,r.jsxs)("div",{className:"debug-col debug-col-server",children:[(0,r.jsx)(vS,{reply:v,ctx:E}),(0,r.jsx)(vC,{reply:v,ctx:E})]}),(0,r.jsx)("div",{className:"debug-col debug-col-sessions",children:(0,r.jsx)(vN,{reply:v,detail:y,groups:S,targetSessionId:x,sources:s.sources,ctx:E})})]})]}),(0,r.jsx)("style",{children:vF})]})}function vt(e){let{kind:t,size:n=12}=e;return(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:["server"===t&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"8",rx:"2"}),(0,r.jsx)("rect",{x:"3",y:"13",width:"18",height:"8",rx:"2"}),(0,r.jsx)("path",{d:"M7 7h.01M7 17h.01"})]}),"warning"===t&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),"error"===t&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M15 9l-6 6M9 9l6 6"})]})]})}function vn(e,t){return["debug-badge",t,`is-${e.tone}`,e.filled&&"is-filled",e.dashed&&"is-dashed",e.faded&&"is-faded"].filter(Boolean).join(" ")}function vr(e){let{text:t,items:n,cap:i,label:s,plain:o=!1}=e;return 0===n.length?null:(0,r.jsxs)("span",{className:"debug-run",title:s,...o?{}:{role:"img","aria-label":s},children:[n.slice(0,i).map((e,n)=>(0,r.jsx)("span",{className:vn(e,void 0!==e.text?"is-name":void 0),title:e.title,children:e.text??t},n)),n.length>i&&(0,r.jsx)("span",{className:"debug-run-more",children:`+${n.length-i}`})]})}let vi={Chrome:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M21.17 8H12M3.95 6.06 8.54 14M10.88 21.94 15.46 14"})]}),Safari:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("path",{d:"M16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88z"})]}),Firefox:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("path",{d:"M12 17a3.5 3.5 0 0 0 3.5-3.5c0-2.5-2-3.5-2.5-6-1.5 1.5-1 3-2 3.5-.5-.5-1-1-1-2-1.5 1-1.5 2.5-1.5 4.5A3.5 3.5 0 0 0 12 17z"})]}),Edge:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M21 12a9 9 0 1 0-4.5 7.8"}),(0,r.jsx)("path",{d:"M7 13.5c0-3 2.5-5 5.5-5 2.5 0 4.5 1.5 4.5 3.5 0 1.3-1 2-2.5 2H10"})]}),Opera:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("ellipse",{cx:"12",cy:"12",rx:"4",ry:"7"})]}),macOS:(0,r.jsx)(vs,{}),iOS:(0,r.jsx)(vs,{}),Windows:(0,r.jsx)("path",{fill:"currentColor",stroke:"none",d:"M0 0h11.377v11.372H0zm12.623 0H24v11.372H12.623zM0 12.623h11.377V24H0zm12.623 0H24V24H12.623z"}),Android:(0,r.jsx)("path",{d:"M4.5 18a7.5 7.5 0 0 1 15 0zM8 12 6.5 9.5M16 12l1.5-2.5M9.5 15h.01M14.5 15h.01"}),Linux:(0,r.jsx)("path",{d:"m4 17 6-5-6-5M12 19h8"}),ChromeOS:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"12",rx:"2"}),(0,r.jsx)("path",{d:"M2 20h20"})]})};function vs(){return(0,r.jsx)("path",{fill:"currentColor",stroke:"none",d:"M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"})}function vo(e){let{client:t}=e,n=t?t.split(" \xb7 ").filter(e=>e in vi):[];return 0===n.length?null:(0,r.jsx)("span",{className:"debug-client","aria-hidden":"true",children:n.map(e=>(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.2,strokeLinecap:"round",strokeLinejoin:"round",children:vi[e]},e))})}function vl(e){let{tone:t,ring:n=!1}=e;return(0,r.jsx)("span",{className:`debug-dot is-${t}${n?" is-ring":""}`,"aria-hidden":"true"})}function va(e){let{tone:t,children:n,title:i}=e;return(0,r.jsx)("span",{className:`debug-chip is-${t}`,title:i,children:n})}function vd(e){let{fraction:t,tone:n,width:i,height:s=4,notches:o,title:l,className:a}=e;return(0,r.jsxs)("span",{className:`debug-bar is-${n}${a?` ${a}`:""}`,style:{width:i,height:s},title:l,"aria-hidden":"true",children:[(0,r.jsx)("span",{className:"debug-bar-fill",style:{width:`${100*t}%`}}),o?.map(e=>(0,r.jsx)("span",{className:"debug-bar-notch",style:{left:`${100*e}%`}},e))]})}function vc(e){let{samples:t,label:n}=e,i=t.slice(-30);return(0,r.jsx)("span",{className:"debug-spark",role:"img","aria-label":n,title:n,children:(0,r.jsxs)("svg",{width:"120",height:"15",viewBox:"0 0 120 15","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"0",y:"14",width:"120",height:"1",style:{fill:"var(--border)"}}),i.map((e,t)=>{let n=e.failed?14:Math.max(1,Math.round(14*Math.min(1,Math.max(.08,Math.sqrt(xA(e.ms)/5e3)))));return(0,r.jsx)("rect",{className:`is-${e.tone}`,x:120-(i.length-t)*4+1,y:14-n,width:"3",height:n,fill:"currentColor"},t)})]})})}function vu(e){let{state:t,label:n}=e;return"awaiting"===t?(0,r.jsx)("span",{className:"debug-status",children:(0,r.jsx)("span",{className:"session-tree-awaiting",role:"img","aria-label":n,title:n})}):"running"===t?(0,r.jsx)("span",{className:"debug-status is-accent",title:n,children:(0,r.jsx)(nK,{size:12,label:n})}):(0,r.jsx)("span",{className:"debug-status",role:"img","aria-label":n,title:n,children:(0,r.jsx)("span",{className:`debug-status-ring is-${t}`})})}function vp(e){let{verdict:t,t:n}=e,i=({reading:()=>n("debug.reading"),hidden:()=>n("debug.poll.hidden"),issues:()=>n("debug.health.issues",{count:t.count}),waiting:()=>n("debug.poll.waiting"),ok:()=>n("debug.health.ok")})[t.kind]();return(0,r.jsxs)("span",{className:`debug-panel-status is-${"ok"===t.kind?"muted":t.tone}`,children:["issues"===t.kind&&(0,r.jsx)(vt,{kind:"error"===t.tone?"error":"warning"}),"ok"===t.kind&&(0,r.jsx)(vl,{tone:"ok"}),("hidden"===t.kind||"waiting"===t.kind)&&(0,r.jsx)(vl,{tone:"dim",ring:!0}),(0,r.jsx)("span",{className:"debug-panel-status-text",children:i})]})}function vh(e){let{issues:t}=e;return(0,r.jsx)("ul",{className:"debug-issues",children:t.map((e,t)=>(0,r.jsxs)("li",{className:`debug-issue is-${e.tone}`,children:[(0,r.jsx)(vt,{kind:e.tone}),(0,r.jsx)("span",{className:"debug-issue-text",children:e.text})]},`${e.id}:${t}`))})}function vm(e,t){let n=function(e){let t=e.filter(e=>!e.failed).map(e=>e.ms).sort((e,t)=>e-t);if(0===t.length)return{count:0,median:0,max:0};let n=Math.floor(t.length/2),r=t.length%2==1?t[n]:(t[n-1]+t[n])/2;return{count:t.length,median:r,max:t[t.length-1]}}(e);return 0===n.count?t("debug.notYet"):t("debug.spark.title",{count:n.count,median:xz(n.median,t),max:xz(n.max,t)})}function vf(e){let{samples:t,t:n}=e,i=t[t.length-1];return i?(0,r.jsx)("span",{className:`debug-value is-${i.tone}`,children:i.failed?"—":xz(i.ms,n)}):(0,r.jsx)("span",{className:"debug-value is-dim",children:"—"})}function vg(e){let{page:t,samples:n,reply:i,ctx:s}=e,{t:o}=s,l=function(e,t,n){let r=[...e].sort((e,t)=>e.createdAt-t.createdAt).map(e=>({id:e.id,kind:e.kind,label:e.label,chat:"agent"===e.kind&&null!==n&&e.label===n,connecting:"connecting"===e.state,opens:e.opens,errors:e.errors,createdAt:e.createdAt})),i="http/1.1"===t?6:null,s=r.length,o=r.filter(e=>!e.connecting).length,l={agent:0,"file-watch":0,terminal:0};for(let e of r)l[e.kind]=(l[e.kind]??0)+1;return{protocol:t,cap:i,slots:null===i?r:r.slice(0,i),mine:s,overflow:null===i?0:Math.max(0,s-i),kinds:l,tone:null===i?"dim":o>=i?"error":o>=i-1?"warning":"dim"}}(t.sources,t.protocol,t.client?.connection?.sessionId??null),a=t.runningPoll;return(0,r.jsxs)("div",{className:"debug-col debug-col-page",children:[(0,r.jsx)("div",{className:"debug-col-head",children:(0,r.jsx)("span",{className:"debug-section-title",children:o("debug.section.page")})}),(0,r.jsx)(vx,{pool:l,ctx:s}),(0,r.jsxs)("div",{className:"debug-measures",children:[(0,r.jsx)("span",{className:"debug-measure-name",children:(0,r.jsx)("span",{className:"debug-label",children:o("debug.page.debugPoll")})}),(0,r.jsx)(vc,{samples:n.poll,label:vm(n.poll,o)}),(0,r.jsx)(vf,{samples:n.poll,t:o}),(0,r.jsx)("span",{className:"debug-measure-name",children:(0,r.jsx)("span",{className:"debug-label",children:o("debug.page.runningPoll")})}),(0,r.jsx)(vc,{samples:n.running,label:xZ([a&&o("debug.page.pollCounts",{count:a.count,failures:a.failures}),vm(n.running,o)])}),(0,r.jsx)(vf,{samples:n.running,t:o}),(0,r.jsx)(vj,{page:t,reply:i,ctx:s}),(0,r.jsx)(vw,{page:t,ctx:s})]})]})}function vx(e){let{pool:t,ctx:n}=e,{t:i,now:s,titleOf:o}=n,l=Object.keys(xC).filter(e=>t.kinds[e]>0).map(e=>`${i(xC[e])} ${t.kinds[e]}`),a=null!==t.cap?xZ([`${i("debug.page.http1",{protocol:t.protocol??""})} \xb7 ${t.mine}/${t.cap}`,...l]):xZ([i("debug.section.page"),...l,t.protocol??i("debug.unknown")]),d=null!==t.cap?Array.from({length:t.cap},(e,n)=>t.slots[n]??null):t.slots;return(0,r.jsxs)("div",{className:"debug-meter-row",children:[(0,r.jsxs)("span",{className:`debug-meter${null===t.cap?" is-inline":""}`,role:"img","aria-label":a,title:a,children:[d.map((e,t)=>e?(0,r.jsx)("span",{className:vn({tone:e.connecting?"warning":e.chat?"accent":"muted",filled:e.chat,dashed:e.connecting},"debug-slot"),title:xZ([i(xC[e.kind]),xQ(e,o),i(xN[e.connecting?"connecting":"open"]),i("debug.page.sourceCounts",{opens:e.opens,errors:e.errors}),xP(s-e.createdAt,i)]),children:"agent"===e.kind?"SSE":i(vv[e.kind])},e.id):(0,r.jsx)("span",{className:"debug-slot is-empty"},`empty:${t}`)),t.overflow>0&&(0,r.jsx)("span",{className:"debug-meter-overflow is-error",children:`+${t.overflow}`})]}),null===t.cap&&null!==t.protocol&&(0,r.jsx)(va,{tone:"dim",children:t.protocol})]})}let vv={"file-watch":"debug.box.file",terminal:"debug.box.terminal"},vb={connected:{tone:"ok",ring:!1},connecting:{tone:"warning",ring:!0},retrying:{tone:"warning",ring:!1},idle:{tone:"dim",ring:!0}};function vy(e,t,n,r){let i=n.at,s=[null!==t.readyState&&r("debug.stream.readyState",{value:t.readyState}),null!==t.openedAt&&`${r("debug.stream.opened")} ${xP(i-t.openedAt,r)}`,null!==t.connectedAt&&`${r("debug.stream.connected")} ${xP(i-t.connectedAt,r)}`,`${r("debug.stream.opens")} ${r("debug.stream.opensRetries",{opens:t.opens,retries:t.retries})}`,null!==t.lastError&&`${r("debug.stream.lastError")} ${xZ([xR(t.lastError.reason,xw,r),t.lastError.message,xP(i-t.lastError.at,r)])}`,null!==t.lastClose&&`${r("debug.stream.lastClose")} ${xZ([t.lastClose.reason?xR(t.lastClose.reason,xM,r):"—",xP(i-t.lastClose.at,r)])}`,`${r("debug.stream.wanted")} ${r(e.wantsStream?"debug.yes":"debug.no")}`],o=n.visibility;return o&&o.hiddenCount>0&&s.push(xZ([r("debug.page.hiddenCount",{count:o.hiddenCount}),null!==o.lastHiddenAt&&r("debug.page.lastHidden",{time:xP(i-o.lastHiddenAt,r)})])),e.released.count>0&&s.push(`${r("debug.stream.released")} ${xZ([r("debug.times",{count:e.released.count}),null!==e.released.lastAt&&xP(i-e.released.lastAt,r)])}`),e.reattached.count>0&&s.push(`${r("debug.stream.reattached")} ${xZ([r("debug.times",{count:e.reattached.count}),null!==e.reattached.lastAt&&xP(i-e.reattached.lastAt,r),e.reattached.lastReason&&r(xS[e.reattached.lastReason])])}`),s.filter(Boolean).join("\n")}function vj(e){let{page:t,reply:n,ctx:i}=e,{t:s,now:o}=i,l=t.client,a=l?.connection??null,d=(0,r.jsx)("span",{className:"debug-measure-name",title:l&&a?vy(l,a,t,s):void 0,children:(0,r.jsx)("span",{className:"debug-label",children:s("debug.section.stream")})});if(!l||!a)return(0,r.jsxs)(r.Fragment,{children:[d,(0,r.jsx)("span",{className:"debug-measure-empty",children:l?s("debug.stream.noConnection"):t.clientFailed?"—":s("debug.stream.noChat")})]});let c=x1(a,o),u=vb[a.state];return(0,r.jsxs)(r.Fragment,{children:[d,c?(0,r.jsx)(vk,{connection:a,freshness:c,heartbeatMs:n?.server.heartbeatMs??0,ctx:i}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{className:"debug-value is-dim",children:"—"})]}),(0,r.jsxs)("span",{className:"debug-measure-sub",title:vy(l,a,t,s),children:[(0,r.jsx)(vl,{tone:u?.tone??"dim",ring:u?.ring??!0}),xZ([s(xk[a.state]??"debug.unknown"),`${s("debug.stream.events")} ${a.events}`,a.retries>0&&`${s("debug.stream.opens")} ${s("debug.stream.opensRetries",{opens:a.opens,retries:a.retries})}`])]}),(l.released.active||null!==l.graceDueAt)&&(0,r.jsxs)("span",{className:"debug-measure-sub debug-chips",children:[l.released.active&&(0,r.jsx)(va,{tone:"accent",children:s("debug.stream.close.released")}),null!==l.graceDueAt&&(0,r.jsx)(va,{tone:"accent",children:`${s("debug.stream.grace")} ${xO(l.graceDueAt-o,s)}`})]})]})}function vk(e){let{connection:t,freshness:n,heartbeatMs:i,ctx:s}=e,{t:o,now:l}=s,{ageMs:a,staleAfterMs:d}=n,c=x2(a,d),u=[];if(i>0)for(let e=i;e<d&&u.length<12;e+=i)u.push(e/d);let p=xZ([`${o("debug.stream.lastData")} ${xP(a,o)}`,null!==t.lastHeartbeatAt&&o("debug.stream.heartbeat",{time:xP(l-t.lastHeartbeatAt,o)}),o("debug.stream.watchdogArmed",{time:xz(d,o)})]);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(vd,{fraction:x0(a,d)??0,tone:c,width:120,notches:u,title:p}),(0,r.jsx)("span",{className:`debug-value is-${c}`,title:p,children:o("debug.stream.dataAgo",{time:xW(a,o)})})]})}function vw(e){let{page:t,ctx:n}=e,{t:i,now:s}=n,o=t.client?.lease??null,l=t.client?.pageId??null,a=(0,r.jsx)("span",{className:"debug-measure-name",children:(0,r.jsx)("span",{className:"debug-label",children:i("debug.section.lease")})});if(!o||0===o.requests)return(0,r.jsxs)(r.Fragment,{children:[a,(0,r.jsx)("span",{className:"debug-measure-empty",children:o?i("debug.lease.noHolder"):t.clientFailed?"—":i("debug.stream.noChat")})]});let d=o.last,c=function(e,t,n){if(null===e||!(t>0))return null;let r=Math.max(0,n-e);return e+(Math.floor(r/t)+1)*t}(o.renewStartedAt,o.renewIntervalMs,s),u=null!==o.inFlightSince&&s-o.inFlightSince>=2e3,p=u||d?.outcome==="unanswered"?"warning":d?.outcome==="error"?"error":"dim",h=i("debug.lease.countsValue",{requests:o.requests,unanswered:o.unanswered,errors:o.errors}),m=xZ([null!==c&&`${i("debug.lease.next")} ${xO(c-s,i)}`,i("debug.lease.every",{time:xz(o.renewIntervalMs,i)}),h,null!==l&&`${i("debug.holder.thisPage")} ${xD(l)}`]);return(0,r.jsxs)(r.Fragment,{children:[a,null===c?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{className:"debug-value is-dim",children:"—"})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(vd,{fraction:u?1:1-(x0(c-s,o.renewIntervalMs)??1),tone:p,width:120,title:m}),(0,r.jsx)("span",{className:"debug-value is-muted",title:m,children:c-s>0?i("debug.lease.renewsIn",{time:xW(c-s,i,"ceil")}):i("debug.lease.renewing")})]}),(0,r.jsx)("span",{className:"debug-measure-sub",children:`${i("debug.lease.last")} ${d?xZ([i(xE[d.outcome]??"debug.unknown"),xz(d.durationMs,i),"error"===d.outcome&&null!==d.httpStatus&&`HTTP ${d.httpStatus}`,i("debug.time.ago",{time:xW(s-d.at,i)})]):i("debug.notYet")}`}),(o.unanswered>0||o.errors>0)&&(0,r.jsx)("span",{className:"debug-measure-sub",children:h})]})}function vS(e){let{reply:t,ctx:n}=e,{t:i,clock:s}=n,o=(0,r.jsx)("span",{className:"debug-section-title",children:i("debug.section.server")});if(!t||!s)return(0,r.jsxs)("div",{className:"debug-col-head debug-server-head",children:[o,(0,r.jsx)("span",{children:i("debug.poll.waiting")})]});let l=t.server,a=i("debug.global.wrappersValue",{...l.wrappers}),d=`${i("debug.global.timers")}: ${i("debug.global.timersValue",{idle:l.idleTimeoutMs>0?xz(l.idleTimeoutMs,i):i("debug.server.idleDisabled"),heartbeat:xz(l.heartbeatMs,i)})}
385
+ ${a}`,c=l.terminals,u=xZ([`${i("debug.global.terminals")}: ${i("debug.global.terminalsValue",{count:c.count,listeners:c.listeners,detached:c.detached,exited:c.exited})}`,null!==c.nextCleanupAt&&i("debug.global.cleanup",{time:xF(s.remaining(c.nextCleanupAt),i)})]),p=Array.from({length:c.count},(e,t)=>t<c.detached?{tone:"dim",dashed:!0,title:u}:t<c.detached+c.exited?{tone:"muted",faded:!0,title:u}:{tone:"muted",title:u}),h=`${i("debug.global.fileWatches")}: ${l.fileWatches}`,m=l.wrappers.starting;return(0,r.jsxs)("div",{className:"debug-col-head debug-server-head",children:[o,(0,r.jsxs)("span",{className:"debug-server-item",title:d,children:[(0,r.jsx)(vt,{kind:"server"}),(0,r.jsx)("span",{children:`${i("debug.global.uptime")} ${xz(s.age(l.startedAt),i)}`})]}),m>0&&(0,r.jsxs)("span",{className:"debug-run",role:"img","aria-label":a,title:a,children:[Array.from({length:Math.min(m,4)},(e,t)=>(0,r.jsx)("span",{className:"debug-status",children:(0,r.jsx)("span",{className:"debug-status-ring is-starting"})},t)),m>4&&(0,r.jsx)("span",{className:"debug-run-more",children:`+${m-4}`})]}),(0,r.jsx)(vr,{text:i("debug.box.file"),items:Array.from({length:l.fileWatches},()=>({tone:"muted",title:h})),cap:4,label:h}),(0,r.jsx)(vr,{text:i("debug.box.terminal"),items:p,cap:4,label:u})]})}function vC(e){let{reply:t,ctx:n}=e,{t:i,myHolder:s}=n;if(!t)return null;let{pages:o,sseTotal:l}=t.server;if(0===l&&0===o.length)return null;let a=xG(o,s);return(0,r.jsxs)("div",{className:"debug-pages",children:[(0,r.jsxs)("div",{className:"debug-page-row debug-list-head",children:[(0,r.jsx)("span",{className:"debug-pages-title",children:`${i("debug.pages.title")} ${a.length}`}),(0,r.jsx)("span",{className:"debug-page-count",children:`SSE ${i("debug.global.streamTotal",{count:l})}`})]}),a.map((e,t)=>{let n=null!==e.holder&&e.holder===s,o=xJ(e.holder,s,i),l=e.agent+e.terminal+e.fileWatch,a=xZ([e.agent>0&&`${i(xC.agent)} ${e.agent}`,e.terminal>0&&`${i(xC.terminal)} ${e.terminal}`,e.fileWatch>0&&`${i(xC["file-watch"])} ${e.fileWatch}`]);return(0,r.jsxs)("div",{className:`debug-page-row${n?" is-current":""}`,title:xZ([o,e.client,e.address,`SSE ${l}`,a]),children:[(0,r.jsx)("span",{className:"debug-page-icons",children:(0,r.jsx)(vo,{client:e.client})}),(0,r.jsx)("span",{className:`debug-page-client${e.client?"":" is-dim"}`,children:e.client??i("debug.pages.unknownClient")}),(0,r.jsx)("span",{className:"debug-page-address",children:e.address??"—"}),(0,r.jsx)("span",{className:"debug-page-holder",children:n?i("debug.holder.thisPage"):null!==e.holder?xD(e.holder):i("debug.holder.none")}),(0,r.jsx)("span",{className:"debug-page-count",children:l})]},`${e.holder??""}:${t}`)})]})}function vN(e){let{reply:t,detail:n,groups:s,targetSessionId:o,sources:l,ctx:a}=e,{t:d,clock:c}=a;if(!t||!c||!s)return(0,r.jsx)("div",{className:"debug-empty",children:d("debug.poll.waiting")});let u=null!==n&&s.some(e=>e.rows.some(e=>e.current&&e.id===n.sessionId)),p=null;return o?n?u||(p=(0,r.jsx)(vI,{detail:n,clock:c,ctx:a})):p=(0,r.jsx)("div",{className:"debug-empty",children:d("debug.poll.waiting")}):p=(0,r.jsx)("div",{className:"debug-empty",children:d("debug.server.noSession")}),(0,r.jsxs)("div",{className:"debug-list",children:[p,0===s.length&&!(n&&!u)&&(0,r.jsx)("div",{className:"debug-empty",children:d("debug.none")}),s.length>0&&(0,r.jsxs)("div",{className:"debug-row debug-list-head","aria-hidden":"true",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{children:d("debug.sessions.head.session")}),(0,r.jsx)("span",{className:"debug-list-head-holders",children:d("debug.sessions.head.holders")}),(0,r.jsx)("span",{className:"debug-list-head-idle",children:d("debug.server.idle")})]}),s.map(e=>(0,r.jsxs)("div",{className:"debug-group",children:[(0,r.jsxs)("div",{className:"debug-group-head",children:[null!==e.name&&(0,r.jsx)(nP,{size:11}),(0,r.jsx)("span",{className:"debug-group-name",children:e.name??d("debug.sessions.unlisted")}),(0,r.jsx)("span",{className:"debug-group-count",children:e.rows.filter(e=>null!==e.summary).length})]}),e.rows.map(e=>{let s=e.current&&n?.sessionId===e.id?n:null;return(0,r.jsxs)(i.Fragment,{children:[(0,r.jsx)(vW,{row:e,sources:l,idleTimeoutMs:t.server.idleTimeoutMs,clock:c,ctx:a,current:s?function(e,t,n){let{t:i}=n,s=e=>xP(t.age(e),i),o=e.wrapper?.idle??null,l=e.lifecycle;return{badges:(0,r.jsx)(vM,{detail:e,clock:t,ctx:n}),idleTitle:o&&null!==o.nextCheckAt?xZ([`${i("debug.server.idle")} ${xz(t.remaining(o.nextCheckAt),i)}`,o.timeoutMs>0&&i("debug.server.idleTimeout",{time:xz(o.timeoutMs,i)}),null!==o.lastResetAt&&i("debug.server.idleReset",{time:s(o.lastResetAt)}),i(o.forcedByStop?"debug.server.idleForced":"debug.server.idleHint")]):void 0,startsTitle:l&&l.starts>1?vE(l,s,i):void 0}}(s,c,a):void 0}),s&&(0,r.jsx)(v$,{detail:s,clock:c,ctx:a})]},e.id)})]},e.key))]})}function vE(e,t,n){return xZ([n("debug.overlay.starts",{count:e.starts}),n("debug.server.lastStart",{time:t(e.lastStartedAt)}),null!==e.lastClosedAt&&n("debug.server.lastClosed",{time:t(e.lastClosedAt)})])}function vI(e){var t;let n,{detail:i,clock:s,ctx:o}=e,{t:l,titleOf:a}=o,d=a(i.sessionId)??xD(i.sessionId),c=(n=(t=i).wrapper)?xX({awaitingInput:n.awaitingInput,running:n.run.running,state:n.state}):t.starting?"starting":"none";return(0,r.jsxs)("div",{className:"debug-group",children:[(0,r.jsxs)("div",{className:"debug-row is-current has-detail is-placeholder",title:l("debug.sessions.current"),children:[(0,r.jsx)("span",{className:"debug-row-status",children:(0,r.jsx)(vu,{state:c,label:l(xY[c])})}),(0,r.jsx)("span",{className:"debug-row-title",children:(0,r.jsx)("span",{className:"debug-row-name",children:d})})]}),(0,r.jsx)(v$,{detail:i,clock:s,ctx:o,unlisted:!0})]})}function v$(e){let{detail:t,clock:n,ctx:i,unlisted:s=!1}=e,{t:o,titleOf:l}=i,a=t.wrapper,d=t.lifecycle,c=e=>xP(n.age(e),o),u=null!==a&&!a.stale,p=a?.state==="closing"?null!==a.closingAt?o("debug.server.closingSince",{time:c(a.closingAt)}):o("debug.state.closing"):null,h=a&&xZ([null!=a.startedAt&&`${o("debug.server.started")} ${c(a.startedAt)}`,u&&a.lastEvent&&`${o("debug.server.lastEvent")} ${a.lastEvent.type} ${c(a.lastEvent.at)}`,u&&a.lastCommand&&`${o("debug.server.lastCommand")} ${a.lastCommand.type} ${c(a.lastCommand.at)}`]);return(0,r.jsxs)("div",{className:"debug-detail",children:[(0,r.jsxs)("div",{className:"debug-detail-line",children:[null!==l(t.sessionId)&&(0,r.jsx)("span",{className:"debug-detail-id",children:xD(t.sessionId)}),!a&&(0,r.jsx)("span",{className:"debug-note",children:o(t.starting?"debug.server.starting":"debug.server.noWrapper")}),s&&d&&d.starts>1&&(0,r.jsx)("span",{className:"debug-starts",title:vE(d,c,o),children:`↻${d.starts}`}),p&&(0,r.jsx)(va,{tone:"warning",children:p}),a?.chatOnly&&(0,r.jsx)(va,{tone:"dim",children:o("debug.server.chatOnly")}),a?.subagent&&(0,r.jsx)(va,{tone:"dim",children:o("debug.server.subagent")}),a?.stale&&(0,r.jsx)(va,{tone:"warning",children:o("debug.server.stale")}),(0,r.jsx)(vT,{detail:t,t:o}),u&&(0,r.jsx)(vR,{detail:t,t:o}),h&&(0,r.jsx)("span",{className:"debug-line",children:h})]}),u&&(0,r.jsx)(vz,{detail:t,clock:n,ctx:i}),u&&(0,r.jsx)(vP,{detail:t,clock:n,ctx:i})]})}function vT(e){let{detail:t,t:n}=e,i=t.wrapper;return null!==i&&!i.stale&&t.eventStreams.every(e=>null!==e.connectedAt)&&i.eventListeners!==t.eventStreams.length&&i?(0,r.jsx)(va,{tone:"warning",children:`${n("debug.server.listeners")} ${i.eventListeners}`}):null}function vM(e){var t;let n,{detail:i,clock:s,ctx:o}=e,{t:l,myHolder:a}=o,d=e=>xP(s.age(e),l),c=xG([...i.eventStreams].sort((e,t)=>e.openedAt-t.openedAt),a),u=c.map(e=>{var t;let n,r=null===e.connectedAt;return{tone:r||e.droppedEvents>0?"warning":(t=e.holder,null===t?"dim":t===a?"accent":"muted"),filled:null!==e.holder&&e.holder===a,dashed:r,title:xZ([xJ(e.holder,a,l),e.client,e.address,null!==e.connectedAt?l("debug.server.streamConnected",{time:d(e.connectedAt)}):l("debug.server.streamStarting"),null!==e.lastWriteAt&&l("debug.server.lastWrite",{time:d(e.lastWriteAt)}),e.droppedEvents>0&&l("debug.server.dropped",{count:e.droppedEvents}),e.queuedBytes>0&&l("debug.server.queued",{size:(n=xA(e.queuedBytes))<1024?`${Math.floor(n)} B`:n<1048576?`${(n/1024).toFixed(1)} KB`:`${(n/1048576).toFixed(1)} MB`})])}}),p=i.providers,h=null===p?[{tone:"dim",title:l("debug.server.providersUnknown")}]:p.map(e=>({tone:"error"===e.active?"error":e.active?"muted":"dim",faded:!1===e.active,text:e.name,title:xZ([e.name,l("error"===e.active?"debug.server.providerError":e.active?"debug.server.providerActive":"debug.server.providerInactive"),e.byFile&&l("debug.server.byFile")])}));return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(vr,{text:"SSE",items:u,cap:3,label:(t=c.map(e=>e.holder),n=t.filter(e=>null!==e&&e===a).length,`SSE: ${t.length} (${l("debug.holder.thisPage")} ${n}, ${l("debug.holder.otherPage")} ${t.length-n})`)}),(0,r.jsx)(vr,{text:l("debug.box.provider"),items:h,cap:1,label:`${l("debug.server.providers")}: ${null===p?l("debug.server.providersUnknown"):p.length}`})]})}function vR(e){let{detail:t,t:n}=e,i=t.wrapper;if(!i)return null;let s=i.run,o=[s.streaming&&n("debug.run.streaming"),s.promptRunning&&n("debug.run.prompt"),s.bashRunning&&n("debug.run.bash"),s.compacting&&n("debug.run.compacting"),s.queuedMessages>0&&n("debug.run.queued",{count:s.queuedMessages}),s.runningTools>0&&n("debug.run.tools",{count:s.runningTools}),s.mutatingCommands>0&&n("debug.run.mutating",{count:s.mutatingCommands}),s.replacement&&n("debug.run.replacement",{kind:s.replacement}),"binding"===i.extensions&&`${n("debug.server.extensions")} ${n("debug.server.extensions.binding")}`].filter(e=>!!e),l=[s.pendingPrompts>0&&n("debug.run.pending",{count:s.pendingPrompts}),s.retrying&&n("debug.run.retrying"),s.waitingForMcp&&n("debug.run.waitingForMcp"),i.awaitingInput&&i.pendingUiRequests>0&&n("debug.server.uiRequests",{count:i.pendingUiRequests}),i.awaitingInput&&i.customUis>0&&n("debug.server.customUis",{count:i.customUis})].filter(e=>!!e);return(0,r.jsxs)(r.Fragment,{children:[o.map(e=>(0,r.jsx)(va,{tone:"dim",children:e},e)),l.map(e=>(0,r.jsx)(va,{tone:"warning",children:e},e))]})}let vA={completed:"ok",failed:"error",aborted:"warning",interrupted:"warning"};function vL(e){let{status:t}=e;if("running"===t||"starting"===t)return(0,r.jsx)("span",{className:"debug-run-icon is-accent",children:(0,r.jsx)(nK,{size:12})});let n=vA[t];return n?(0,r.jsx)("span",{className:`debug-run-icon is-${n}`,children:(0,r.jsx)(xv,{status:t})}):(0,r.jsx)("span",{className:"debug-run-icon",children:(0,r.jsx)("span",{className:"debug-status-ring is-alive"})})}function vz(e){let{detail:t,clock:n,ctx:i}=e,{t:s,titleOf:o}=i,l=t.subagents;if(!l.active&&0===l.runs.length&&0===l.notifications.length)return null;let a=e=>xP(n.age(e),s);return(0,r.jsxs)("div",{className:"debug-block",children:[(0,r.jsxs)("div",{className:"debug-subhead",children:[(0,r.jsx)("span",{children:s("debug.server.subagents")}),l.active&&(0,r.jsx)(va,{tone:"accent",children:s("debug.server.subagentsActive")})]}),l.runs.map((e,t)=>(0,r.jsxs)("div",{className:"debug-run-line",children:[(0,r.jsx)(vL,{status:e.status}),(0,r.jsx)("span",{className:"debug-run-name",children:o(e.sessionId)??e.profile??xD(e.sessionId)}),(0,r.jsx)("span",{className:"debug-line",children:xZ([xR(e.status,xT,s),e.background&&s("debug.server.background"),e.resumed&&s("debug.server.resumed"),null!==e.dispatchedAt&&a(e.dispatchedAt)])}),e.abortRequested&&(0,r.jsx)(va,{tone:"warning",children:s("debug.server.abortRequested")}),e.mcpWaiting&&(0,r.jsx)(va,{tone:"warning",children:s("debug.run.waitingForMcp")})]},`${e.sessionId}:${t}`)),l.notifications.map((e,t)=>(0,r.jsx)("div",{className:"debug-line is-warning",children:xZ([s("debug.server.notifying",{parent:xD(e.parentSessionId)}),null!==e.since&&a(e.since)])},`${e.sessionId}:${t}`))]})}function vP(e){let{detail:t,clock:n,ctx:i}=e,{t:s}=i,o=t.mcp;if(!o||0===o.servers.length&&0===o.problems)return null;let l=null!==o.idleReleaseAt&&o.idleMs>0?n.remaining(o.idleReleaseAt):null;return(0,r.jsxs)("div",{className:"debug-block",children:[(0,r.jsxs)("div",{className:"debug-pills",children:[(0,r.jsx)("span",{className:`debug-subhead${o.active?"":" is-dim"}`,children:"MCP"}),o.servers.map((e,t)=>{let{tone:n,filled:i}=e.hasError||"failed"===e.state||"conflict"===e.state?{tone:"error",filled:!0}:e.released?{tone:"dim",filled:!1}:"connected"===e.state?{tone:"ok",filled:!0}:"connecting"===e.state?{tone:"warning",filled:!1}:"needs-auth"===e.state||"not-trusted"===e.state||"disconnected"===e.state?{tone:"warning",filled:!0}:{tone:"muted",filled:!1},o=xR(e.state,pg,s),l=xZ([`${e.name} (${e.scope})`,o,e.released&&s("debug.server.mcpReleased"),e.hasError&&s("debug.server.mcpError")]),a="connected"!==e.state?o:e.hasError?s("debug.server.mcpError"):null;return(0,r.jsxs)("span",{className:"debug-pill",role:"img","aria-label":l,title:l,children:[(0,r.jsx)(vl,{tone:n,ring:!i}),(0,r.jsx)("span",{className:e.released?"is-dim":void 0,children:e.name}),a&&(0,r.jsx)("span",{className:"debug-pill-state",children:`\xb7 ${a}`})]},`${e.scope}:${e.name}:${t}`)}),o.problems>0&&(0,r.jsx)(va,{tone:"warning",children:s("debug.server.mcpProblems",{count:o.problems})}),o.disposed&&(0,r.jsx)(va,{tone:"dim",children:s("debug.server.mcpDisposed")})]}),null!==l&&(0,r.jsxs)("div",{className:"debug-idle-row",children:[(0,r.jsx)(vd,{fraction:x0(l,o.idleMs)??0,tone:"dim",width:80}),(0,r.jsx)("span",{className:"debug-value is-muted",children:s("debug.server.mcpRelease",{time:xF(l,s)})})]})]})}function vW(e){var t;let n,i,{row:s,sources:o,idleTimeoutMs:l,clock:a,ctx:d,current:c}=e,{t:u}=d,p=s.summary,h=s.info?nq(s.info):xD(s.id),m=p&&null!==p.nextIdleCheckAt?a.remaining(p.nextIdleCheckAt):null,f=p?xX(p):null,g=["debug-row",1===s.depth&&"is-sub",s.current&&"is-current",c&&"has-detail",s.placeholder&&"is-placeholder"].filter(Boolean).join(" ");return(0,r.jsxs)("div",{className:g,title:xZ([s.current&&u("debug.sessions.current"),p?(n=[p.subagent?u("debug.overlay.subagentId",{id:xD(p.sessionId)}):xD(p.sessionId),u(xI[p.state]??xI.none)],p.running&&n.push(u("debug.overlay.running")),p.awaitingInput&&n.push(u("debug.overlay.awaiting")),p.eventStreams>0&&n.push(u("debug.overlay.streams",{count:p.eventStreams})),p.providers>0&&n.push(u("debug.overlay.providers",{count:p.providers})),null!==m&&n.push(u(p.forcedByStop?"debug.overlay.closesIn":"debug.overlay.idle",{time:(i=xA(m))<6e4?u("debug.duration.seconds",{count:Math.floor(i/1e3)}):i<36e5?u("debug.duration.minutes",{count:Math.floor(i/6e4)}):i<864e5?u("debug.duration.hours",{count:Math.floor(i/36e5)}):u("debug.duration.days",{count:Math.floor(i/864e5)})})),p.starts>1&&n.push(u("debug.overlay.starts",{count:p.starts})),n.join(" \xb7 ")):h]),children:[(0,r.jsx)("span",{className:"debug-row-status",children:f&&(0,r.jsx)(vu,{state:f,label:u(xY[f])})}),(0,r.jsxs)("span",{className:"debug-row-title",children:[1===s.depth&&(0,r.jsx)("span",{className:"debug-row-branch","aria-hidden":"true"}),(0,r.jsx)("span",{className:"debug-row-name",children:h}),p&&p.starts>1&&(0,r.jsx)("span",{className:"debug-row-starts",title:c?.startsTitle,children:`↻${p.starts}`})]}),p&&(0,r.jsx)(vO,{summary:p,mine:(t=s.id,o.filter(e=>"agent"===e.kind&&e.label===t).length),remaining:m,idleTimeoutMs:l,t:u,badges:c?.badges,idleTitle:c?.idleTitle})]})}function vO(e){let{summary:t,mine:n,remaining:i,idleTimeoutMs:s,t:o,badges:l,idleTitle:a}=e,d=o("debug.overlay.streams",{count:t.eventStreams}),c=Math.min(t.eventStreams,n),u=Array.from({length:t.eventStreams},(e,t)=>t<c?{tone:"accent",filled:!0,title:d}:{tone:"muted",title:d}),p=o("debug.overlay.providers",{count:t.providers}),h=Array.from({length:t.providers},()=>({tone:"muted",title:p})),m=null!==i&&(s>0||t.forcedByStop),f=t.forcedByStop?"warning":"dim",g=null!==i?o("debug.overlay.closesIn",{time:xW(i,o)}):void 0;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"debug-row-badges",children:l??(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(vr,{text:"SSE",items:u,cap:3,label:d}),(0,r.jsx)(vr,{text:o("debug.box.provider"),items:h,cap:1,label:p})]})}),(0,r.jsx)("span",{className:`debug-row-idle is-${f}`,title:a,children:m&&null!==i&&(0,r.jsxs)(r.Fragment,{children:[s>0&&(0,r.jsx)(vd,{fraction:x0(i,s)??0,tone:f,width:36,height:3,className:"debug-row-idle-bar"}),t.forcedByStop&&(0,r.jsx)("span",{className:"debug-row-forced",role:"img","aria-label":g,title:g}),(0,r.jsx)("span",{className:"debug-row-idle-text",children:xW(i,o)})]})})]})}let vF=`
386
+ .debug-panel {
387
+ --dbg-ok: #16a34a;
388
+ --dbg-warn: #d97706;
389
+ --dbg-err: #ef4444;
390
+ container-type: inline-size;
391
+ container-name: debug-panel;
392
+ display: flex;
393
+ max-height: min(720px, 80dvh);
394
+ flex-direction: column;
395
+ background: var(--bg-panel);
396
+ border-bottom: 1px solid var(--border);
397
+ box-shadow: 0 10px 28px rgba(0,0,0,0.10);
398
+ color: var(--text);
399
+ }
400
+ .debug-panel .is-ok { color: var(--dbg-ok); }
401
+ .debug-panel .is-warning { color: var(--dbg-warn); }
402
+ .debug-panel .is-error { color: var(--dbg-err); }
403
+ .debug-panel .is-accent { color: var(--accent); }
404
+ .debug-panel .is-muted { color: var(--text-muted); }
405
+ .debug-panel .is-dim { color: var(--text-dim); }
406
+ .debug-panel-header {
407
+ display: flex;
408
+ flex-shrink: 0;
409
+ align-items: center;
410
+ gap: 12px;
411
+ min-width: 0;
412
+ padding: 8px 16px;
413
+ border-bottom: 1px solid var(--border);
414
+ font-size: 12px;
415
+ }
416
+ .debug-panel-heading {
417
+ flex-shrink: 0;
418
+ color: var(--text);
419
+ cursor: help;
420
+ font-weight: 700;
421
+ }
422
+ .debug-panel-status {
423
+ display: inline-flex;
424
+ min-width: 0;
425
+ align-items: center;
426
+ gap: 6px;
427
+ font-variant-numeric: tabular-nums;
428
+ }
429
+ .debug-panel-status svg {
430
+ flex-shrink: 0;
431
+ }
432
+ .debug-panel-status-text {
433
+ min-width: 0;
434
+ overflow: hidden;
435
+ text-overflow: ellipsis;
436
+ white-space: nowrap;
437
+ }
438
+ .debug-panel-copy {
439
+ flex-shrink: 0;
440
+ margin-left: auto;
441
+ padding: 2px 8px;
442
+ border: 1px solid var(--border);
443
+ border-radius: 4px;
444
+ background: transparent;
445
+ color: var(--text-muted);
446
+ cursor: pointer;
447
+ font-size: 11px;
448
+ }
449
+ .debug-panel-copy:hover {
450
+ background: var(--bg-hover);
451
+ color: var(--text);
452
+ }
453
+ .debug-panel-scroll {
454
+ display: flex;
455
+ min-height: 0;
456
+ flex: 1;
457
+ flex-direction: column;
458
+ gap: 12px;
459
+ overflow: auto;
460
+ padding: 10px 16px 12px;
461
+ font-size: 12px;
462
+ line-height: 1.5;
463
+ }
464
+ .debug-section-title {
465
+ color: var(--text);
466
+ font-size: 11px;
467
+ font-weight: 700;
468
+ }
469
+ .debug-empty,
470
+ .debug-note {
471
+ color: var(--text-dim);
472
+ font-size: 12px;
473
+ }
474
+ .debug-label {
475
+ color: var(--text-dim);
476
+ font-size: 11px;
477
+ white-space: nowrap;
478
+ }
479
+ .debug-value {
480
+ font-family: var(--font-mono);
481
+ font-size: 11px;
482
+ font-variant-numeric: tabular-nums;
483
+ white-space: nowrap;
484
+ }
485
+ .debug-line {
486
+ color: var(--text-dim);
487
+ font-family: var(--font-mono);
488
+ font-size: 11px;
489
+ font-variant-numeric: tabular-nums;
490
+ overflow-wrap: anywhere;
491
+ }
492
+ .debug-panel .debug-line.is-warning {
493
+ color: var(--dbg-warn);
494
+ }
495
+
496
+ .debug-issues {
497
+ display: flex;
498
+ flex-direction: column;
499
+ gap: 4px;
500
+ margin: 0;
501
+ padding: 0;
502
+ list-style: none;
503
+ }
504
+ .debug-issue {
505
+ display: flex;
506
+ align-items: flex-start;
507
+ gap: 6px;
508
+ padding: 4px 8px;
509
+ border-left: 2px solid currentColor;
510
+ border-radius: 4px;
511
+ background: color-mix(in srgb, currentColor 8%, var(--bg-panel));
512
+ }
513
+ .debug-issue > svg {
514
+ flex-shrink: 0;
515
+ margin-top: 3px;
516
+ }
517
+ .debug-issue-text {
518
+ min-width: 0;
519
+ color: var(--text);
520
+ font-size: 12px;
521
+ overflow-wrap: anywhere;
522
+ }
523
+
524
+ /* Three columns when the panel is wide: the page's as wide as its table, the server's and the
525
+ sessions' each capped, so names never stretch and push the badges to the far edge. */
526
+ .debug-cols {
527
+ display: grid;
528
+ grid-template-areas: "page server sessions";
529
+ grid-template-columns: minmax(320px, max-content) minmax(340px, 480px) minmax(360px, 560px);
530
+ gap: 0;
531
+ }
532
+ .debug-col {
533
+ display: flex;
534
+ min-width: 0;
535
+ flex-direction: column;
536
+ gap: 8px;
537
+ }
538
+ .debug-col-page {
539
+ grid-area: page;
540
+ }
541
+ .debug-col-server {
542
+ grid-area: server;
543
+ }
544
+ .debug-col-sessions {
545
+ grid-area: sessions;
546
+ }
547
+ .debug-col-server,
548
+ .debug-col-sessions {
549
+ margin-left: 20px;
550
+ padding-left: 20px;
551
+ border-left: 1px solid var(--border);
552
+ }
553
+ .debug-list,
554
+ .debug-block {
555
+ display: flex;
556
+ min-width: 0;
557
+ flex-direction: column;
558
+ gap: 6px;
559
+ }
560
+ .debug-block {
561
+ gap: 4px;
562
+ }
563
+ .debug-col-head {
564
+ display: flex;
565
+ min-height: 18px;
566
+ align-items: center;
567
+ gap: 8px;
568
+ }
569
+ /* Name, scale, value; a measure's details span the row below it. */
570
+ /* As wide as the column (the details get the room), never so wide a value drifts off its bar. */
571
+ .debug-measures {
572
+ display: grid;
573
+ max-width: 400px;
574
+ grid-template-columns: max-content minmax(max-content, 1fr) max-content;
575
+ align-items: center;
576
+ gap: 4px 10px;
577
+ }
578
+ /* Numbers line up on the right, as the count in the column's head does. */
579
+ .debug-measures > .debug-value {
580
+ justify-self: end;
581
+ text-align: right;
582
+ }
583
+ .debug-measure-name {
584
+ display: inline-flex;
585
+ align-items: center;
586
+ gap: 6px;
587
+ }
588
+ .debug-measure-name[title] {
589
+ cursor: help;
590
+ }
591
+ /* Wrapped to the table's width rather than widening it (a percentage min-width adds nothing to
592
+ the columns' sizes). */
593
+ .debug-measure-sub,
594
+ .debug-measure-empty {
595
+ grid-column: 2 / -1;
596
+ width: 0;
597
+ min-width: 100%;
598
+ color: var(--text-dim);
599
+ font-family: var(--font-mono);
600
+ font-size: 11px;
601
+ font-variant-numeric: tabular-nums;
602
+ overflow-wrap: anywhere;
603
+ }
604
+ .debug-measure-sub {
605
+ margin-top: -4px;
606
+ }
607
+ .debug-measure-sub > .debug-dot {
608
+ margin-right: 6px;
609
+ vertical-align: 0;
610
+ }
611
+ .debug-measure-empty {
612
+ font-family: inherit;
613
+ font-size: 12px;
614
+ }
615
+ .debug-chips {
616
+ display: flex;
617
+ flex-wrap: wrap;
618
+ gap: 4px;
619
+ }
620
+ .debug-chip {
621
+ display: inline-flex;
622
+ align-items: center;
623
+ padding: 0 6px;
624
+ border: 1px solid color-mix(in srgb, currentColor 35%, transparent);
625
+ border-radius: 9px;
626
+ font-family: var(--font-mono);
627
+ font-size: 11px;
628
+ line-height: 16px;
629
+ white-space: nowrap;
630
+ }
631
+
632
+ /* A boxed word: "SSE", a provider's name, File, Term. Filled is this page's own. */
633
+ .debug-badge {
634
+ display: inline-flex;
635
+ height: 16px;
636
+ box-sizing: border-box;
637
+ flex-shrink: 0;
638
+ align-items: center;
639
+ padding: 0 4px;
640
+ border: 1px solid currentColor;
641
+ border-radius: 3px;
642
+ background-clip: padding-box;
643
+ font: 600 10px/14px var(--font-mono);
644
+ white-space: nowrap;
645
+ }
646
+ .debug-panel .debug-badge.is-filled {
647
+ border-color: var(--accent);
648
+ background-color: var(--accent);
649
+ color: var(--accent-contrast);
650
+ }
651
+ /* This page's, amber: a stream of its own still starting or dropping events. */
652
+ .debug-panel .debug-badge.is-filled.is-warning {
653
+ border-color: var(--dbg-warn);
654
+ background-color: var(--dbg-warn);
655
+ color: var(--bg-panel);
656
+ }
657
+ .debug-badge.is-dashed {
658
+ border-style: dashed;
659
+ }
660
+ .debug-badge.is-faded {
661
+ opacity: 0.45;
662
+ }
663
+ /* A provider's name: twelve characters, then an ellipsis (a block, so the ellipsis applies). */
664
+ .debug-badge.is-name {
665
+ display: inline-block;
666
+ max-width: calc(12ch + 10px);
667
+ overflow: hidden;
668
+ text-overflow: ellipsis;
669
+ }
670
+ /* A page's browser and system marks. */
671
+ .debug-client {
672
+ display: inline-flex;
673
+ align-items: center;
674
+ gap: 3px;
675
+ }
676
+ .debug-client svg {
677
+ display: block;
678
+ flex-shrink: 0;
679
+ }
680
+
681
+ /* The connected pages: marks, browser and system, address, page, its stream count. */
682
+ .debug-pages {
683
+ display: flex;
684
+ flex-direction: column;
685
+ }
686
+ .debug-page-row {
687
+ position: relative;
688
+ display: grid;
689
+ min-height: 22px;
690
+ grid-template-columns: 30px minmax(0, 1.2fr) minmax(0, 1fr) minmax(0, 1fr) 32px;
691
+ align-items: center;
692
+ column-gap: 8px;
693
+ padding: 0 4px;
694
+ border-radius: 4px;
695
+ font-size: 11px;
696
+ }
697
+ .debug-page-row.debug-list-head {
698
+ min-height: 18px;
699
+ grid-template-columns: minmax(0, 1fr) auto;
700
+ color: var(--text-dim);
701
+ font-size: 10px;
702
+ }
703
+ .debug-page-row.is-current {
704
+ background: var(--bg-selected);
705
+ }
706
+ .debug-page-row.is-current::before {
707
+ content: "";
708
+ position: absolute;
709
+ top: 4px;
710
+ left: 0;
711
+ width: 3px;
712
+ height: 14px;
713
+ border-radius: 0 2px 2px 0;
714
+ background: var(--accent);
715
+ }
716
+ .debug-page-icons {
717
+ display: inline-flex;
718
+ padding-left: 4px;
719
+ color: var(--text-muted);
720
+ }
721
+ .debug-page-icons svg {
722
+ width: 12px;
723
+ height: 12px;
724
+ }
725
+ .debug-page-client,
726
+ .debug-page-address,
727
+ .debug-page-holder {
728
+ min-width: 0;
729
+ overflow: hidden;
730
+ text-overflow: ellipsis;
731
+ white-space: nowrap;
732
+ }
733
+ .debug-page-client {
734
+ color: var(--text);
735
+ }
736
+ .debug-page-address {
737
+ color: var(--text-muted);
738
+ font-family: var(--font-mono);
739
+ }
740
+ .debug-page-holder {
741
+ color: var(--text-dim);
742
+ }
743
+ .debug-page-count {
744
+ justify-self: end;
745
+ color: var(--text-muted);
746
+ font-family: var(--font-mono);
747
+ font-variant-numeric: tabular-nums;
748
+ white-space: nowrap;
749
+ }
750
+ .debug-list-head .debug-page-count {
751
+ color: var(--text-dim);
752
+ }
753
+ .debug-run {
754
+ display: inline-flex;
755
+ flex-wrap: wrap;
756
+ align-items: flex-start;
757
+ gap: 3px;
758
+ vertical-align: middle;
759
+ }
760
+ .debug-run-more {
761
+ color: var(--text-dim);
762
+ font-family: var(--font-mono);
763
+ font-size: 10px;
764
+ line-height: 16px;
765
+ }
766
+
767
+ .debug-meter-row {
768
+ display: flex;
769
+ flex-wrap: wrap;
770
+ align-items: center;
771
+ gap: 8px;
772
+ }
773
+ .debug-meter {
774
+ display: flex;
775
+ min-height: 18px;
776
+ flex-wrap: wrap;
777
+ align-items: center;
778
+ gap: 3px;
779
+ }
780
+ .debug-slot {
781
+ display: inline-flex;
782
+ min-width: 32px;
783
+ height: 18px;
784
+ box-sizing: border-box;
785
+ align-items: center;
786
+ justify-content: center;
787
+ border-radius: 3px;
788
+ }
789
+ .debug-slot.is-empty {
790
+ border: 1px dotted var(--border);
791
+ }
792
+ .debug-meter.is-inline .debug-slot {
793
+ min-width: 0;
794
+ height: 16px;
795
+ }
796
+ .debug-meter-overflow {
797
+ margin-left: 2px;
798
+ font-family: var(--font-mono);
799
+ font-size: 11px;
800
+ }
801
+
802
+ .debug-spark {
803
+ display: inline-flex;
804
+ width: 120px;
805
+ height: 15px;
806
+ }
807
+ .debug-spark svg {
808
+ display: block;
809
+ }
810
+ .debug-bar {
811
+ position: relative;
812
+ display: inline-block;
813
+ flex-shrink: 0;
814
+ overflow: hidden;
815
+ border-radius: 2px;
816
+ background: var(--border);
817
+ vertical-align: middle;
818
+ }
819
+ .debug-bar-fill {
820
+ position: absolute;
821
+ top: 0;
822
+ bottom: 0;
823
+ left: 0;
824
+ background: currentColor;
825
+ }
826
+ .debug-bar-notch {
827
+ position: absolute;
828
+ top: 0;
829
+ bottom: 0;
830
+ width: 1px;
831
+ background: var(--bg-panel);
832
+ }
833
+ .debug-dot {
834
+ display: inline-block;
835
+ width: 8px;
836
+ height: 8px;
837
+ flex-shrink: 0;
838
+ border-radius: 50%;
839
+ background: currentColor;
840
+ }
841
+ .debug-dot.is-ring {
842
+ background: transparent;
843
+ box-shadow: inset 0 0 0 1.5px currentColor;
844
+ }
845
+
846
+ .debug-status {
847
+ display: inline-flex;
848
+ width: 14px;
849
+ height: 14px;
850
+ flex-shrink: 0;
851
+ align-items: center;
852
+ justify-content: center;
853
+ }
854
+ .debug-status-ring {
855
+ width: 7px;
856
+ height: 7px;
857
+ box-sizing: border-box;
858
+ border: 1.5px solid var(--text-dim);
859
+ border-radius: 50%;
860
+ }
861
+ .debug-status-ring.is-closing {
862
+ border-style: dashed;
863
+ border-color: var(--dbg-warn);
864
+ }
865
+ .debug-status-ring.is-none {
866
+ border-style: dotted;
867
+ border-color: var(--text-dim);
868
+ }
869
+ .debug-status-ring.is-starting {
870
+ border-style: dashed;
871
+ }
872
+
873
+ /* The chat's details under its row, from the title's edge; the row's tint carried down. */
874
+ .debug-detail {
875
+ display: flex;
876
+ min-width: 0;
877
+ flex-direction: column;
878
+ gap: 4px;
879
+ margin-bottom: 2px;
880
+ padding: 0 4px 5px 24px;
881
+ border-radius: 0 0 4px 4px;
882
+ background: var(--bg-selected);
883
+ }
884
+ .debug-detail-line {
885
+ display: flex;
886
+ min-width: 0;
887
+ flex-wrap: wrap;
888
+ align-items: center;
889
+ gap: 2px 6px;
890
+ }
891
+ .debug-detail-id,
892
+ .debug-starts {
893
+ color: var(--text-dim);
894
+ font-family: var(--font-mono);
895
+ font-size: 11px;
896
+ }
897
+ .debug-idle-row {
898
+ display: flex;
899
+ flex-wrap: wrap;
900
+ align-items: center;
901
+ gap: 4px 8px;
902
+ }
903
+ .debug-subhead {
904
+ display: flex;
905
+ align-items: center;
906
+ gap: 6px;
907
+ color: var(--text);
908
+ font-size: 11px;
909
+ font-weight: 700;
910
+ }
911
+ .debug-panel .debug-subhead.is-dim {
912
+ color: var(--text-dim);
913
+ }
914
+ .debug-run-line {
915
+ display: flex;
916
+ flex-wrap: wrap;
917
+ align-items: center;
918
+ gap: 2px 6px;
919
+ }
920
+ .debug-run-icon {
921
+ display: inline-flex;
922
+ width: 12px;
923
+ height: 12px;
924
+ flex-shrink: 0;
925
+ align-items: center;
926
+ justify-content: center;
927
+ }
928
+ .debug-run-icon svg {
929
+ width: 12px;
930
+ height: 12px;
931
+ }
932
+ .debug-run-name {
933
+ min-width: 0;
934
+ overflow: hidden;
935
+ color: var(--text);
936
+ font-size: 12px;
937
+ text-overflow: ellipsis;
938
+ white-space: nowrap;
939
+ }
940
+ .debug-pills {
941
+ display: flex;
942
+ flex-wrap: wrap;
943
+ align-items: center;
944
+ gap: 4px 10px;
945
+ }
946
+ .debug-pill {
947
+ display: inline-flex;
948
+ align-items: center;
949
+ gap: 4px;
950
+ font-size: 11px;
951
+ }
952
+ .debug-pill-state {
953
+ color: var(--text-dim);
954
+ white-space: nowrap;
955
+ }
956
+
957
+ .debug-group {
958
+ display: flex;
959
+ flex-direction: column;
960
+ }
961
+ .debug-group-head {
962
+ display: flex;
963
+ min-height: 22px;
964
+ align-items: center;
965
+ gap: 5px;
966
+ color: var(--text-dim);
967
+ font-size: 11px;
968
+ }
969
+ .debug-group-head svg {
970
+ flex-shrink: 0;
971
+ }
972
+ .debug-group-name {
973
+ min-width: 0;
974
+ overflow: hidden;
975
+ font-weight: 600;
976
+ text-overflow: ellipsis;
977
+ white-space: nowrap;
978
+ }
979
+ .debug-group-count {
980
+ font-family: var(--font-mono);
981
+ font-size: 10px;
982
+ font-variant-numeric: tabular-nums;
983
+ }
984
+ .debug-row {
985
+ display: grid;
986
+ min-height: 24px;
987
+ /* The title keeps room for a few characters; the badges wrap before they take it all. */
988
+ grid-template-columns: 14px minmax(96px, 1fr) auto 104px;
989
+ align-items: center;
990
+ column-gap: 6px;
991
+ padding: 0 4px;
992
+ border-radius: 4px;
993
+ }
994
+ .debug-row.debug-list-head {
995
+ min-height: 18px;
996
+ color: var(--text-dim);
997
+ font-size: 10px;
998
+ }
999
+ /* At the end of their columns, spilling left rather than out of the row when wider. */
1000
+ .debug-list-head-holders,
1001
+ .debug-list-head-idle {
1002
+ justify-self: end;
1003
+ white-space: nowrap;
1004
+ }
1005
+ .debug-row.is-current {
1006
+ position: relative;
1007
+ background: var(--bg-selected);
1008
+ }
1009
+ .debug-row.has-detail {
1010
+ border-radius: 4px 4px 0 0;
1011
+ }
1012
+ /* The sidebar's mark of the selected session (app/sidebar.css): a short bar on the left edge,
1013
+ on the first line however many lines the row takes. */
1014
+ .debug-row.is-current::before {
1015
+ content: "";
1016
+ position: absolute;
1017
+ top: 5px;
1018
+ left: 0;
1019
+ width: 3px;
1020
+ height: 14px;
1021
+ border-radius: 0 2px 2px 0;
1022
+ background: var(--accent);
1023
+ }
1024
+ .debug-row-status {
1025
+ display: inline-flex;
1026
+ width: 14px;
1027
+ justify-content: center;
1028
+ }
1029
+ .debug-row-title {
1030
+ position: relative;
1031
+ display: flex;
1032
+ min-width: 0;
1033
+ align-items: center;
1034
+ gap: 4px;
1035
+ }
1036
+ .debug-row.is-sub .debug-row-title {
1037
+ padding-left: 16px;
1038
+ }
1039
+ .debug-row-branch {
1040
+ position: absolute;
1041
+ top: calc(50% - 8px);
1042
+ left: 4px;
1043
+ width: 8px;
1044
+ height: 8px;
1045
+ border-bottom: 1px solid var(--border);
1046
+ border-left: 1px solid var(--border);
1047
+ }
1048
+ .debug-row-name {
1049
+ min-width: 0;
1050
+ overflow: hidden;
1051
+ color: var(--text);
1052
+ font-size: 12px;
1053
+ text-overflow: ellipsis;
1054
+ white-space: nowrap;
1055
+ }
1056
+ .debug-row.is-sub .debug-row-name {
1057
+ color: var(--text-muted);
1058
+ }
1059
+ .debug-row.is-current .debug-row-name {
1060
+ font-weight: 600;
1061
+ }
1062
+ .debug-row.is-placeholder .debug-row-name {
1063
+ color: var(--text-dim);
1064
+ }
1065
+ .debug-row-starts {
1066
+ flex-shrink: 0;
1067
+ color: var(--text-dim);
1068
+ font-family: var(--font-mono);
1069
+ font-size: 10px;
1070
+ }
1071
+ .debug-row-badges {
1072
+ display: flex;
1073
+ min-width: 0;
1074
+ flex-wrap: wrap;
1075
+ justify-content: flex-end;
1076
+ align-items: center;
1077
+ gap: 3px 8px;
1078
+ }
1079
+ .debug-row-idle {
1080
+ display: flex;
1081
+ align-items: center;
1082
+ justify-content: flex-end;
1083
+ gap: 4px;
1084
+ }
1085
+ .debug-row-forced {
1086
+ width: 6px;
1087
+ height: 6px;
1088
+ flex-shrink: 0;
1089
+ border-radius: 1px;
1090
+ background: currentColor;
1091
+ }
1092
+ .debug-row-idle-text {
1093
+ min-width: 3ch;
1094
+ font-family: var(--font-mono);
1095
+ font-size: 11px;
1096
+ font-variant-numeric: tabular-nums;
1097
+ text-align: right;
1098
+ }
1099
+
1100
+ /* The server's totals beside its title. */
1101
+ .debug-server-head {
1102
+ flex-wrap: wrap;
1103
+ gap: 4px 14px;
1104
+ color: var(--text-dim);
1105
+ font-size: 11px;
1106
+ }
1107
+ .debug-server-item {
1108
+ display: inline-flex;
1109
+ flex-wrap: wrap;
1110
+ align-items: center;
1111
+ gap: 3px 4px;
1112
+ }
1113
+
1114
+ /* Narrower: the sessions under the server's pages, one border down both; the page's column
1115
+ beside them, its height going to the sessions' row rather than opening a gap under the pages. */
1116
+ @container debug-panel (max-width: 1239px) {
1117
+ .debug-cols {
1118
+ grid-template-areas: "page server" "page sessions";
1119
+ grid-template-columns: minmax(320px, max-content) minmax(0, 560px);
1120
+ grid-template-rows: auto 1fr;
1121
+ }
1122
+ .debug-col-sessions {
1123
+ padding-top: 10px;
1124
+ }
1125
+ }
1126
+ @container debug-panel (max-width: 760px) {
1127
+ .debug-cols {
1128
+ grid-template-areas: "page" "server" "sessions";
1129
+ grid-template-columns: minmax(0, 1fr);
1130
+ grid-template-rows: none;
1131
+ }
1132
+ .debug-col-server {
1133
+ margin-top: 10px;
1134
+ padding-top: 10px;
1135
+ border-top: 1px solid var(--border);
1136
+ }
1137
+ .debug-col-server,
1138
+ .debug-col-sessions {
1139
+ margin-left: 0;
1140
+ padding-left: 0;
1141
+ border-left: 0;
1142
+ }
1143
+ }
1144
+ @container debug-panel (max-width: 520px) {
1145
+ .debug-detail-id {
1146
+ display: none;
1147
+ }
1148
+ .debug-row {
1149
+ grid-template-columns: 14px minmax(0, 1fr) 64px;
1150
+ }
1151
+ /* The badges take a line of their own under the title, which keeps its width. */
1152
+ .debug-row-badges {
1153
+ grid-column: 2 / -1;
1154
+ grid-row: 2;
1155
+ flex-wrap: wrap;
1156
+ justify-content: flex-start;
1157
+ padding-bottom: 4px;
1158
+ }
1159
+ .debug-row.is-sub .debug-row-badges {
1160
+ padding-left: 16px;
1161
+ }
1162
+ .debug-row-badges:empty,
1163
+ .debug-list-head-holders,
1164
+ .debug-page-holder {
1165
+ display: none;
1166
+ }
1167
+ .debug-page-row {
1168
+ grid-template-columns: 30px minmax(0, 1fr) minmax(0, 1fr) 24px;
1169
+ }
1170
+ .debug-row-idle-bar {
1171
+ display: none;
1172
+ }
1173
+ .debug-server-head .debug-section-title {
1174
+ flex-basis: 100%;
1175
+ }
1176
+ }
1177
+ `;function vD(e){let{sessionId:t,running:n,...s}=e,{t:o}=(0,tn.s)(),[l,a]=(0,i.useState)(null),[d,c]=(0,i.useState)("loading"),u=(0,i.useRef)(null);return((0,i.useEffect)(()=>{let e,r=new AbortController,i=async()=>{try{let s=await fetch(`/api/sessions/${encodeURIComponent(t)}`,{signal:r.signal,cache:"no-store"});if(404===s.status){c("missing"),n&&(e=setTimeout(()=>void i(),1e3));return}let o=await s.json();o.info?a(o.info):c("error")}catch(e){e instanceof Error&&"AbortError"===e.name||c("error")}};return i(),()=>{r.abort(),clearTimeout(e)}},[t,n]),l)?(0,r.jsx)(aj,{...s,session:l,sessionRunning:n,newSessionCwd:null,newSessionDraftKey:null,chatInputRef:u,panel:!0}):(0,r.jsx)("div",{role:"error"===d?"alert":void 0,style:{padding:"24px 16px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:o("loading"===d||n?"sessionPanel.loading":"missing"===d?"sessionPanel.missing":"sessionPanel.error")})}var vB=n(63606),vH=n(8422);let v_="pi-web:terminal-theme",vU="dark",vK={dark:{background:"#111318",foreground:"#d7dce5",cursor:"#60a5fa",selectionBackground:"#365b8a",black:"#1d222b",red:"#f87171",green:"#4ade80",yellow:"#facc15",blue:"#60a5fa",magenta:"#c084fc",cyan:"#22d3ee",white:"#e5e7eb",brightBlack:"#6b7280",brightRed:"#fca5a5",brightGreen:"#86efac",brightYellow:"#fde047",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#ffffff"},light:{background:"#fbfbfc",foreground:"#24292f",cursor:"#2563eb",cursorAccent:"#fbfbfc",selectionBackground:"#bfd7fb",black:"#24292f",red:"#cf222e",green:"#116329",yellow:"#7d4e00",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#1a7f37",brightYellow:"#633c01",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#8c959f"}};function vq(){try{var e;return e=window.localStorage.getItem(v_),"light"===e?"light":vU}catch{return vU}}let vV=null,vZ=new Set;function vJ(){return null===vV&&(vV=vq()),vV}function vG(){vZ.forEach(e=>e())}function vY(e){if(null!==e.key&&e.key!==v_)return;let t=vq();t!==vV&&(vV=t,vG())}function vX(e){return 0===vZ.size&&(window.addEventListener("storage",vY),vV=vq()),vZ.add(e),()=>{vZ.delete(e),0===vZ.size&&window.removeEventListener("storage",vY)}}async function vQ(e,t){let n=await fetch(e,{...t,signal:AbortSignal.timeout(15e3)}),r=await n.json().catch(()=>{throw Error(`Terminal request failed (HTTP ${n.status}): server returned an empty or invalid JSON response. Check the pi-web server log.`)});if(!r||"object"!=typeof r)throw Error(`Terminal request failed (HTTP ${n.status}): invalid JSON response. Check the pi-web server log.`);if(!n.ok)throw Error(r.error??`HTTP ${n.status}`);return r}let v0={ctrl:!1,alt:!1},v1=[["Escape","/","-","Home","ArrowUp","End","PageUp"],["Tab","ctrl","alt","ArrowLeft","ArrowDown","ArrowRight","PageDown"]],v2=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown"]),v4={ArrowUp:"A",ArrowDown:"B",ArrowRight:"C",ArrowLeft:"D",Home:"H",End:"F"},v8={PageUp:5,PageDown:6};function v3(e){let{ctrl:t,alt:n}=e;return 1+2*!!n+4*!!t}function v5(e,t){if(!t.ctrl&&!t.alt||1!=[...e].length)return e;let n=t.ctrl?function(e){if(/^[a-z]$/i.test(e))return String.fromCharCode(31&e.toUpperCase().charCodeAt(0));let t=e.charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):" "===e?"\0":"/"===e||"-"===e?"\x1f":"?"===e?"":e}(e):e;return t.alt?`\x1b${n}`:n}let v6={Escape:"ESC","/":"/","-":"-",Home:"HOME",ArrowUp:"↑",End:"END",PageUp:"PGUP",Tab:"TAB",ctrl:"CTRL",alt:"ALT",ArrowLeft:"↓",ArrowDown:"↓",ArrowRight:"↑",PageDown:"PGDN"},v9={ArrowUp:"Up",ArrowDown:"Down",ArrowLeft:"Left",ArrowRight:"Right",PageUp:"Page Up",PageDown:"Page Down"};function v7(e){let t=window.matchMedia("(pointer: coarse)");return t.addEventListener("change",e),window.screen.orientation?.addEventListener("change",e),window.addEventListener("orientationchange",e),window.addEventListener("resize",e),()=>{t.removeEventListener("change",e),window.screen.orientation?.removeEventListener("change",e),window.removeEventListener("orientationchange",e),window.removeEventListener("resize",e)}}let be=()=>window.matchMedia("(pointer: coarse)").matches&&function(){let e=window.screen.orientation?.type;if(e)return e.startsWith("portrait");let t=window.orientation;return"number"==typeof t?t%180==0:window.innerHeight>=window.innerWidth}();function bt(e){let{modifiers:t,onKey:n,onToggleModifier:s}=e,{t:o}=(0,tn.s)(),l=(0,i.useRef)(null),a=()=>{null!==l.current&&window.clearTimeout(l.current),l.current=null};return(0,i.useEffect)(()=>a,[]),(0,r.jsx)("div",{className:"terminal-extra-keys",role:"toolbar","aria-label":o("terminal.extraKeys"),children:v1.flat().map(e=>{let i="ctrl"===e||"alt"===e;return(0,r.jsx)("button",{type:"button",tabIndex:-1,className:i&&t[e]?"is-active":void 0,"aria-pressed":i?t[e]:void 0,"aria-label":i?void 0:v9[e],onPointerDown:t=>((e,t)=>{if(e.preventDefault(),0!==e.button)return;if(a(),"ctrl"===t||"alt"===t)return void s(t);if(n(t),!v2.has(t))return;let r=()=>{n(t),l.current=window.setTimeout(r,50)};l.current=window.setTimeout(r,400)})(t,e),onPointerUp:a,onPointerCancel:a,onPointerLeave:a,onMouseDown:e=>e.preventDefault(),onContextMenu:e=>e.preventDefault(),children:"ArrowLeft"===e||"ArrowRight"===e?(0,r.jsx)("span",{className:"is-rotated",children:v6[e]}):v6[e]},e)})})}function bn(e){let{tab:t,active:n,onRestart:s,onClosed:o,onCloseError:l}=e,{t:a}=(0,tn.s)(),{id:d,cwd:c,restored:u}=t,p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(Promise.resolve()),f=(0,i.useRef)(null),g=(0,i.useRef)({onClosed:o,onCloseError:l});g.current={onClosed:o,onCloseError:l};let[x,v]=(0,i.useState)("connecting"),[b,y]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(0),[C,N]=(0,i.useState)(v0),E=(0,i.useRef)(C),I=(0,i.useSyncExternalStore)(v7,be,()=>!1),$=(0,i.useSyncExternalStore)(vX,vJ,()=>vU),T=(0,i.useRef)($);T.current=$;let M=s0(s9().fontSize)-14+13,R=(0,i.useRef)(M);R.current=M;let A=(0,i.useRef)(()=>{}),L=(0,i.useCallback)(()=>{let e=E.current;return(e.ctrl||e.alt)&&(E.current=v0,N(v0)),e},[]);(0,i.useEffect)(()=>{var e;let t,n,r,i,s,o=p.current;if(!o)return;let l=!1,a=null,g=!1,x=!1,b=!1;v("connecting"),y(null),k(null);let j=()=>{let e=getComputedStyle(o);return{fontFamily:e.getPropertyValue("--font-mono").trim()||"monospace",fontWeight:on(e.getPropertyValue("--font-mono-weight"))}},S=new vH.B({cursorBlink:!0,...j(),fontSize:R.current,lineHeight:1.25,scrollback:8e3,screenReaderMode:!0,disableStdin:!0,theme:vK[T.current]});h.current=S;let C=new vB.Y;S.loadAddon(C),S.open(o),S.attachCustomKeyEventHandler(e=>{if("keydown"!==e.type)return!0;let t=e.key.toLowerCase();return!((e.ctrlKey||e.metaKey)&&"v"===t||(e.ctrlKey||e.metaKey)&&"c"===t&&S.hasSelection())});let N=(e=e=>{l||(b=!0,S.options.disableStdin=!0,y(e.message),v("error"))},n=Promise.resolve(),r=!1,i=null,s=t=>{r||(n=n.then(async()=>{r||(t===i&&(i=null),await vQ(`/api/terminal/${encodeURIComponent(d)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))}).catch(t=>{r=!0,e(t)}))},{write(e){if(!r)for(let t of e.match(/[\s\S]{1,32768}/gu)??[])i&&i.data.length+t.length<=65536?i.data+=t:s(i={type:"input",data:t})},resize(e,t){i=null,s({type:"resize",cols:e,rows:t})},stop:()=>(r=!0,i=null,n)});f.current=N;let E=S.onData(e=>{!g||x||b||N.write(v5(e,L()))}),I=()=>{o.offsetWidth&&o.offsetHeight&&C.fit()},$=S.onResize(e=>{let{cols:t,rows:n}=e;!g||x||b||N.resize(Math.max(2,t),Math.max(2,n))});A.current=I;let M=new ResizeObserver(I);M.observe(o);let z=om(()=>{if(l)return;let e=j();S.options.fontFamily=e.fontFamily,S.options.fontWeight=e.fontWeight,I()}),P=()=>{if(l||x||!navigator.onLine)return;a?.close();let e=new URLSearchParams({holder:e_()});void 0!==t&&e.set("after",String(t)),(a=eV("terminal",new EventSource(`/api/terminal/${encodeURIComponent(d)}/events?${e}`),c)).onmessage=e=>{let n=JSON.parse(e.data);if("output"===n.type){if(n.reset)S.reset();else if(void 0!==t&&n.offset<=t)return;S.write(n.data),t=n.offset}else x=!0,g=!1,S.options.disableStdin=!0,a?.close(),k("exit"===n.type?n.exitCode:null),v("exited")},a.onopen=()=>{g=!0,!b&&(S.options.disableStdin=!1,v("ready"),I(),N.resize(Math.max(2,S.cols),Math.max(2,S.rows)),o.offsetWidth&&o.offsetHeight&&S.focus())},a.onerror=()=>{l||x||(g=!1,S.options.disableStdin=!0,v(a?.readyState===EventSource.CLOSED?"error":"connecting"))}};m.current=(async()=>{I(),u||w>0?await vQ(`/api/terminal/${encodeURIComponent(d)}`):await vQ("/api/terminal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:d,cwd:c,cols:S.cols,rows:S.rows})}),P()})().catch(e=>{l||(y(e.message),v("error"))});let W=()=>{g=!1,S.options.disableStdin=!0,a?.close(),x||b||v("connecting")},O=e=>{e.persisted&&P()};return window.addEventListener("pagehide",W),window.addEventListener("pageshow",O),window.addEventListener("offline",W),window.addEventListener("online",P),()=>{l=!0,a?.close(),N.stop(),M.disconnect(),z(),E.dispose(),$.dispose(),window.removeEventListener("pagehide",W),window.removeEventListener("pageshow",O),window.removeEventListener("offline",W),window.removeEventListener("online",P),S.dispose(),h.current=null,A.current=()=>{}}},[d,c,u,w,L]),(0,i.useEffect)(()=>{h.current&&(h.current.options.theme=vK[$])},[$]),(0,i.useEffect)(()=>{let e=h.current;e&&e.options.fontSize!==M&&(e.options.fontSize=M,A.current())},[M]),(0,i.useEffect)(()=>{n&&h.current?.focus()},[n]),(0,i.useEffect)(()=>{if(!t.closing)return;let e=!1;return h.current&&(h.current.options.disableStdin=!0),(async()=>{await m.current,await f.current?.stop(),await vQ(`/api/terminal/${encodeURIComponent(d)}`,{method:"DELETE",keepalive:!0}),e||g.current.onClosed()})().catch(t=>{e||(y(t.message),v("error"),g.current.onCloseError())}),()=>{e=!0}},[d,t.closing]);let z="dark"===$?"light":"dark",P="light"===z?"terminal.lightTheme":"terminal.darkTheme";return(0,r.jsxs)("section",{className:"terminal-panel","data-terminal-theme":$,"aria-label":a("terminal.title"),children:[(0,r.jsxs)("header",{className:"terminal-panel-header",children:[(0,r.jsxs)("div",{className:"terminal-panel-path",children:[(0,r.jsx)("span",{className:`terminal-status-dot is-${x}`,title:a(`terminal.${x}`)}),(0,r.jsx)("span",{title:c,children:c})]}),(0,r.jsxs)("div",{className:"terminal-panel-actions",children:["error"===x&&(0,r.jsx)("button",{type:"button",onClick:()=>S(e=>e+1),disabled:!!t.closing,title:a("terminal.reconnect"),"aria-label":a("terminal.reconnect"),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>(function(e){if(e!==vJ()){vV=e;try{window.localStorage.setItem(v_,e)}catch{}vG()}})(z),title:a(P),"aria-label":a(P),children:"light"===z?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"})]}):(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}),(0,r.jsx)("button",{type:"button",onClick:s,disabled:!!t.closing,title:a("terminal.restart"),"aria-label":a("terminal.restart"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M20 11a8 8 0 1 0-2.34 5.66"}),(0,r.jsx)("polyline",{points:"20 4 20 11 13 11"})]})})]})]}),(0,r.jsxs)("div",{children:[b&&(0,r.jsx)("div",{className:"terminal-panel-error",role:"alert",children:b}),"exited"===x&&(0,r.jsx)("div",{className:"terminal-panel-exit",role:"status",children:null===j?a("terminal.exited"):a("terminal.exitCode",{code:j})})]}),(0,r.jsx)("div",{className:"terminal-xterm",children:(0,r.jsx)("div",{ref:p,className:"terminal-xterm-host"})}),I&&(0,r.jsx)(bt,{modifiers:C,onKey:e=>{let t=h.current;if(!t)return;let n=function(e,t,n){let r=t.ctrl||t.alt,i=v4[e];if(i)return r?`\x1b[1;${v3(t)}${i}`:n?`\x1bO${i}`:`\x1b[${i}`;let s=v8[e];return s?r?`\x1b[${s};${v3(t)}~`:`\x1b[${s}~`:"Escape"===e?t.alt?"\x1b\x1b":"\x1b":"Tab"===e?t.alt?"\x1b ":" ":v5(e,t)}(e,L(),t.modes.applicationCursorKeysMode);t.input(n,!0)},onToggleModifier:e=>{let t={...E.current,[e]:!E.current[e]};E.current=t,N(t)}})]})}let br="pi-web:terminal-tabs";function bi(e){return{id:Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),cwd:e}}function bs(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let bo=[48,120,240,420,720];var bl=n(63384);let ba="pi-web:tab-open-session";function bd(){try{return window.sessionStorage}catch{return null}}function bc(e){if("string"!=typeof e||0===e.length)return null;if(e.startsWith("{"))try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))return null;if("session"===t.kind&&"string"==typeof t.sessionId&&t.sessionId)return{kind:"session",sessionId:t.sessionId};if("new"===t.kind&&"string"==typeof t.cwd&&t.cwd.trim())return{kind:"new",cwd:t.cwd};return null}catch{return null}return{kind:"session",sessionId:e}}function bu(e,t){t.setItem(ba,JSON.stringify(e))}let bp=new Set(lR.kU);function bh(e){let t=e.at(-1);return t?`agent:${t.sessionId}`:null}function bm(){var e,t;let n,u,x,v,b,y,j,k,w,S,C,N,E,I,$=(0,s.useRouter)(),T=(0,s.useSearchParams)(),[M,R]=(0,i.useState)(()=>{let e;return{requestedCwd:e=T.get("cwd")?.trim()||null,sessionId:e?null:T.get("session")||null,sidebarCollapsed:"collapsed"===T.get("sidebar")}});(0,aF.D)(),ob();let{locale:A,t:L}=(0,tn.s)(),z=tp(),P=(0,i.useSyncExternalStore)(td,tc,tu);(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=new Set,i=!1,s=()=>{n=null,function(e){let{hasFocusedEditable:t,innerHeight:n,viewportHeight:r,viewportScale:i}=e;return!!t&&n/(i>0?i:1)-r>60}({hasFocusedEditable:bs(),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?(t.style.setProperty("--app-viewport-height",`${e.height}px`),t.dataset.keyboardOpen="true"):(t.style.removeProperty("--app-viewport-height"),delete t.dataset.keyboardOpen);let r=0!==window.scrollX||0!==window.scrollY,i=.01>Math.abs(e.scale-1);r&&i&&window.scrollTo(0,0)},o=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(s),(()=>{if(i)return;i=!0;let e=0,t=()=>{if(e>=bo.length){i=!1;return}let n=bo[e++],o=window.setTimeout(()=>{r.delete(o),s(),t()},n);r.add(o)};t()})()},l=()=>{bs()&&o()};return o(),e.addEventListener("resize",o),e.addEventListener("scroll",o),window.addEventListener("resize",o),window.addEventListener("focusin",o),window.addEventListener("focusout",o),window.addEventListener("pageshow",o),document.addEventListener("compositionstart",l),document.addEventListener("compositionupdate",l),document.addEventListener("compositionend",l),document.addEventListener("input",l),document.addEventListener("keyup",l),()=>{for(let t of(e.removeEventListener("resize",o),e.removeEventListener("scroll",o),window.removeEventListener("resize",o),window.removeEventListener("focusin",o),window.removeEventListener("focusout",o),window.removeEventListener("pageshow",o),document.removeEventListener("compositionstart",l),document.removeEventListener("compositionupdate",l),document.removeEventListener("compositionend",l),document.removeEventListener("input",l),document.removeEventListener("keyup",l),null!==n&&window.cancelAnimationFrame(n),r))window.clearTimeout(t);r.clear(),t.style.removeProperty("--app-viewport-height"),delete t.dataset.keyboardOpen}},[]),(0,i.useEffect)(()=>{"Notification"in window&&"granted"===Notification.permission&&uu(A)},[A]);let{soundEnabled:W,onSoundToggle:O,playDoneSound:F,unlockAudio:D,holdAudio:B,soundEnabledRef:H}=function(){let[e,t]=(0,i.useState)(()=>{try{let e=localStorage.getItem("pi-sound-enabled");return null===e||"true"===e}catch{return!0}}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),s=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),o=(0,i.useRef)(0),l=(0,i.useRef)(0),a=(0,i.useRef)(void 0),d=(0,i.useCallback)(e=>{clearTimeout(a.current),a.current=setTimeout(()=>{0===o.current&&0===l.current&&e.suspend().catch(()=>{})},1e3)},[]),c=(0,i.useCallback)((e,t)=>{o.current++,e.resume().then(t).catch(()=>{}).then(()=>{o.current--,d(e)})},[d]),u=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!e&&!n.current)return;let t=s();t&&"running"!==t.state&&c(t,()=>{})},[s,c]),p=(0,i.useCallback)(()=>{let e=!n.current;e?u(!0):r.current?.suspend().catch(()=>{}),n.current=e;try{localStorage.setItem("pi-sound-enabled",String(e))}catch{}t(e)},[u]),h=(0,i.useCallback)(()=>{if(l.current++,clearTimeout(a.current),n.current){let e=s();e&&"running"!==e.state&&c(e,()=>{})}let e=!1;return()=>{!e&&(e=!0,l.current--,r.current&&d(r.current))}},[s,c,d]);return{soundEnabled:e,onSoundToggle:p,playDoneSound:(0,i.useCallback)(()=>{if(!n.current)return;let e=s();if(!e)return;let t=Date.now();c(e,()=>{if(n.current&&!(Date.now()-t>3e3))try{let t;t=e.currentTime,[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),s=e.createGain();i.connect(s),s.connect(e.destination),i.type="sine",i.frequency.value=n;let o=t+.18*r;s.gain.setValueAtTime(0,o),s.gain.linearRampToValueAtTime(.18,o+.02),s.gain.exponentialRampToValueAtTime(.001,o+.45),i.start(o),i.stop(o+.45)})}catch{}})},[s,c]),unlockAudio:u,holdAudio:h,soundEnabledRef:n}}(),[_,U]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{U("true"===localStorage.getItem("pi-quote-selection-enabled"))}catch{}},[]);let K=(0,i.useCallback)(e=>{U(e);try{localStorage.setItem("pi-quote-selection-enabled",String(e))}catch{}},[]),q=(0,i.useRef)(new Set),[V,Z]=(0,i.useState)(new Set),J=(0,i.useCallback)(()=>{H.current&&F()},[F,H]),[G,Y]=(0,i.useState)(null),X=(0,i.useRef)(G);X.current=G;let[Q,ee]=(0,i.useState)(null),et=null!==Q&&Q===G?.id?Q:null;(0,i.useEffect)(()=>{ee(null)},[G?.id]);let en=(0,i.useCallback)(e=>{ee("trajectory"===e?X.current?.id??null:null)},[]),er=(0,i.useCallback)(()=>{let e=X.current?.id;e&&(aM().catch(()=>{}),(0,bl.J)(e))},[]),[ei,es]=(0,i.useState)([]),eo=(0,i.useCallback)(e=>{es(e),Y(t=>{if(!t)return t;let n=e.find(e=>e.id===t.id);return n?{...t,...n,detailsPending:n.detailsPending,relation:n.relation,branch:n.branch,isWorktree:n.isWorktree}:t})},[]),el=(0,i.useMemo)(()=>G?[...ei.filter(e=>e.id!==G.id),G]:ei,[G,ei]),ea=(0,i.useMemo)(()=>{var e;return(e=G?.id)?d(el).find(t=>t.root.id===e||t.subagents.some(t=>t.id===e))??null:null},[G?.id,el]),[ed,ec]=(0,i.useState)(()=>new Set),eu=(0,i.useCallback)(e=>{ec(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]);e=ed.size>0,(0,i.useEffect)(()=>{if(!e)return;let t=e=>{e.preventDefault(),e.returnValue=!0};return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e]);let ep=ea?(n=c(t=ea.subagents,ed))>0?{count:n,running:!0}:{count:t.length,running:!1}:null,eh=ep?.running?L("agentSwitcher.titleRunning",{count:ep.count}):L("agentSwitcher.title"),[em,ef]=(0,i.useState)(null),[eg,ex]=(0,i.useState)("initial"),ev=(0,i.useRef)(null),eb=(0,i.useRef)(null),[ey,ej]=(0,i.useState)(null),ek=(0,i.useRef)(null),ew=(0,i.useCallback)(e=>{e&&e.cwd===ek.current?.cwd&&(ek.current=null),ej(e)},[]),eS=(0,i.useRef)(null),eC=(0,i.useRef)(null),[eN,eE]=(0,i.useState)(null),eI=(0,i.useCallback)(e=>{eC.current=e,eE(null)},[]),[e$,eT]=(0,i.useState)(()=>M.requestedCwd?"validating":"idle"),[eM,eR]=(0,i.useState)(null),[eA,eL]=(0,i.useState)(0),[ez,eP]=(0,i.useState)(0),eW=(0,i.useRef)(new Map),eO=(0,i.useCallback)((e,t)=>{eW.current.set(e,t)},[]),[eF,eD]=(0,i.useState)(null),eH=(0,i.useCallback)(e=>{eD(t=>t===e?null:t)},[]),[e_,eU]=(0,i.useState)(0),[eK,eq]=(0,i.useState)(null),[eV,eZ]=(0,i.useState)(0),[eY,eX]=(0,i.useState)(null),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useState)(!1),[e4,e8]=(0,i.useState)(null),[e3,e5]=(0,i.useState)(!1),[e6,e9]=(0,i.useState)(!1),[e7,te]=(0,i.useState)(!1),[tt,tr]=(0,i.useState)(()=>!M.sidebarCollapsed),ti=(0,i.useRef)(!M.sidebarCollapsed),[ts,to]=(0,i.useState)(!1),[tl,ta]=(0,i.useState)(!1),tm=ts&&tl&&!z;(0,i.useEffect)(()=>{(!ts||z)&&ta(!1)},[ts,z]);let[tg,tx]=(0,i.useState)(!1),tv=P&&null===et?ep?.running&&!tg?{count:ep.count,running:!0}:null:null,tb=tg?L("chat.close"):tv?L("chat.moreControlsAgentsRunning",{count:tv.count}):L("chat.moreControls"),[ty,tj]=(0,i.useState)(!1),tk=(0,i.useRef)(260),tw=(0,i.useRef)(560),tS=(0,i.useCallback)(()=>th(.42*window.innerWidth,360,640),[]),tC=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:n,rightPanelWidth:r}=e;if(t<=640)return 480;let i=t<960;return Math.min(480,t-(i?320:420)-(!i&&n?r:0))})({viewportWidth:window.innerWidth,rightPanelOpen:ts,rightPanelWidth:tw.current}),[ts]),tN=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,sidebarOpen:n,sidebarWidth:r}=e;return t<960?1200:Math.min(1200,t-420-(n?r:0))})({viewportWidth:window.innerWidth,sidebarOpen:tt,sidebarWidth:tk.current}),[tt]),tE=tf({ariaLabel:L("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:tC,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:tk}),tI=tf({ariaLabel:L("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:560,getDefaultWidth:tS,getMaxWidth:tN,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:tw}),t$=tE.reclampWidth,tT=tI.reclampWidth;(0,i.useEffect)(()=>{tr(!z&&ti.current)},[z]),(0,i.useEffect)(()=>{tj(!0)},[]),(0,i.useEffect)(()=>{ts&&(t$(),tT())},[tT,t$,ts]);let tM=(0,i.useRef)(null),[tR,tA]=(0,i.useState)({}),tL=(0,i.useRef)(null),tP=(0,i.useRef)(null),[tW,tO]=(0,i.useState)([]),[tF,tD]=(0,i.useState)(null),[tB,t_]=(0,i.useState)(!1),tU=(0,i.useRef)(null),tK=xr(tW),tV=(0,i.useCallback)((e,t,n,r)=>{tO(e),tD(t),t_(r),tU.current=n},[]),tZ=(0,i.useCallback)(e=>{tU.current?.(e)},[]),[tJ,tG]=(0,i.useState)(null),[tY,tX]=(0,i.useState)(null),[tQ,t0]=(0,i.useState)(!1),t1=(0,i.useRef)(null),t2=(0,i.useRef)(0),t4=(0,i.useCallback)(e=>{tG(e),t0(!1)},[]),t8=(0,i.useCallback)(e=>{tX(e)},[]),t3=(0,i.useCallback)(e=>{t2.current+=1,t1.current=e,t0(!1)},[]),t5=(0,i.useRef)(null),t6=(0,i.useCallback)(e=>{t5.current=e},[]);(0,i.useEffect)(()=>{null===eJ.trackingSince&&"u">typeof document&&(eJ.trackingSince=Date.now(),document.addEventListener("visibilitychange",eG))},[]);let[t9,t7]=(0,i.useState)(null),ne=(0,i.useCallback)(e=>{t7(e)},[]),[nt,nn]=(0,i.useState)(null),nr=(0,i.useRef)(null),ni=(0,i.useCallback)((e,t)=>{(0,ia.D)(t).then(()=>{nr.current&&clearTimeout(nr.current),nn(e),nr.current=setTimeout(()=>nn(null),1400)})},[]);(0,i.useEffect)(()=>()=>{nr.current&&clearTimeout(nr.current)},[]);let[no,nl]=(0,i.useState)(null),na=(0,i.useCallback)(e=>{nl(e)},[]),[nd,nc]=(0,i.useState)(null),nu=(0,i.useCallback)(e=>{nc(e)},[]),[np,nh]=(0,i.useState)("overview"),[nm,nf]=(0,i.useState)(null),[ng,nx]=(0,i.useState)(null);(0,i.useEffect)(()=>{tK||nf(e=>"branches"===e?null:e)},[tK]),(0,i.useEffect)(()=>{ea||nf(e=>"agents"===e?null:e)},[ea]),(0,i.useEffect)(()=>{tm&&nf(null)},[tm]),(0,i.useEffect)(()=>{null!==et&&nf(null)},[et]);let nv=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];z&&tr(!1),"session"===e&&nh("overview"),nf(t=>t===e?null:e),z&&P&&t&&tx(!0)},[z,P]),nb=(0,i.useRef)(null),ny=(0,i.useCallback)(e=>{nf(e=>"debug"===e?null:e),e&&requestAnimationFrame(()=>eB(document,nb.current))},[]),nj=(0,i.useCallback)(()=>{if(tQ)return;let e=t1.current;if(!e)return;let t=++t2.current;t0(!0),e().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{t2.current===t&&t0(!1)})},[tQ]),nk=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"overview";z&&tr(!1),tx(!1),nh(e),nf("session")},[z]),nw=(0,i.useCallback)(e=>{eq(e)},[]),nS=(0,i.useCallback)(()=>{z&&(nf(null),tx(!1)),tr(e=>{let t=!e;return z||(ti.current=t),t})},[z]),nC=(0,i.useCallback)(()=>{tr(!1),nf(null),tx(e=>!e)},[]),nN=(0,i.useCallback)(()=>{z&&(tr(!1),nf(null),tx(!1)),to(e=>!e)},[z]),nE=(0,i.useCallback)(()=>{nf(null),ta(e=>!e)},[]);(0,i.useEffect)(()=>{if(!tg)return;let e=e=>{let t=tP.current;t&&e.composedPath().includes(t)||tx(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),tx(!1))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[tg]),(0,i.useEffect)(()=>{tx(!1)},[z,P,G?.id,eg]),(0,i.useEffect)(()=>{if(!nm||!tL.current)return;let e=()=>{let e=tL.current.getBoundingClientRect();if("agents"===nm){let t=Math.min(420,e.width);nx({top:e.bottom,left:z?e.left:e.right-t,width:t});return}nx({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(tL.current),()=>t.disconnect()},[nm,z]);let[nI,n$]=(0,i.useState)([]),[nT,nM]=(0,i.useState)(null),nR=(0,i.useRef)(new Map),[nA,nL]=(0,i.useState)(0),nz=(0,i.useRef)(0),[nP,nW]=(0,i.useState)([]),[nO,nF]=(0,i.useState)(!1),[nD,nB]=(0,i.useState)([]),nH=[...nI,...nP.map(e=>({id:e.id,label:(0,tH.WP)(e.cwd)||e.cwd,filePath:e.cwd,kind:"terminal",closing:!!e.closing})),...nD.map(e=>{let t=e.side?ei.find(t=>t.id===e.sessionId):void 0,n=t?l(t,e.label):e.label;return{id:`agent:${e.sessionId}`,label:n,filePath:n,kind:e.side?"side":"agent"}})];(0,i.useEffect)(()=>{try{let e=function(e){try{let t=JSON.parse(e??"null"),n=[];for(let e of Array.isArray(t?.tabs)?t.tabs:[])e&&"string"==typeof e.id&&/^[a-f0-9]{32}$/.test(e.id)&&"string"==typeof e.cwd&&e.cwd.trim()&&!n.some(t=>t.id===e.id||t.cwd===e.cwd)&&n.push({id:e.id,cwd:e.cwd,restored:!0});return{tabs:n,activeId:n.some(e=>e.id===t.activeId)?t.activeId:null,open:t?.open===!0}}catch{return{tabs:[],activeId:null,open:!1}}}(window.sessionStorage.getItem(br));nW(e.tabs),e.activeId&&(nM(e.activeId),to(e.open))}catch{}nF(!0)},[]),(0,i.useEffect)(()=>{if(nO)try{window.sessionStorage.setItem(br,JSON.stringify({tabs:nP.map(e=>{let{id:t,cwd:n}=e;return{id:t,cwd:n}}),activeId:nT,open:ts}))}catch{}},[nP,nT,ts,nO]);let n_=(0,i.useCallback)((e,t,n,r)=>{e!==nz.current?function(e,t,n,r,i){for(let[s,o]of e)if(o.generation===t)return void e.set(s,{...o,tabs:dw(o.tabs,n,r,i)})}(nR.current,e,t,n,r):n$(e=>dw(e,t,n,r))},[]),nU=(0,i.useCallback)((e,t)=>{if(e===t)return;let n=nT?.startsWith("file:")?nT:null,r=function(e,t,n,r,i){if(t===n)return r;t&&e.set(t,{...r,generation:i});let s=e.get(n);return s?(e.delete(n),{tabs:s.tabs,activeTabId:s.activeTabId,open:s.open}):{tabs:[],activeTabId:null,open:!1}}(nR.current,e,t,{tabs:nI,activeTabId:n,open:ts&&!!n},nz.current);nz.current+=1,nL(nz.current),n$(r.tabs),nB([]),(!nT||n||nT.startsWith("agent:"))&&(nM(r.activeTabId),to(r.open))},[nT,nI,ts]),nK=(0,i.useCallback)((e,t)=>{tM.current?.insertText(tq(e,t)),z&&(to(!1),tr(!1))},[z]),nq=(0,i.useCallback)(e=>{let t=e.map(e=>tq(e,!1)).join("");t&&tM.current?.insertText(t),z&&(to(!1),tr(!1))},[z]),nV=(0,i.useCallback)((e,t,n)=>{let r,i,s,o;tM.current?.insertText((r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),s=e.includes(" ")?`@"${e}"`:`@${e}`,o=r===i?`:${r}`:`:${r}-${i}`,`${s}${o} `)),z&&(to(!1),tr(!1))},[z]),nZ=M.sessionId,nJ=M.sessionFromTab?null:M.sessionId,[nG,nY]=(0,i.useState)(null),nX=(0,i.useRef)(null),[nQ,n0]=(0,i.useState)(()=>!nZ);(0,i.useLayoutEffect)(()=>{var e;let t=(e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:bd();if(!e)return null;try{return bc(e.getItem(ba))}catch{return null}}(),M.requestedCwd||M.sessionId||!e?M:"session"===e.kind?{...M,sessionId:e.sessionId,sessionFromTab:!0}:{...M,requestedCwd:e.cwd});t!==M&&(R(t),t.sessionId&&n0(!1))},[M]);let n1=(0,i.useRef)(!1),n2=(0,i.useRef)(!1),n4=(0,i.useRef)(0),n8=(0,i.useCallback)(()=>{n4.current+=1},[]);(0,i.useEffect)(()=>{if(G){!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:h();if(n)try{let r=m(n);r[e]=t,n.setItem(p,JSON.stringify(r))}catch{}}(G.projectKey??nX.current??g(G),G.id),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:bd();if(t&&e)try{bu({kind:"session",sessionId:e},t)}catch{}}(G.id);return}em&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:bd(),n=e.trim();if(t&&n)try{bu({kind:"new",cwd:n},t)}catch{}}(em)},[em,G]),(0,i.useEffect)(()=>{let e=M.requestedCwd;if(!e)return;let t=new AbortController;return eT("validating"),eR(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async t=>{let n=await t.json().catch(()=>({}));if(!t.ok||!n.cwd)throw Error(n.error??`HTTP ${t.status}`);n1.current=!0;let r=`initial:${e}`;ex(r),ev.current=`new:${r}:${n.cwd}`,ef(n.cwd),eT("ready"),new URLSearchParams(window.location.search).get("cwd")||$.replace(`?cwd=${encodeURIComponent(n.cwd)}`,{scroll:!1})}).catch(e=>{t.signal.aborted||(eR(e instanceof Error?e.message:String(e)),eT("error"))}),()=>t.abort()},[M,$]);let n3=(0,i.useCallback)((e,t)=>{let n=++n4.current,r=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:h();if(!t)return null;try{let n=m(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);if(!r)return;let i=i=>{if(n!==n4.current)return;let s=i?.sessions.find(e=>e.id===r);if(!s){i&&f(e);return}if(g(s)!==e)return void f(e);let o=ev.current;o&&sR(o,sw(t)),ev.current=null,Y(s),eP(e=>e+1),new URLSearchParams(window.location.search).get("session")!==s.id&&$.replace(`?session=${encodeURIComponent(s.id)}`,{scroll:!1})};ei.length>0?i({sessions:ei}):fetch("/api/sessions").then(e=>e.ok?e.json():null).then(i).catch(()=>{})},[$,ei]),n5=(0,i.useCallback)((e,t,n)=>{n8();let r=em??nG;if(nY(e),!e)return;let i=n2.current;n2.current=!1;let s=n??t??e,o=nX.current??(G?g(G):null);if(nX.current=s,n1.current){n1.current=!1;return}if(r===e&&o!==s||o===s&&(null!==G||r===e))return;let l=ev.current;l&&r&&sR(l,sw(r));let a="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,d=`new:${a}:${e}`;sR(sw(e),d),ex(a),ev.current=d,Y(null),ef(t=>t&&t!==e?null:t),eP(e=>e+1),tO([]),tD(null),t_(!1),tG(null),tX(null),t0(!1),nf(e=>"debug"===e?e:null),o!==s&&(nU(o,s),i||n3(s,e)),$.replace(window.location.pathname,{scroll:!1})},[nG,nU,n8,em,$,G,n3]),n6=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;eD(n?{sessionId:e.id,entryId:n,blockIndex:r}:null),n&&ee(null),n8();let s=ev.current,o=em??(null===G?nG:null);s&&o&&sR(s,sw(o)),ev.current=null;let l=g(e);if(nX.current!==l&&(nU(nX.current,l),nf(e=>"debug"===e?e:null)),nX.current=l,!t&&G){let t=g(G)===g(e);if(G.id===e.id&&t){z&&tr(!1);return}}ef(null),Y(e),eP(e=>e+1),tO([]),tD(null),t_(!1),tU.current=null,tG(null),tX(null),t0(!1),n0(!0),!z||t||i?.keepSidebarOpen||tr(!1),t&&(n1.current=!0),t&&new URLSearchParams(window.location.search).get("session")===e.id||$.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[nG,nU,n8,$,z,em,G]),n9=(0,i.useCallback)((e,t,n,r)=>{n8();let i=`new:${e}:${t}`,s=ev.current,o=em??(null===G?nG:null);if(r?.carryComposer&&null===G&&s){let e=tM.current;e?e.rekeyDraft(s,i):sR(s,i),eE(eC.current)}else s&&o&&o!==t&&sR(s,sw(o));let l=n??(t===nG?nX.current:null)??t;nX.current!==l&&nU(nX.current,l),nX.current=l,sN(i)||sR(sw(t),i),ev.current=i,ex(e),Y(null),ef(t),eP(e=>e+1),tO([]),tD(null),t_(!1),tG(null),tX(null),t0(!1),nf(e=>"debug"===e?e:null),z&&tr(!1),$.replace(`?cwd=${encodeURIComponent(t)}`,{scroll:!1}),z||eS.current||requestAnimationFrame(()=>{document.activeElement?.closest("[aria-modal='true']")||tM.current?.focus()})},[nG,nU,n8,z,em,$,G]);!function(e){let{onNewSession:t,activeCwd:n}=e;(0,i.useEffect)(()=>{let e=e=>{if("Escape"===e.key)return void function(e){if("Escape"!==e.key||e.defaultPrevented||!o)return;let t=e.target?.tagName;"TEXTAREA"!==t&&"INPUT"!==t&&(e.preventDefault(),o())}(e);if(e.ctrlKey&&e.altKey&&("n"===e.key.toLowerCase()||"Dead"===e.key&&"KeyN"===e.code)){if(!n||!t)return;e.preventDefault(),t(n)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[n,t])}({onNewSession:e=>n9(`kb-${Date.now()}`,e),activeCwd:nG});let n7=(0,i.useCallback)(e=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{let n=t?.sessions.find(t=>t.id===e);n&&Y(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),re=(0,i.useCallback)((e,t)=>{eL(e=>e+1),ev.current===t&&(n8(),ev.current=null,ef(null),Y(e),n7(e.id),$.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[n8,$,n7]),rt=(0,i.useCallback)(e=>{let{targetSession:t,title:n,body:r,tag:i}=e;if(!("Notification"in window))return;let s=()=>{ul({title:n,body:r,sessionUrl:t?`/?session=${encodeURIComponent(t.id)}`:"/",tag:i,onClick:()=>{window.focus(),t&&n6(t)}})};"granted"===Notification.permission?(s(),uu(A)):"default"===Notification.permission&&Notification.requestPermission().then(e=>{"granted"===e&&(s(),uu(A))})},[n6,A]),rn=(0,i.useCallback)(e=>{eL(e=>e+1),eU(e=>e+1),e.aborted||e.subagentsActive||a(G?.relation)||!us()||(G&&Z(e=>{if(e.has(G.id))return e;let t=new Set(e);return t.add(G.id),t}),rt({targetSession:G,title:G?.name??L("i18n.sessionComplete"),body:L("i18n.taskFinished"),tag:G?`pi-session-complete:${G.id}`:"pi-session-complete"}))},[rt,G,L]);(0,i.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&document.hasFocus()&&Z(e=>0===e.size?e:new Set)};return e(),document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e)}},[]);let rr=(0,i.useCallback)(e=>{var t;!a(G?.relation)&&us()&&(t=q.current,!(!lm(e)||t.has(e.id))&&(t.add(e.id),1)&&rt({targetSession:G,title:L("i18n.attentionNeeded"),body:"custom"===e.method?L("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[rt,G,L]),ri=(0,i.useCallback)(()=>{eU(e=>e+1)},[]),rs=(0,i.useRef)(null),ro=(0,i.useCallback)(e=>{bp.has(e)||rs.current||(rs.current=setTimeout(()=>{rs.current=null,eU(e=>e+1)},1e3))},[]);(0,i.useEffect)(()=>()=>{rs.current&&clearTimeout(rs.current)},[]);let rl=(0,i.useCallback)(e=>{n8(),ev.current=null,eL(e=>e+1),eP(e=>e+1),ef(null),Y(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),n7(e),$.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[n8,$,n7]),ra=(0,i.useCallback)(()=>{n0(!0),nJ&&(n2.current=!0)},[nJ]),rd=(0,i.useCallback)(e=>{n8(),eL(e=>e+1);let t=X.current;if(t?.id===e){!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:bd();if(t&&e)try{let n=bc(t.getItem(ba));if(n?.kind!=="session"||n.sessionId!==e)return;t.removeItem(ba)}catch{}}(e);let n=t.cwd,r="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;ex(r),ev.current=n?`new:${r}:${n}`:null,Y(null),ef(n??null),eP(e=>e+1),tO([]),tD(null),t_(!1),tG(null),tX(null),t0(!1),nf(e=>"debug"===e?e:null),$.replace(n?`?cwd=${encodeURIComponent(n)}`:window.location.pathname,{scroll:!1})}},[n8,$]),rc=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,s=n?.page,o=`file:${e}`;n$(n=>(function(e,t){let n=e.find(e=>e.id===t.tabId);if(!n)return[...e,{id:t.tabId,label:t.fileName,filePath:t.filePath,sourceSessionId:t.sourceSessionId,initialDisplayMode:t.modeHint,page:t.page,viewerState:t.modeHint?{displayMode:t.modeHint,scrollTop:0,scrollLeft:0}:void 0,viewerRevision:0}];let r=!!(t.sourceSessionId&&n.sourceSessionId!==t.sourceSessionId),i=n.page!==t.page;return r||t.modeHint||i?e.map(e=>{if(e.id!==t.tabId)return e;let n={...e},s=!1;return r&&(n.sourceSessionId=t.sourceSessionId,s=!0),i&&(n.page=t.page,s=!0),t.modeHint&&(n.initialDisplayMode=t.modeHint,n.viewerState={displayMode:t.modeHint,wrapLines:e.viewerState?.wrapLines,scrollTop:0,scrollLeft:0},s=!0),s&&(n.viewerRevision=(e.viewerRevision??0)+1),n}):e})(n,{fileName:t,filePath:e,modeHint:i,page:s,sourceSessionId:r,tabId:o})),nM(o),to(!0),z&&tr(!1)},[z]),ru=(0,i.useCallback)((e,t)=>{rc(e,(0,tH.WP)(e),{sourceSessionId:G?.id??null,page:t})},[rc,G?.id]),rp=(0,i.useCallback)(e=>{let t=nP.find(t=>t.cwd===e),n=t??bi(e);t||nW(e=>[...e,n]),nM(n.id),to(!0),z&&tr(!1)},[nP,z]),rh=(0,i.useCallback)((e,t,n)=>{nB(r=>{if(r.some(t=>t.sessionId===e))return r;let i=t;for(let e=2;n&&r.some(e=>e.label===i);e+=1)i=`${t} ${e}`;return[...r,{sessionId:e,label:i,...n?{side:!0}:{}}]}),nM(`agent:${e}`),to(!0),z&&tr(!1)},[z]),rm=(0,i.useMemo)(()=>new Set(ts?nD.map(e=>e.sessionId):[]),[nD,ts]),rg=(0,i.useCallback)((e,t)=>{let n,r;t&&tA(n=>({...n,[e.id]:t})),rh(e.id,l(e,t&&((r=t.trim()).startsWith("/")||r.startsWith("!")?null:(n=r.trim().split("\n")[0].trim())?n.length>40?`${n.slice(0,40).trimEnd()}…`:n:null)||L("sideChat.title")),!0),eL(e=>e+1)},[rh,L]),rx=(0,i.useCallback)(async e=>{let t=await lC(e,L);return"error"in t?t.error:(z&&nf(null),rg(t.session,null),null)},[rg,z,L]),rv=nD.filter(e=>e.side&&ed.has(e.sessionId)).map(e=>e.sessionId).join();(0,i.useEffect)(()=>{rv&&eL(e=>e+1)},[rv]);let rb=(0,i.useCallback)(e=>{if(nP.some(t=>t.id===e))return void nW(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"}));if(e.startsWith("agent:")){let t=nD.filter(t=>`agent:${t.sessionId}`!==e);nB(t),nM(n=>n!==e?n:nI.at(-1)?.id??nP.at(-1)?.id??bh(t)),0===nI.length&&0===nP.length&&0===t.length&&to(!1);return}n$(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===nP.length&&0===nD.length&&to(!1),n}),nM(t=>{if(t!==e)return t;let n=nI.filter(t=>t.id!==e);return n.at(-1)?.id??nP.at(-1)?.id??bh(nD)})},[nI,nP,nD]),ry=G?.id;(0,i.useEffect)(()=>{nD.some(e=>e.sessionId===ry)&&rb(`agent:${ry}`)},[nD,rb,ry]);let rj=em??(null===G&&nG?nG:null),rk=null===G&&rj?`new:${eg}:${rj}`:null;(0,i.useLayoutEffect)(()=>{ev.current=rk},[rk]);let rw=(0,i.useCallback)((e,t)=>{null===G&&rj&&e.cwd!==rj&&(eS.current=t,e.projectKey&&e.projectRoot&&ek.current?.cwd!==e.cwd&&(ek.current={cwd:e.cwd,project:{key:e.projectKey,root:e.projectRoot},branch:null}),eb.current?.startNewSessionIn({...e,carryComposer:!0}))},[rj,G]),rS=(0,i.useRef)(rw);rS.current=rw;let rC=(0,i.useCallback)(e=>{eb.current?.openFolderForNewSession(e=>rS.current(e,"project"),e)},[]),rN=(0,i.useCallback)(()=>{eb.current?.openDefaultDirectoryForNewSession(e=>rS.current(e,"project"))},[]),rE=(0,i.useCallback)(()=>{eb.current?.refreshWorktrees()},[]),rI=(0,i.useCallback)(async(e,t)=>{let n=eb.current;if(!n)throw Error("The session sidebar is not mounted");let r=await n.createWorktree(e,t);return"path"in r&&(ek.current={cwd:r.path,project:e,branch:t}),r},[]),r$=(0,i.useCallback)(()=>{eS.current=null},[]),rT=null===G&&rj?(0,r.jsx)(az,{context:function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(e?.cwd===t)return e;if(e?.worktrees?.some(e=>e.path===t))return{...e,cwd:t,currentWorktreePath:t};let r=n?.cwd===t?n:null;if(r&&e?.worktrees&&e.project.key===r.project.key)return{...e,cwd:t,worktrees:[...e.worktrees,{path:t,branch:r.branch,isMain:!1}],currentWorktreePath:t};let i=e?.projects??[],s=r?.project??i.find(e=>e.root===t)??{key:t,root:t},o=s.alias??i.find(e=>e.key===s.key)?.alias;return{cwd:t,project:void 0===o?s:{...s,alias:o},worktrees:null,currentWorktreePath:null,projects:i}}(ey,rj,ek.current),mobile:z,initialFocus:eS.current,onInitialFocusDone:r$,onPick:rw,onUseDefaultDirectory:rN,onOpenFolder:rC,onRefreshWorktrees:rE,onCreateWorktree:rI}):null,rR=null!==G||null!==rj,rA=G?.cwd??rj,rL=nQ&&!rR;(0,i.useEffect)(()=>{rR||nf(e=>"debug"===e?null:e)},[rR]),(0,i.useEffect)(()=>{if(eX(null),e0(!1),e8(null),!rA)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(rA)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);eX(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[rA]);let rz=(0,i.useCallback)(async()=>{if(rA&&!e1){e2(!0),e8(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:rA})}),t=await e.json();if(!e.ok||t.error)return void e8({error:t.error??`HTTP ${e.status}`,...t.reason?{reason:t.reason}:{}});eX(t),e0(!1),eZ(e=>e+1),eP(e=>e+1)}catch(e){e8({error:e instanceof Error?e.message:String(e)})}finally{e2(!1)}}},[e1,rA]),rP=(0,i.useCallback)(()=>{e8(null),e0(!0)},[]),rW=(0,i.useCallback)((e,t)=>{e===rA&&eX(t)},[rA]),rO=nI.find(e=>e.id===nT)??null,rF=nD.find(e=>`agent:${e.sessionId}`===nT)??null,rD=nG?(0,tH.WP)(nG)||nG:null,rB=rD?`${rD} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==rB&&(document.title=rB)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[rB]);let rH=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(rM,{selectedSessionId:G?.id??null,onSelectSession:n6,onNewSession:n9,controlRef:eb,onNewSessionContextChange:ew,initialSessionId:nZ,initialSessionLinked:null!==nJ,skipInitialProjectSelection:null!==M.requestedCwd,onInitialRestoreDone:ra,refreshKey:eA,onSessionDeleted:rd,selectedCwd:G?.cwd??em??null,onCwdChange:n5,onOpenFile:rc,onOpenTerminal:rp,explorerRefreshKey:e_,onExplorerRefresh:ri,onAtMention:nK,onAtMentions:nq,onBackgroundTaskDone:J,hiddenFinishedSessionIds:V,onRunningSessionIdsChange:eu,onSessionsChange:eo,onSessionImported:rl}),(0,r.jsxs)("div",{style:{padding:"8px",flexShrink:0,display:"flex",justifyContent:"space-between",gap:4},children:[[["models",L("common.models")],["skills",L("common.skills")]].map(e=>{let[t,n]=e,i=dI(t)&&!rA;return(0,r.jsxs)("button",{type:"button",onClick:()=>eq(t),disabled:i,title:i?L("settings.projectRequired"):n,"aria-label":n,style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:6,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:i?"default":"pointer",fontSize:12,opacity:i?.35:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)(gQ,{section:t,size:14,strokeWidth:2}),(0,r.jsx)("span",{children:n})]},t)}),(0,r.jsxs)("button",{type:"button",onClick:()=>eq(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:d$();if(!t)return"general";try{let n=dT(t).section;if(!("string"==typeof n&&dC.includes(n)))return"general";return dI(n)&&!e?"general":n}catch{return"general"}}(rA)),title:L("common.settings"),"aria-label":L("common.settings"),style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:6,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)(gQ,{section:"general",size:14,strokeWidth:2}),(0,r.jsx)("span",{children:L("common.settings")})]})]})]}),r_=e=>rR&&eY?.requiresTrust&&!eY.trusted?(0,r.jsxs)("button",{type:"button",onClick:rP,title:L("trust.resourcesNotLoaded"),"aria-label":L("trust.resourcesNotLoaded"),style:{display:"flex",alignItems:"center",justifyContent:e?"flex-start":"center",gap:6,width:e?"100%":void 0,minHeight:e?32:void 0,height:e?void 0:"100%",padding:e?"6px 12px":"0 12px",background:e?"color-mix(in srgb, #d97706 8%, var(--bg-panel))":"none",border:"none",borderRight:e?"none":"1px solid var(--border)",borderBottom:e?"1px solid var(--border)":"none",color:"#d97706",cursor:"pointer",flexShrink:0,fontSize:11,lineHeight:1.35,textAlign:"left"},"data-mobile-trust-banner":e?"true":void 0,children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"M12 8v4"}),(0,r.jsx)("path",{d:"M12 16h.01"})]}),(0,r.jsx)("span",{children:L("trust.resourcesNotLoaded")})]}):null,rU=(e,t)=>(0,r.jsxs)("span",{"aria-hidden":"true",style:{position:"relative",minWidth:15,height:15,padding:"0 4px",display:"grid",placeItems:"center",borderRadius:7,background:e.running?"color-mix(in srgb, var(--accent) 22%, var(--bg-panel))":"var(--bg-selected)",color:"var(--accent)",fontSize:10,lineHeight:1,fontVariantNumeric:"tabular-nums",fontWeight:e.running?600:void 0,...t?{position:"absolute",top:3,right:3,minWidth:13,height:13,padding:"0 3px",fontSize:9}:{}},children:[e.running&&(0,r.jsxs)("svg",{className:"animate-spin motion-reduce:animate-none",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{position:"absolute",top:-3,left:-3,width:"calc(100% + 6px)",height:"calc(100% + 6px)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"11",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),(0,r.jsx)("path",{d:"M23 12a11 11 0 0 0-11-11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),e.count]}),rK=e=>e||rR?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[(0,r.jsx)(ls,{view:null!==et?"trajectory":"chat",onChange:en,trajectoryDisabled:!G,onTrajectoryIntent:er,iconWidth:e?36:void 0}),e&&rq(!0)]}):null,rq=e=>null!==et?null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>nv("agents",e),disabled:!ea,title:eh,"aria-label":eh,"aria-pressed":"agents"===nm,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"agents"===nm?"var(--bg-selected)":"none",border:"none",borderTop:"agents"===nm?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"agents"===nm?"var(--text)":ea?"var(--text-muted)":"var(--text-dim)",cursor:ea?"pointer":"not-allowed",opacity:ea?1:.45,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},"data-mobile-toolbar-action":e?"agents":void 0,children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"agents"===nm?"var(--accent)":"var(--text-dim)"},"aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}),ep&&ep.count>0&&rU(ep,e)]}),tK&&(e?(0,r.jsx)("button",{type:"button",onClick:()=>nv("branches",!0),title:L("i18n.branches"),"aria-label":L("i18n.branches"),"aria-pressed":"branches"===nm,style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:"100%",padding:0,background:"branches"===nm?"var(--bg-selected)":"none",border:"none",borderTop:"branches"===nm?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"branches"===nm?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0},"data-mobile-toolbar-action":"branches",children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"branches"===nm?"var(--accent)":"var(--text-dim)"},"aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}):(0,r.jsx)(xs,{tree:tW,activeLeafId:tF,onLeafChange:tZ,locked:tB,inline:!0,compact:!0,containerRef:tL,open:"branches"===nm,onToggle:()=>nv("branches"),hasSession:!0}))]}),rV=e=>{if(!e&&!rR||null!==et)return null;let t=t9?.tokens,n=t9?.cost??0,i=lK(n),s=t?lq(t):null,o=null!==s?`${s.toFixed(1)}%`:null,l="var(--text-muted)",a=null,d=null;if(no?.contextWindow){let e=no.percent;null!==e&&e>90?l="#ef4444":null!==e&&e>70&&(l="rgba(234,179,8,0.95)"),a=null!==e?`${e.toFixed(0)}% / ${lU(no.contextWindow)}`:`? / ${lU(no.contextWindow)}`,d=null!==e?`${e.toFixed(0)}%`:null}let c=[];if(t&&(c.push(`${L("session.input")}: ${t.input.toLocaleString(A)}`),c.push(`${L("session.output")}: ${t.output.toLocaleString(A)}`),c.push(`${L("session.cacheRead")}: ${t.cacheRead.toLocaleString(A)}`),c.push(`${L("session.cacheWrite")}: ${t.cacheWrite.toLocaleString(A)}`),o&&c.push(`${L("session.cacheHitRate")}: ${o}`),n>0&&c.push(`${L("session.cost")}: $${n.toFixed(4)}`)),no?.contextWindow){let e=no.percent;c.push(`${L("session.context")}: ${null!==e?`${e.toFixed(1)}%`:"?"} / ${no.contextWindow.toLocaleString(A)}`)}let u=c.join(" | "),p=e&&P&&tg,h=!!(t&&(t.input>0||t.output>0)||i||d),m=!!(t&&(t.input>0||t.output>0||t.cacheRead>0)||o||i||a);return(0,r.jsx)("button",{type:"button",onClick:()=>nv("session"),disabled:!rR||p,tabIndex:p?-1:void 0,title:u||L("session.title"),"aria-label":L("session.title"),"aria-pressed":"session"===nm,"aria-hidden":!!p||void 0,className:e?"mobile-session-stats":void 0,"data-mobile-toolbar-stats":e?"true":void 0,style:{marginLeft:0,display:"flex",alignItems:"center",justifyContent:"flex-end",flex:e?1:void 0,minWidth:0,gap:e?7:10,paddingLeft:e?6:12,paddingRight:e?6:12,height:"100%",overflow:"hidden",visibility:p?"hidden":"visible",pointerEvents:p?"none":"auto",background:"session"===nm?"var(--bg-selected)":"none",border:"none",borderTop:"session"===nm?"2px solid var(--accent)":"2px solid transparent",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:rR?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{rR&&!p&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===nm?"var(--text)":"var(--text-muted)"},children:e?(0,r.jsxs)(r.Fragment,{children:[t&&t.input>0&&(0,r.jsxs)("span",{className:"mobile-session-stat-io",style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"8.5",x2:"5",y2:"1.5"}),(0,r.jsx)("polyline",{points:"2 4 5 1.5 8 4"})]}),lU(t.input)]}),t&&t.output>0&&(0,r.jsxs)("span",{className:"mobile-session-stat-io",style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),lU(t.output)]}),i&&(0,r.jsx)("span",{className:"mobile-session-stat-cost",style:{color:"var(--text)",fontWeight:500,flexShrink:0},children:i}),d&&(0,r.jsx)("span",{style:{color:l,flexShrink:0},children:d}),!h&&rR&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-dim)"},children:L("session.title")})]}):(0,r.jsxs)(r.Fragment,{children:[t&&t.input>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"8.5",x2:"5",y2:"1.5"}),(0,r.jsx)("polyline",{points:"2 4 5 1.5 8 4"})]}),lU(t.input)]}),t&&t.output>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),lU(t.output)]}),t&&t.cacheRead>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8.5 5a3.5 3.5 0 1 1-1-2.45"}),(0,r.jsx)("polyline",{points:"6.5 1.5 8.5 2.5 7.5 4.5"})]}),lU(t.cacheRead)]}),o&&(0,r.jsxs)("span",{title:`${L("session.cacheHitRate")}: ${o}`,style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"5",cy:"5",r:"4"}),(0,r.jsx)("circle",{cx:"5",cy:"5",r:"1.2"})]}),o]}),i&&(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--text)",fontWeight:500},children:i}),a&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:l},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M1 9 L1 5 Q1 1 5 1 Q9 1 9 5 L9 9"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"9",y2:"9"})]}),a]}),!m&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:L("session.title")})]})})},rZ=e=>{if(!rR)return null;let t="debug"===nm;return(0,r.jsx)("button",{ref:nb,type:"button",onClick:()=>nv("debug",e),title:L("debug.title"),"aria-label":L("debug.title"),"aria-pressed":t,style:{marginLeft:0,display:"flex",alignItems:"center",justifyContent:"center",width:36,height:"100%",padding:0,background:t?"var(--bg-selected)":"none",border:"none",borderTop:t?"2px solid var(--accent)":"2px solid transparent",...e?{borderRight:"1px solid var(--border)"}:{borderLeft:"1px solid var(--border)"},color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=t?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"debug":void 0,children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:t?"var(--accent)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8 2l1.9 1.9M16 2l-1.9 1.9M9 7.1v-1a3 3 0 0 1 6 0v1"}),(0,r.jsx)("path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6zM12 20v-9"}),(0,r.jsx)("path",{d:"M6.5 9C4.6 8.8 3 7.1 3 5M6 13H2M3 21c0-2.1 1.7-3.9 3.8-4M21 5c0 2.1-1.6 3.8-3.5 4M22 13h-4M17.2 17c2.1.1 3.8 1.9 3.8 4"})]})})},rJ=e=>{let t=e&&P&&tg;return(0,r.jsx)("button",{type:"button",onClick:nN,disabled:t,tabIndex:t?-1:void 0,"aria-controls":"file-panel","aria-expanded":ts,"aria-hidden":!!t||void 0,title:ts?L("files.hidePanel"):L("files.showPanel"),"aria-label":ts?L("files.hidePanel"):L("files.showPanel"),"data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:(e||rR)&&null===et?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,visibility:t?"hidden":"visible",pointerEvents:t?"none":"auto",background:ts?"var(--bg-selected)":"none",border:"none",borderLeft:"1px solid var(--border)",color:ts?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{t||(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color=ts?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]})})};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("style",{children:`
1178
+ .mobile-session-stats {
1179
+ container-type: inline-size;
1180
+ }
1181
+ @container (max-width: 158px) {
1182
+ .mobile-session-stat-io {
1183
+ display: none !important;
1184
+ }
1185
+ }
1186
+ @container (max-width: 88px) {
1187
+ .mobile-session-stat-cost {
1188
+ display: none !important;
1189
+ }
1190
+ }
1191
+ @media (max-width: 640px) {
1192
+ .sidebar-overlay-backdrop.sidebar-mobile-pending {
1193
+ opacity: 0 !important;
1194
+ pointer-events: none !important;
1195
+ }
1196
+ .sidebar-container.sidebar-mobile-pending.sidebar-open {
1197
+ transform: translateX(calc(-100% - env(safe-area-inset-left)));
1198
+ box-shadow: none;
1199
+ }
1200
+ }
1201
+ `}),(0,r.jsxs)("div",{style:{display:"flex",width:"100%",height:"var(--app-viewport-height, 100dvh)",paddingLeft:"env(safe-area-inset-left)",paddingRight:"env(safe-area-inset-right)",overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsx)("div",{className:`sidebar-overlay-backdrop${ty?"":" sidebar-mobile-pending"}`,onClick:()=>tr(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!tt,pointerEvents:tt?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:tE.panelRef,id:"session-sidebar",inert:tm,className:`sidebar-container${tt?" sidebar-open":" sidebar-closed"}${ty?"":" sidebar-mobile-pending"}${tE.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${tE.width}px`,background:"var(--bg-panel)",borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,paddingTop:"env(safe-area-inset-top)",paddingBottom:"env(safe-area-inset-bottom)",zIndex:200},children:rH}),tt&&(0,r.jsx)("div",{...tE.separatorProps,inert:tm,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${tE.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${L("layout.resizeSidebar")}: ${L("layout.resizeHint")}`}),(0,r.jsxs)("div",{inert:tm,style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:tL,style:{flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",position:"relative",borderBottom:"1px solid var(--border)",height:"calc(36px + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)"},children:[(0,r.jsx)("button",{onClick:nS,title:tt?L("sidebar.hide"):L("sidebar.show"),"aria-label":tt?L("sidebar.hide"):L("sidebar.show"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"none",border:"none",borderRight:"1px solid var(--border)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:tt?(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]}):(0,r.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),z&&(0,r.jsxs)("div",{ref:tP,"data-mobile-toolbar":"true",style:{position:"relative",display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:[P&&(0,r.jsxs)("button",{type:"button",onClick:nC,title:tb,"aria-label":tb,"aria-controls":"mobile-toolbar-actions","aria-expanded":tg,"data-mobile-toolbar-more":"true",style:{position:"relative",zIndex:tg?21:void 0,display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:tg?"var(--bg-selected)":"none",border:"none",borderRight:"1px solid var(--border)",color:tg?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},children:[tg?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"5",x2:"19",y2:"19"}),(0,r.jsx)("line",{x1:"19",y1:"5",x2:"5",y2:"19"})]}):(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.5"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.5"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.5"})]}),tv&&rU(tv,!0)]}),!P&&rK(!0),!P&&rZ(!0),rV(!0),rJ(!0),P&&tg&&(0,r.jsxs)("div",{id:"mobile-toolbar-actions",role:"toolbar","aria-label":L("chat.moreControls"),"data-mobile-toolbar-actions":"true",style:{position:"absolute",top:0,right:0,bottom:0,left:36,zIndex:20,display:"flex",alignItems:"stretch",overflowX:"auto",overflowY:"hidden",scrollbarWidth:"none",background:"color-mix(in srgb, var(--bg-panel) 94%, var(--bg))",boxShadow:"4px 0 18px rgba(0,0,0,0.12)",backdropFilter:"blur(10px)"},children:[rK(!0),rZ(!0)]})]}),!z&&(0,r.jsxs)(r.Fragment,{children:[r_(!1),rK(!1),rR&&null===et?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%",marginLeft:"auto",minWidth:0},children:[rZ(!1),rq(!1),rV(!1)]}):null]}),!z&&rJ(!1),z&&tK&&(0,r.jsx)(xs,{tree:tW,activeLeafId:tF,onLeafChange:tZ,locked:tB,inline:!0,compact:!0,containerRef:tL,open:"branches"===nm,onToggle:()=>nv("branches"),hasSession:rR,hideInlineButton:!0}),nm&&ng&&(0,r.jsxs)("div",{style:{position:"fixed",top:ng.top,left:ng.left,width:ng.width,maxHeight:`calc(100dvh - ${ng.top}px)`,overflowY:"auto",zIndex:500},children:["agents"===nm&&ea&&G&&(0,r.jsx)(xj,{rootSession:ea.root,subagents:ea.subagents,selectedSessionId:G.id,runningSessionIds:ed,onSelectSession:n6,openSubagentTabIds:rm,onToggleSubagentTab:(e,t,n)=>{rm.has(e)?rb(`agent:${e}`):(z&&nf(null),rh(e,t,n))},onNewSideChat:()=>rx(ea.root.id)}),"session"===nm&&(0,r.jsx)(xh,{systemPrompt:tJ,tools:tY,systemInfoLoading:tQ,onOpenSystemInfo:nj,translate:L,messageSummary:nd,contextUsage:no??t9?.contextUsage??null,initialTab:np,children:t9?(u=t9.totalActiveMs??0,x=[...t9.sessionName?[{label:L("session.name"),value:t9.sessionName,copyField:null}]:[],{label:L("session.file"),value:t9.sessionFile??L("session.inMemory"),copyField:"file"},{label:L("session.id"),value:t9.sessionId,copyField:"id"},...u>0?[{label:L("session.totalActive"),value:lV(u),copyField:null}]:[]],v=[...G?[{label:L("session.projectDir"),value:G.projectRoot??G.cwd,copyField:"projectDir"}]:[],...G?.branch?[{label:L("session.gitBranch"),value:G.branch,copyField:"gitBranch"}]:[],...G?.isWorktree?[{label:L("session.gitWorktree"),value:G.cwd,copyField:"gitWorktree"}]:[]],b=[[L("session.user"),t9.userMessages.toLocaleString(A)],[L("session.assistant"),t9.assistantMessages.toLocaleString(A)],[L("session.toolCalls"),t9.toolCalls.toLocaleString(A)],[L("session.toolResults"),t9.toolResults.toLocaleString(A)],[L("session.total"),t9.totalMessages.toLocaleString(A)]],y=[[L("session.input"),t9.tokens.input.toLocaleString(A)],[L("session.output"),t9.tokens.output.toLocaleString(A)],...t9.tokens.cacheRead>0?[[L("session.cacheRead"),t9.tokens.cacheRead.toLocaleString(A)]]:[],...t9.tokens.cacheWrite>0?[[L("session.cacheWrite"),t9.tokens.cacheWrite.toLocaleString(A)]]:[],[L("session.total"),t9.tokens.total.toLocaleString(A)]],j=no??t9.contextUsage,k=lq(t9.tokens),w=[...t9.cost>0?[[L("session.cost"),`$${t9.cost.toFixed(4)}`]]:[],...j?.contextWindow?[[L("session.context"),`${null!==j.percent?`${j.percent.toFixed(1)}%`:"?"} / ${lU(j.contextWindow)}`]]:[],...null!==k?[[L("session.cacheHitRate"),`${k.toFixed(1)}%`]]:[]],S=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"left",i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:i?"max-content max-content":"auto minmax(0, 1fr)",columnGap:i?14:12,rowGap:4,justifyContent:i?"start":void 0},children:t.map(t=>{let[s,o]=t;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:s}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:i?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:o})]},`${e}:${s}`)})})]})},C={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},N=(e,t)=>{let n=nt===e;return(0,r.jsx)("button",{type:"button",title:n?L("session.copied"):L(C[e]),onClick:()=>ni(e,t),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:n?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:4,cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=n?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:n?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})},E=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:L("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:x.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?N(e.copyField,e.value):null})]},`session-info:${e.label}`))}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:10},children:[G&&!G.transient&&(0,r.jsx)("button",{type:"button",onClick:()=>{nf(null),e5(!0)},style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 10px",borderRadius:5,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",fontSize:11,fontFamily:"var(--font-ui)",cursor:"pointer"},children:L("share.dialogTitle")}),G&&!G.transient&&(0,r.jsx)("button",{type:"button",onClick:()=>{nf(null),e9(!0)},style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 10px",borderRadius:5,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",fontSize:11,fontFamily:"var(--font-ui)",cursor:"pointer"},children:L("export.dialogTitle")}),(0,r.jsx)("button",{type:"button",onClick:()=>{nf(null),te(!0)},style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 10px",borderRadius:5,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",fontSize:11,fontFamily:"var(--font-ui)",cursor:"pointer"},children:L("import.dialogTitle")})]})]}),I=v.length>0?(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:L("session.projectSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:v.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?N(e.copyField,e.value):null})]},`project-info:${e.label}`))})]}):null,(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:z?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:z?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:z?16:20},children:[E,I]}),S(L("session.messages"),b),S(L("session.tokens"),[...y,...w],"right",!0)]})):(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:L("session.load")}),(0,r.jsx)("button",{type:"button",onClick:()=>{nf(null),te(!0)},style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 10px",borderRadius:5,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",fontSize:11,fontFamily:"var(--font-ui)",cursor:"pointer"},children:L("import.dialogTitle")})]})}),"debug"===nm&&(0,r.jsx)(x9,{fallback:L("debug.failed"),children:(0,r.jsx)(x7,{readerRef:t5,selectedSessionId:G?.id??null,sessions:el,onClose:ny})})]})]}),z&&r_(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative"},children:rR?(0,r.jsx)(aj,{session:G,searchTarget:eF?.sessionId===G?.id?eF:null,onSearchTargetHandled:eH,initialScrollPosition:G?eW.current.get(G.id)??null:null,onScrollPositionChange:eO,sessionRunning:!!(G&&ed.has(G.id)),newSessionCwd:rj,newSessionDraftKey:rk,newSessionContextBar:rT,trajectoryView:null!==et?(0,r.jsx)(aR,{sessionId:et,running:ed.has(et)},et):null,initialNewSessionChoices:null===G?eN:null,onNewSessionChoicesChange:eI,onAgentEnd:rn,onToolEnd:ro,onAttentionNeeded:rr,onSessionCreated:re,onSessionForked:rl,onSideSession:rg,modelsRefreshKey:eV,chatInputRef:tM,onBranchDataChange:tV,onSystemPromptChange:t4,onSystemToolsChange:t8,onSystemInfoLoaderChange:t3,onDebugSnapshotReaderChange:t6,onSessionStatsChange:ne,onSessionStatsPanelOpen:nk,onMessageContextSummaryChange:nu,onOpenSettings:nw,onContextUsageChange:na,onOpenFile:ru,onFilesUploaded:ri,onOpenSubagent:rh,quoteSelectionEnabled:_,soundEnabled:W,onSoundToggle:O,playDoneSound:F,unlockAudio:D,holdAudio:B},ez):"validating"===e$?(0,r.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:L("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:M.requestedCwd})]}):"error"===e$?(0,r.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"#dc2626"},children:L("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:M.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eM})]}):rL?nG?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:L("workspace.selectSession")}):(0,r.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"44",height:"44",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{opacity:.7,flexShrink:0},children:[(0,r.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,r.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:L("workspace.getStarted")}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),L("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),L("workspace.addModels")]})]})]}):null})]}),(0,r.jsx)("div",{"aria-hidden":"true",className:`right-panel-overlay-backdrop${ts?" is-open":""}`,onClick:()=>to(!1)}),ts&&(0,r.jsx)("div",{...tI.separatorProps,inert:tm,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${tI.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${L("layout.resizeFilePanel")}: ${L("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:tI.panelRef,id:"file-panel",className:`right-panel-container${ts?" right-panel-open":" right-panel-closed"}${tm?" right-panel-full-width":""}${tI.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${tI.width}px`,display:"flex",flexDirection:"column",borderLeft:"1px solid var(--border)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,height:"calc(36px + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{flex:1,overflow:"hidden"},children:(0,r.jsx)(dk,{tabs:nH,activeTabId:nT??"",onSelectTab:nM,onCloseTab:rb})}),(0,r.jsx)("button",{type:"button",className:"file-panel-expand-button",onClick:nE,"aria-controls":"file-panel","aria-pressed":tm,title:L(tm?"files.restorePanelWidth":"files.expandPanel"),"aria-label":L(tm?"files.restorePanelWidth":"files.expandPanel"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:tm?"M9 3v6H3m12-6v6h6M9 21v-6H3m12 6v-6h6M3 3l6 6m12-6-6 6M3 21l6-6m12 6-6-6":"M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5M3 3l6 6m12-6-6 6M3 21l6-6m12 6-6-6"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>to(!1),"aria-controls":"file-panel","aria-expanded":ts,title:L("files.hidePanel"),"aria-label":L("files.hidePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"var(--bg-selected)",border:"none",borderLeft:"1px solid var(--border)",color:"var(--text)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]})})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflow:"hidden",paddingBottom:"env(safe-area-inset-bottom)"},children:[rO?.filePath?(0,r.jsx)(dy,{filePath:rO.filePath,cwd:nG??void 0,sourceSessionId:rO.sourceSessionId,gitRefreshKey:e_,initialDisplayMode:rO.initialDisplayMode,initialPage:rO.page,initialState:rO.viewerState,watchEnabled:ts,onStateChange:e=>n_(nA,rO.id,rO.viewerRevision??0,e),onMentionLines:ts?nV:void 0,onAtMention:nK,onOpenFile:(e,t)=>rc(e,(0,tH.WP)(e),{sourceSessionId:rO.sourceSessionId,page:t})},`${nA}:${rO.id}:${rO.viewerRevision??0}`):nP.some(e=>e.id===nT)||rF?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:L("files.noneOpen")}),nP.map(e=>(0,r.jsx)("div",{hidden:e.id!==nT,style:{width:"100%",height:"100%"},children:(0,r.jsx)(bn,{tab:e,active:ts&&e.id===nT,onRestart:()=>nW(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n;return t="restart"===e.closing?bi(e.cwd):null,n=nP.filter(t=>t.id!==e.id),void(nW(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),nM(r=>r!==e.id?r:t?.id??n.at(-1)?.id??nI.at(-1)?.id??bh(nD)),!t&&!n.length&&!nI.length&&!nD.length&&to(!1))},onCloseError:()=>nW(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id)),rF&&(0,r.jsx)(vD,{sessionId:rF.sessionId,running:ed.has(rF.sessionId),initialPrompt:tR[rF.sessionId],onInitialPromptConsumed:()=>tA(e=>{if(!(rF.sessionId in e))return e;let t={...e};return delete t[rF.sessionId],t}),modelsRefreshKey:eV,quoteSelectionEnabled:_,onOpenFile:ru,onOpenSubagent:rh,onSessionForked:e=>{z&&to(!1),rl(e)},onOpenSettings:nw,onToolEnd:ro,onFilesUploaded:ri,soundEnabled:W,onSoundToggle:O,playDoneSound:F,unlockAudio:D,holdAudio:B},rF.sessionId)]})]})]}),eK&&(0,r.jsx)(g1,{cwd:rA,sessionId:G?.id??null,initialSection:eK,quoteSelectionEnabled:_,onQuoteSelectionChange:K,onClose:()=>{eq(null),eZ(e=>e+1)},onSessionReloaded:()=>eP(e=>e+1),projectTrust:eY,onOpenTrustDialog:rP,onProjectTrustChanged:rW}),eQ&&rA&&(0,r.jsx)(g4,{cwd:rA,busy:e1,error:e4,onCancel:()=>{e1||e0(!1)},onConfirm:()=>void rz(),onStatus:eX}),e3&&G&&!G.transient&&(0,r.jsx)(rf,{sessionId:G.id,leafId:tF,onClose:()=>e5(!1)}),e6&&G&&!G.transient&&(0,r.jsx)(tz,{sessionId:G.id,leafId:tF,onClose:()=>e9(!1)}),e7&&(0,r.jsx)(ns,{cwd:G?.cwd??em,onImported:e=>{te(!1),rl(e)},onClose:()=>te(!1)})]})}},7834:(e,t,n)=>{"use strict";function r(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);try{let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch{return Promise.reject()}}n.d(t,{D:()=>r})},8436:(e,t,n)=>{"use strict";n.d(t,{k:()=>o});var r=n(95155),i=n(12115),s=n(21278);function o(e){let{src:t,alt:n="",children:o,className:l,style:a}=e,{t:d}=(0,s.s)(),c=d("chat.previewImage"),u=n.trim()?`${c}: ${n}`:c,[p,h]=(0,i.useState)(!1),m=(0,i.useRef)(null),f=(0,i.useRef)(null),g=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!p)return;let e=f.current;if(!e)return;let t=m.current,n=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),g.current?.focus({preventScroll:!0}),()=>{document.body.style.overflow=n,e.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[p]);let x=()=>{f.current?.open&&f.current.close(),h(!1)};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:m,type:"button",className:l,style:{display:"block",padding:0,border:"none",background:"none",color:"inherit",cursor:"zoom-in",...a},onClick:()=>h(!0),"aria-label":u,"aria-haspopup":"dialog","aria-expanded":p,title:c,children:o}),p&&(0,r.jsxs)("dialog",{ref:f,className:"image-preview-dialog","aria-label":d("chat.previewImage"),onCancel:e=>{e.preventDefault(),e.stopPropagation(),x()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),x())},onClick:e=>{e.target===e.currentTarget&&x()},children:[(0,r.jsx)("img",{className:"image-preview-image",src:t,alt:n}),(0,r.jsx)("button",{ref:g,type:"button",className:"image-preview-close",onClick:x,"aria-label":d("chat.close"),title:d("chat.close"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]})}},14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>p,getPresetFromTools:()=>u,kU:()=>o,sn:()=>c,xG:()=>h});let r="configured",i=["configured","none","read-only","default","full"],s=[],o=["read","grep","find","ls"],l=["read","bash","edit","write"],a=["bash","read","edit","write","grep","find","ls"],d=new Set([...a,"powershell"]);function c(e){return"string"==typeof e&&i.includes(e)}function u(e){return p(e.filter(e=>e.active).map(e=>e.name))}function p(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>d.has(e)).sort().join(",");return t===[...o].sort().join(",")?"read-only":t===[...l].sort().join(",")?"default":t===[...a].sort().join(",")?"full":"default"}function h(e){if(e!==r)return"none"===e?[...s]:"read-only"===e?[...o]:"full"===e?[...a]:[...l]}},16015:(e,t,n)=>{"use strict";n.d(t,{_:()=>s,n:()=>o});let r=!1,i=null;function s(){return r}function o(){return i??=n.e(1326).then(n.bind(n,61326)).then(()=>{r=!0},e=>{throw i=null,e})}},19870:(e,t,n)=>{"use strict";function r(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function i(e){try{return decodeURIComponent(e)}catch{return e}}function s(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function o(e){let t=s(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,o=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){o.length>0&&".."!==o[o.length-1]?o.pop():i||n||r||o.push(e);continue}o.push(e)}let l=o.join("/");return n?l:r?`//${l}`:i?`/${l}`:l}function l(e,t){let n,r,l,a,d,c=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t;if(!e)return null;let u=e.split("#",1)[0].split("?",1)[0].trim();if(!u)return null;let p=null,h=null,m=i(u),f=m.startsWith("\\\\"),g=s(m),x=g.toLowerCase();if(x.startsWith("/api/")||x.startsWith("/_next/")||!f&&g.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(g)&&!x.startsWith("file:")&&!/^[a-zA-Z]:\//.test(g))return null;if(x.startsWith("file:")?h=(p=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=i(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(u))?"absolute":null:/^[a-zA-Z]:\//.test(g)||g.startsWith("/")?(p=g,h="absolute"):t&&!(g.startsWith("#")||g.startsWith("?"))&&(g.startsWith("./")||g.startsWith("../")||g.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(g))&&(p=`${s(t).replace(/\/+$/,"")}/${g}`,h="relative"),!p)return null;let v=o(p).replace(/:\d+(?::\d+)?$/,"");return"relative"===h&&c&&(n=o(v).replace(/\/+$/,""),r=o(c).replace(/\/+$/,""),a=(l=/^[a-zA-Z]:\//.test(n)||/^[a-zA-Z]:\//.test(r))?n.toLowerCase():n,!(a===(d=l?r.toLowerCase():r)||a.startsWith(`${d}/`)))?null:v}n.d(t,{Vc:()=>l,XJ:()=>d,XK:()=>c,pz:()=>r});let a=/^page=(\d+)$/i;function d(e){if(!e)return null;let t=e.indexOf("#");if(-1===t)return null;let n=e.slice(t+1).trim().match(a);if(!n)return null;let r=Number.parseInt(n[1],10);return Number.isInteger(r)&&r>0?r:null}function c(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,s=i(e),l=t?i(t).replace(/\/+$/,""):void 0,a=/^[a-zA-Z]:\//.test(s),d=s.startsWith("//");if(a||d)n=s;else if(s.startsWith("/")){let e=l?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??l?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!l)return null;n=`${l}/${s}`}return o(n)}},22408:(e,t,n)=>{"use strict";n.d(t,{NG:()=>E,nT:()=>S,t:()=>y,wL:()=>w,hB:()=>j,fP:()=>k,Rb:()=>b});var r=n(95155),i=n(12115),s=n(50640),o=n(55961),l=n(7644),a=n(96793),d=n(21278),c=n(99220),u=n(7834);let p=2e3,h=!1,m=[],f=!1;function g(){f=!1,m.pop()?.(),m.length>0&&x()}function x(){!f&&(f=!0,"function"==typeof window.requestIdleCallback?window.requestIdleCallback(g,{timeout:500}):setTimeout(g,50))}var v=n(16015);function b(e,t){let n=URL.createObjectURL(new Blob([e],{type:"image/svg+xml;charset=utf-8"})),r=document.createElement("a");r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}function y(e){let{code:t,isStreaming:s,defaultPreview:o=!1}=e,{isDark:l}=(0,a.D)(),{t:c}=(0,d.s)(),[u,p]=(0,i.useState)(o),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(!1),x=(0,i.useRef)(null),v=`${l?"dark":"light"}
1202
+ ${t}`,y=u&&!s;(0,i.useEffect)(()=>{if(!y)return;let e=!1;return m({key:v,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:l?"dark":"default"}),!await r.parse(t,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,s=await r.render(i,t);e||m({key:v,status:"ready",svg:s.svg})})().catch(()=>{e||m({key:v,status:"error"})}),()=>{e=!0}},[t,v,l,y]);let C=(0,i.useMemo)(()=>(0,r.jsx)(j,{isStreaming:s,previewVisible:y,onToggle:()=>p(e=>!e),title:y?c("i18n.showMermaidSource"):c("i18n.previewMermaid")}),[s,y,c]);if(!y)return(0,r.jsx)(E,{code:t,lang:"mermaid",headerAction:C,isStreaming:s});let N=h?.key===v&&"error"===h.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:c("i18n.invalidMermaid")}):h?.key!==v||"ready"!==h.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":c("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!f&&(0,r.jsx)("button",{ref:x,type:"button",className:"mermaid-block mermaid-preview-button",title:c("i18n.openMermaidViewer"),"aria-label":c("i18n.openMermaidViewer"),onClick:()=>g(!0),dangerouslySetInnerHTML:{__html:h.svg}}),f&&(0,r.jsx)(S,{title:c("i18n.mermaidDiagram"),label:c("i18n.mermaidViewer"),onClose:()=>g(!1),children:(0,r.jsx)("div",{dangerouslySetInnerHTML:{__html:h.svg}})})]});return(0,r.jsx)(w,{lang:"mermaid",actions:(0,r.jsxs)(r.Fragment,{children:[h?.key===v&&"ready"===h.status&&(0,r.jsx)(k,{onClick:()=>{let e=x.current?.querySelector("svg");e&&b(new XMLSerializer().serializeToString(e),"mermaid-diagram.svg")}}),C]}),children:N})}function j(e){let{isStreaming:t,previewVisible:n,onToggle:i,title:s}=e,{t:o}=(0,d.s)();return(0,r.jsx)("button",{type:"button",onClick:i,disabled:t,title:t?o("i18n.previewAfterStreaming"):s,className:["markdown-code-action",n?"is-active":""].filter(Boolean).join(" "),children:o(n?"i18n.source":"i18n.preview")})}function k(e){let{onClick:t}=e,{t:n}=(0,d.s)();return(0,r.jsx)("button",{type:"button",className:"markdown-code-action",title:`${n("i18n.downloadFile")} (SVG)`,"aria-label":`${n("i18n.downloadFile")} (SVG)`,onClick:t,children:"SVG"})}function w(e){let{lang:t,actions:n,children:i}=e;return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t}),(0,r.jsx)("div",{className:"markdown-code-actions",children:n})]}),i]})}function S(e){let{title:t,label:n,onClose:s,children:o}=e,{t:l}=(0,d.s)(),a=(0,i.useRef)(null),[c,u]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:a,className:"mermaid-zoom-dialog","aria-label":n,onCancel:e=>{e.preventDefault(),s()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),s())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:t}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>Math.max(.5,e-.25)),disabled:c<=.5,title:l("i18n.zoomOut"),"aria-label":l("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*c),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>Math.min(3,e+.25)),disabled:c>=3,title:l("i18n.zoomIn"),"aria-label":l("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>u(1),title:l("i18n.fitToWidth"),"aria-label":l("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:s,title:l("i18n.close"),"aria-label":l("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&s()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*c}%`},children:o})})]})})}let C={...l.xJ,'pre[class*="language-"]':{...l.xJ['pre[class*="language-"]']}};function N(e){let{rows:t,stylesheet:n,useInlineStyles:i}=e;return t.map((e,t)=>{let o=e.children??[],l=o[0]?.properties?.className.includes("react-syntax-highlighter-line-number")?o[0]:null,a={...e,properties:{...e.properties,className:[...e.properties?.className??[],"markdown-code-line-text"]},children:l?o.slice(1):o};return(0,r.jsxs)("span",{className:"markdown-code-line",children:[l&&(0,s.Ay)({node:l,stylesheet:n,useInlineStyles:i,key:"number"}),(0,s.Ay)({node:a,stylesheet:n,useInlineStyles:i,key:"text"})]},t)})}delete C['pre[class*="language-"]'].background;let E=(0,i.memo)(function(e){let{code:t,lang:n,headerAction:s,isStreaming:f}=e,{isDark:g}=(0,a.D)(),{t:b}=(0,d.s)(),[y,j]=(0,i.useState)(!1),k=(0,c.c)(),[w,S]=(0,i.useState)(()=>{var e;return!f&&(0,v._)()&&(e=t.length,h||(h=!0,setTimeout(()=>{p=2e3,h=!1},0)),!(e>p)&&(p-=e,!0))});return(0,i.useEffect)(()=>{if(!f&&!w&&k){var e;return e=()=>S(!0),m.push(e),x(),()=>{let t=m.indexOf(e);-1!==t&&m.splice(t,1)}}},[f,w,k]),(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:n||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[s,(0,r.jsx)("button",{onClick:()=>{(0,u.D)(t).then(()=>{j(!0),setTimeout(()=>j(!1),1500)})},className:"markdown-code-action",children:b(y?"i18n.copied":"i18n.copy")})]})]}),f?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,whiteSpace:"pre-wrap",overflowWrap:"anywhere",backgroundColor:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:t})}):(0,r.jsx)(o.A,{language:w&&n||"text",style:g?C:l.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",flexShrink:0},renderer:N,customStyle:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,fontWeight:"var(--font-mono-weight)",border:"none",borderRadius:0,backgroundColor:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)"}},children:t})]})})},28999:(e,t,n)=>{"use strict";function r(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function i(e){let t=r(e),n=t.split("/").filter(Boolean);return t.startsWith("//")&&n.length>0&&(n[0]=`//${n[0]}`),n.map(encodeURIComponent).join("/")}function s(e){let t=r(e).replace(/\/+$/,"");return t.split("/").pop()??t}function o(e){let t=r(e).replace(/\/+$/,""),n=t.lastIndexOf("/");return n<0?"":0===n?"/":2===n&&/^[a-zA-Z]:\//.test(t)?t.slice(0,3):t.slice(0,n)}function l(e,t){if(!t)return e;let n=r(e),i=r(t).replace(/\/$/,"");return n.startsWith(i+"/")?n.slice(i.length+1):e}function a(e,t){return`${r(e).replace(/\/$/,"")}/${t}`}n.d(t,{A0:()=>r,HG:()=>i,WP:()=>s,e_:()=>a,gX:()=>o,qP:()=>l})},35754:(e,t,n)=>{"use strict";n.d(t,{EC:()=>c,GO:()=>a,RW:()=>d,en:()=>i,jL:()=>r,lF:()=>p,t9:()=>u});let r=0xa00000,i=0xa00000,s={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},o={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},l={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function a(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function d(e){return null!==(s[a(e)]??null)}function c(e){return null!==(o[a(e)]??null)}function u(e){return null!==(l[a(e)]??null)}function p(e){let t;return null!==("pdf"===(t=a(e))||"docx"===t?t:null)}},42927:(e,t,n)=>{Promise.resolve().then(n.bind(n,7413)),Promise.resolve().then(n.bind(n,21278))},63384:(e,t,n)=>{"use strict";n.d(t,{J:()=>p,p:()=>h});var r=n(12115);let i={messages:[],entryIds:[],oldestEntryId:null,hasMore:!1};function s(e,t){let n=new Map;e.entryIds.forEach((t,r)=>n.set(t,e.messages[r]));let r=t.messages.map((e,r)=>n.get(t.entryIds[r])??e),i=t.hasMore&&t.entryIds.length?e.entryIds.indexOf(t.entryIds[0]):-1;return i<0?{...t,messages:r}:{messages:[...e.messages.slice(0,i),...r],entryIds:[...e.entryIds.slice(0,i),...t.entryIds],oldestEntryId:e.oldestEntryId,hasMore:e.hasMore}}let o=new Map,l=new Set;function a(e){let t=o.get(e);return void 0===t?null:Date.now()-t.fetchedAt>6e5?(o.delete(e),null):t}function d(e,t,n){for(o.delete(e),o.set(e,{transcript:function(e){let t=e.messages.length-6e3;if(t<=0)return e;for(;t<e.messages.length&&e.messages[t]?.role==="toolResult";)t+=1;return{messages:e.messages.slice(t),entryIds:e.entryIds.slice(t),oldestEntryId:e.entryIds[t]??null,hasMore:!0}}(t),fetchedAt:n});o.size>3;){let e=o.keys().next().value;if(void 0===e)break;o.delete(e)}}function c(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=new URLSearchParams({deferMedia:"1",tail:String(t)});return n.before&&r.set("before",n.before),fetch(`/api/sessions/${encodeURIComponent(e)}/context?${r}`,{signal:n.signal,cache:"no-store"})}async function u(e){let t=(await e.json()).context??{};return{messages:t.messages??[],entryIds:t.entryIds??[],oldestEntryId:t.oldestEntryId??null,hasMore:!!t.hasMore}}function p(e){let t=a(e);l.has(e)||null!==t&&Date.now()-t.fetchedAt<1e4||(l.add(e),c(e,1e3).then(async t=>{if(!t.ok)return;let n=await u(t),r=s(a(e)?.transcript??i,n);d(e,r,Date.now())}).catch(()=>{}).finally(()=>{l.delete(e)}))}function h(e,t){let[n]=(0,r.useState)(()=>a(e)),[l,p]=(0,r.useState)(n?.transcript??i),[h,m]=(0,r.useState)(n?"ready":"loading"),[f,g]=(0,r.useState)(null),x=(0,r.useRef)(l);x.current=l;let v=(0,r.useRef)(null),b=(0,r.useRef)(!1),y=(0,r.useRef)(null),j=(0,r.useRef)(!1),k=(0,r.useRef)(n?.fetchedAt??0);(0,r.useEffect)(()=>{let e=new AbortController;return v.current=e,()=>{e.abort()}},[e]);let w=(0,r.useCallback)(async t=>{if(b.current){y.current=Math.max(y.current??0,t);return}b.current=!0;let n=async(t,n)=>{try{var r;let i,l=200===t&&Date.now()-k.current>1e4?1e3:t,a=await c(e,l,{signal:n});if(404===a.status)return void m("notFound");if(!a.ok)throw Error(`HTTP ${a.status}`);let d=await u(a);if(n.aborted)return;p(e=>{let t=s(e,d);return e.entryIds.length===t.entryIds.length&&e.entryIds.at(-1)===t.entryIds.at(-1)&&e.oldestEntryId===t.oldestEntryId&&e.hasMore===t.hasMore?e:t}),m("ready"),g(null),k.current=Date.now(),r=k.current,i=o.get(e),void 0!==i&&(i.fetchedAt=r)}catch(e){if(n.aborted)return;g(e instanceof Error?e.message:String(e)),m(e=>"ready"===e?e:"error")}};try{let e=t;for(;null!==e;){let t=v.current?.signal;if(void 0===t||t.aborted)break;await n(e,t),e=y.current,y.current=null}}finally{b.current=!1}},[e]);(0,r.useEffect)(()=>{w(n?200:1e3)},[n,w]),(0,r.useEffect)(()=>{if(!t)return;let e=()=>{"visible"===document.visibilityState&&w(200)};e();let n=setInterval(e,2e3);return()=>{clearInterval(n)}},[t,w]);let S=(0,r.useRef)(!1);return(0,r.useEffect)(()=>{S.current&&!t&&w(200),S.current=t},[t,w]),(0,r.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&Date.now()-k.current>1e4&&w(200)};return document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}},[w]),(0,r.useEffect)(()=>{"ready"===h&&d(e,l,k.current)},[e,h,l]),{transcript:l,status:h,error:f,loadEarlier:(0,r.useCallback)(async()=>{let t=x.current.oldestEntryId,n=v.current?.signal;if(!t||j.current||void 0===n)return!1;j.current=!0;try{let r=await c(e,1e3,{before:t,signal:n});if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await u(r);if(x.current.oldestEntryId!==t)return!1;return p(e=>e.oldestEntryId!==t?e:{messages:[...i.messages,...e.messages],entryIds:[...i.entryIds,...e.entryIds],oldestEntryId:i.oldestEntryId,hasMore:i.hasMore}),!0}catch{return!1}finally{j.current=!1}},[e]),retry:(0,r.useCallback)(()=>{m("loading"),w(1e3)},[w])}}},68925:(e,t,n)=>{"use strict";n.d(t,{$7:()=>W,AA:()=>v,Ep:()=>k,Hm:()=>O,LA:()=>K,LO:()=>_,SG:()=>g,iA:()=>F,o9:()=>U,t9:()=>x,u_:()=>M,xq:()=>b});var r=n(32316),i=n(88374),s=n(5924),o=n(94764),l=n(63835),a=n(54152),d=n(31678),c=n(6796),u=n(98164);let p=["obsidian","logseq","notion","vscode","vscode-insiders","cursor","zed","jetbrains","zoommtg","zoomus","msteams","slack"],h=RegExp(`^(?:${p.join("|")}):`,"i"),m=o.j.clobberPrefix??"user-content-",f={...o.j,clobberPrefix:m,attributes:{...o.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...o.j.protocols,href:[...o.j.protocols?.href??[],"file",...p]},strip:[...o.j.strip||[],"iframe","object","style","form"]};function g(e){return h.test(e)?e:(0,r.Lv)(e)}function x(e){return/^file:/i.test(e)?e:g(e)}function v(e){return!!(e&&/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(e))}function b(e){if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("href");if(!t?.startsWith("#"))return;e.preventDefault();let n=t.slice(1);if(!n)return;try{n=decodeURIComponent(n)}catch{}let r=CSS.escape(n);e.currentTarget.closest(".markdown-body")?.querySelector(`[id="${r}"], a[name="${r}"]`)?.scrollIntoView({block:"start"})}function y(e,t,n,r,i){let s="",o=0;for(let l=e.indexOf(t);-1!==l;l=e.indexOf(t,l+1)){if(l>0&&n.includes(e[l-1]))continue;r.lastIndex=l;let t=r.exec(e);t&&(s+=e.slice(o,l)+i(t),l=(o=r.lastIndex)-1)}return s+e.slice(o)}let j=/`((?:[^`\n]|\\`)*?[^\\`\n])`(?!`)/y;function k(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,s=0,o=null,l=new Map;for(let e=0;e<n.length;e++){var a,d;let t=n[e];if(o){r.push(t),RegExp(`</${o}\\s*>`,"i").test(t)&&(o=null);continue}let c=t.match(/^ {0,3}(`{3,}|~{3,})/);if(c){let e=c[1][0],n=c[1].length;i?e===i.marker&&n>=i.size&&(i=null):i={marker:e,size:n},s=0,r.push(t);continue}if(i){r.push(t);continue}let u=t.match(/<(code|pre|script|style)\b/i);if(u){let e=u[1].toLowerCase(),n=t.slice((u.index??0)+u[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(o=e),s=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){s=0,r.push(t);continue}if(s||(t=y(t,"`","\\`",j,e=>{let[t,n]=e,r=n.replace(/\\`/g,"`");if(r===n)return t;let i="`".repeat(Math.max(...r.match(/`+/g)?.map(e=>e.length)??[0])+1);return`${i}${r}${i}`})),s||t.includes("`")){s=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,s),r.push(t);continue}let p=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(p){let e=p[2].trim();if(e){r.push(`${p[1]}$$`,`${p[1]}${e}`,`${p[1]}$$`);continue}}let h=t.match(/^([ ]{0,3})\[[ \t]*(.+?)[ \t]*\][ \t]*$/);if(h){let e=h[2].trim();if(a=e,/\\[A-Za-z]+/.test(a)&&!/\b(?:https?|file|mailto):|\b[A-Za-z]:\\|^\\\\/i.test(a)){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let m=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(m){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${m[1]}$$`,...n.slice(e+1,t).map(e=>S(e,m[1])),`${m[1]}$$`),e=t;continue}}let f=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(f){let e=f[2].trim();if(e){r.push(`${f[1]}$$`,`${f[1]}${e}`,`${f[1]}$$`);continue}}let g=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(g){let t=g[1],i=g[2].trimEnd();if(i&&!i.includes("$$")){let s=w(n,e+1,t,l);if(s){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<s.index;i++)r.push(S(n[i],t));s.content&&r.push(`${t}${s.content}`),r.push(`${t}$$`),e=s.index;continue}}}let x=t.match(/^([ \t]{0,3})\$\$\s*$/);if(x){let t=x[1],i=w(n,e+1,t,l);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let s=e+1;s<i.index;s++)r.push(S(n[s],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((d=t,/^\s{0,3}\[[^\]]+\]:/.test(d)||/]\s*\(/.test(d)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(d)||/\b(?:https?|file|mailto):/i.test(d)||/\b[A-Za-z]:\\/.test(d)?d:y(d,"\\(","\\",C,e=>{let[t,n]=e;return n.trim()?`$${n}$`:t})))}return r.join(t)}function w(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var s,o,l,a;let t=e[i];if(s=t,""===(o=n)?/^ {0,3}\$\$\s*$/.test(s):s.startsWith(o)&&/^\$\$\s*$/.test(s.slice(o.length)))return{index:i,content:"",glued:!1};if(l=t,/^ {0,3}(`{3,}|~{3,})/.test(l)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(l)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(l)||/^ {0,3}>/.test(l)||/<(code|pre|script|style)\b/i.test(l)||(a=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(a)))return r.set(n,i),null;let d=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==d)return{index:i,content:d,glued:!0}}return r.set(n,e.length),null}function S(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let C=/\\\(([^`\r\n$]*?[^`\r\n$\\])\\\)/y,N={singleTilde:!1},E=/[\u3001\u3002\u3008-\u3011\u3014-\u301B\uFF01\uFF08\uFF09\uFF0C\uFF1A\uFF1B\uFF1F\u2018\u2019\u201C\u201D\u2013\u2014\u2026\u00B7\uFF5E\u301C]/;function I(){return(e,t)=>{var n;let r;n="string"==typeof t.value?t.value:"",(r=e=>{let t=e.children;for(let e=0;e<t.length;e++){let i=t[e];"link"===i.type&&function(e,t,n,r){if(null!=n.title||1!==n.children.length)return;let i=n.children[0];if("text"!==i.type)return;let s=n.position?.start,o=n.position?.end;if(s?.offset==null||o?.offset==null||r.slice(s.offset,o.offset)!==i.value)return;let l=i.value,a=l.search(E);if(a<=0||!n.url.endsWith(l))return;let d=l.slice(0,a),c={line:s.line,column:s.column+a,offset:s.offset+a};n.url=n.url.slice(0,n.url.length-l.length)+d,i.value=d,n.position={start:s,end:c},e.splice(t+1,0,{type:"text",value:l.slice(a),position:{start:c,end:o}})}(t,e,i,n);let s=t[e];"children"in s&&Array.isArray(s.children)&&r(s)}})(e)}}let $=function(){u.A.call(this);let e=this.data(),t=e.micromarkExtensions?.at(-1),n=t?.text?.[36];for(let e of Array.isArray(n)?n:n?[n]:[]){if("mathText"!==e.name)continue;let t=e.tokenize;e.tokenize=function(e,n,r){let i=this.now();return t.call(this,e,e=>{let t=this.sliceSerialize({start:i,end:this.now()});if(t.startsWith("$")&&!t.startsWith("$$")){let n=t.slice(1,-1),i=/^\s*[+-]?(?:\d|\.\d)/.test(n),s=null!==e&&e>=48&&e<=57,o=/^\s/.test(n)!==/\s$/.test(n);if(i&&(s||o))return r(e)}return n(e)},r)}}};function T(){return e=>{let t=e=>{("link"===e.type||"definition"===e.type)&&/^\/?[A-Za-z]:\//.test(e.url)&&(e.url=`file:///${e.url.replace(/^\//,"")}`),"children"in e&&e.children.forEach(t)};t(e)}}let M=[[a.A,["yaml"]],[d.A,N],c.A,I,$,T],R=/[ \t]*(?:\r\n|\r|\n)[ \t]*/,A=new Set(["root","blockquote","listItem","footnoteDefinition"]);function L(){return{type:"lineBreak",data:{hName:"br"}}}function z(e){if(!e.children)return;let t=A.has(e.type);e.children=e.children.map(e=>{if("html"!==e.type)return z(e),e;let n={type:"text",value:e.value??""};return t?{type:"paragraph",children:[n]}:n})}function P(e){e.children&&(e.children=e.children.flatMap(e=>"break"===e.type?[L()]:"text"===e.type&&e.value?e.value.split(R).flatMap((e,t)=>[...t>0?[L()]:[],...e?[{type:"text",value:e}]:[]]):(P(e),[e])))}let W=[...M??[],function(){return e=>{z(e),P(e)}}],O=[...M??[],function(){return(e,t)=>{z(e),P(e);let n=String(t.value).split(/\r\n|\r|\n/);for(let t of e.children??[])"paragraph"===t.type&&function(e,t){if(!e.position)return;let n=e.position.start.line-1,r=()=>{let e=/^[ \t]*/.exec(t[n]??"")?.[0];return e?[{type:"text",value:e}]:[]},i=r(),s=e=>{e.children=e.children?.flatMap(e=>"lineBreak"===e.type?(n+=1,[e,...r()]):(e.children?s(e):e.position&&(n+=e.position.end.line-e.position.start.line),[e]))};s(e),e.children=[...i,...e.children??[]]}(t,n)}}],F=[[a.A,["yaml"]],[d.A,N],c.A,I,$,T];function D(){return e=>{let t=e=>{if(!e||"object"!=typeof e)return;let n=e.properties?.href;for(let r of("element"===e.type&&"string"==typeof n&&n.startsWith("#")&&n.length>1&&(e.properties.href=`#${m}${n.slice(1)}`),e.children??[]))t(r)};t(e)}}function B(e){return"text"===e.type?e.value:"element"===e.type?e.children.map(B).join(""):""}function H(){return e=>{let t=e=>{e.children=e.children.map(e=>{if("element"!==e.type)return e;let n="pre"===e.tagName&&1===e.children.length?e.children[0]:null,r=n?.type==="element"&&"code"===n.tagName?n.properties.className:null;return Array.isArray(r)&&r.includes("language-math")?{type:"element",tagName:"div",properties:{className:["markdown-math-display"],dataMathSource:B(e).replace(/\n$/,"")},children:[e]}:(t(e),e)})};t(e)}}let _=[s.A,[l.A,f],D,H,[i.A,{throwOnError:!1,strict:!1}]],U=[s.A,[l.A,f],function(){return e=>{let t=new Map,n=e=>e.children.forEach(e=>{if("element"===e.type){if(/^h[1-6]$/.test(e.tagName)){let n=B(e).toLowerCase().replace(/[^\p{L}\p{M}\p{N}_\- ]/gu,"").replace(/ /g,"-"),r=n;for(;t.has(r);)t.set(n,t.get(n)+1),r=`${n}-${t.get(n)}`;t.set(r,0),e.properties.dataHeadingAnchor=r}n(e)}});n(e)}},H,[i.A,{throwOnError:!1,strict:!1}]],K=[s.A,[l.A,f],D,[i.A,{throwOnError:!1,strict:!1}]]},68929:(e,t,n)=>{"use strict";n.d(t,{F$:()=>r,g4:()=>o,nk:()=>s});let r=[{id:"auto",label:"settings.themeSystem",scheme:null},{id:"light",label:"settings.themeLight",scheme:"light"},{id:"mist",label:"settings.themeMist",scheme:"light"},{id:"lilac",label:"settings.themeLilac",scheme:"light"},{id:"sand",label:"settings.themeSand",scheme:"light"},{id:"rose",label:"settings.themeRose",scheme:"light"},{id:"dark",label:"settings.themeDark",scheme:"dark"},{id:"pine",label:"settings.themePine",scheme:"dark"},{id:"dusk",label:"settings.themeDusk",scheme:"dark"},{id:"ember",label:"settings.themeEmber",scheme:"dark"},{id:"slate",label:"settings.themeSlate",scheme:"dark"},{id:"contrast-light",label:"settings.themeContrastLight",scheme:"light"},{id:"contrast-dark",label:"settings.themeContrastDark",scheme:"dark"},{id:"zenburn",label:"settings.themeZenburn",scheme:"dark"}];r.flatMap(e=>"light"===e.scheme?[e.id]:[]);let i=r.flatMap(e=>"dark"===e.scheme?[e.id]:[]);function s(e){return r.some(t=>t.id===e)}function o(e){return i.includes(e)}},88576:e=>{e.exports={preview:"ChatMinimap_preview__laAya",earlier:"ChatMinimap_earlier__IxOXN",turn:"ChatMinimap_turn__fZuce",number:"ChatMinimap_number__3C_cY",toolBadge:"ChatMinimap_toolBadge__fzFQn",content:"ChatMinimap_content__C7_ju",user:"ChatMinimap_user__WHJHv",userText:"ChatMinimap_userText__Nj9jo",assistant:"ChatMinimap_assistant__s6JLb",assistantJump:"ChatMinimap_assistantJump__3CM2M",outline:"ChatMinimap_outline__aleIF",heading:"ChatMinimap_heading__djZbv",paragraph:"ChatMinimap_paragraph__EqWlO",lock:"ChatMinimap_lock__9WDY5"}},96793:(e,t,n)=>{"use strict";n.d(t,{D:()=>b});var r=n(12115),i=n(68929);let s="pi-theme",o={preference:"auto",theme:"light"},l=new Set,a=null,d=!1;function c(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function u(e){return"auto"===e?c():e}function p(e){"u">typeof document&&(document.documentElement.dataset.theme=e,document.documentElement.classList.toggle("dark",(0,i.g4)(e)))}function h(){if(a)return a;let e=function(){try{let e=localStorage.getItem(s);if((0,i.nk)(e))return e}catch{}return"auto"}(),t=u(e);return p(t),a={preference:e,theme:t}}function m(e,t,n){if(p(t),n)try{localStorage.setItem(s,e)}catch{}a={preference:e,theme:t},l.forEach(e=>e())}function f(){let e=h();if("auto"!==e.preference)return;let t=c();t!==e.theme&&m("auto",t,!1)}function g(e){return l.add(e),h(),d||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",f),window.addEventListener("focus",f),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&f()}),d=!0),f(),()=>{l.delete(e)}}function x(){return h()}function v(){return o}function b(){let e=(0,r.useSyncExternalStore)(g,x,v),t=(0,r.useCallback)((e,t)=>{if(h().preference===e)return;let n=u(e),r=()=>{m(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let s=t?.x??window.innerWidth/2,o=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(o,window.innerHeight-o));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${o}px)`,`circle(${l}px at ${s}px ${o}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]);return{theme:e.theme,preference:e.preference,setThemePreference:t,isDark:(0,i.g4)(e.theme)}}},99220:(e,t,n)=>{"use strict";n.d(t,{c:()=>s});var r=n(12115),i=n(16015);function s(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0],[t,n]=(0,r.useState)(i._);return(0,r.useEffect)(()=>{if(t||!e)return;let r=!0;return(0,i.n)().then(()=>{r&&n(!0)},()=>{}),()=>{r=!1}},[e,t]),t}}},e=>{e.O(0,[349,7330,3888,5772,4908,1278,8441,3794,7358],()=>e(e.s=42927)),_N_E=e.O()}]);