cuelo 0.5.7 → 0.5.9

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 (333) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +4 -3
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +2 -2
  6. package/.next/required-server-files.json +2 -2
  7. package/.next/routes-manifest.json +9 -3
  8. package/.next/server/app/_global-error/page.js +3 -3
  9. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  10. package/.next/server/app/_global-error.html +1 -1
  11. package/.next/server/app/_global-error.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  16. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  17. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  18. package/.next/server/app/_not-found/page.js +2 -2
  19. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  20. package/.next/server/app/_not-found.html +1 -1
  21. package/.next/server/app/_not-found.rsc +3 -3
  22. package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  23. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  24. package/.next/server/app/_not-found.segments/_index.segment.rsc +3 -3
  25. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  26. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  27. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  28. package/.next/server/app/api/agent/[id]/account/route.js +1 -1
  29. package/.next/server/app/api/agent/[id]/bash-output/route.js +1 -1
  30. package/.next/server/app/api/agent/[id]/events/route.js +2 -2
  31. package/.next/server/app/api/agent/[id]/route.js +1 -1
  32. package/.next/server/app/api/agent/new/route.js +1 -1
  33. package/.next/server/app/api/agent/running/route.js +1 -1
  34. package/.next/server/app/api/attachments/route.js +5 -0
  35. package/.next/server/app/api/attachments/route_client-reference-manifest.js +1 -0
  36. package/.next/server/app/api/auth/all-providers/route.js +1 -1
  37. package/.next/server/app/api/auth/api-key/[provider]/route.js +1 -1
  38. package/.next/server/app/api/auth/login/[provider]/route.js +2 -2
  39. package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
  40. package/.next/server/app/api/auth/providers/route.js +1 -1
  41. package/.next/server/app/api/cwd/browse/route.js +1 -1
  42. package/.next/server/app/api/cwd/validate/route.js +1 -1
  43. package/.next/server/app/api/default-cwd/route.js +1 -1
  44. package/.next/server/app/api/display-settings/route.js +1 -1
  45. package/.next/server/app/api/document-text/route.js +2 -2
  46. package/.next/server/app/api/experiments/route.js +1 -1
  47. package/.next/server/app/api/file-index/route.js +1 -1
  48. package/.next/server/app/api/files/[...path]/route.js +1 -1
  49. package/.next/server/app/api/git/diff/route.js +2 -2
  50. package/.next/server/app/api/git/status/route.js +2 -2
  51. package/.next/server/app/api/gpt6/handles/route.js +1 -1
  52. package/.next/server/app/api/gpt6/mcp/route.js +1 -1
  53. package/.next/server/app/api/gpt6/reply/route.js +1 -1
  54. package/.next/server/app/api/gpt6/token/route.js +1 -1
  55. package/.next/server/app/api/gpt6/web6-session/route.js +1 -1
  56. package/.next/server/app/api/home/route.js +1 -1
  57. package/.next/server/app/api/live/call/[callId]/route.js +1 -1
  58. package/.next/server/app/api/live/events/route.js +2 -2
  59. package/.next/server/app/api/live/offer/route.js +1 -1
  60. package/.next/server/app/api/live/voices/route.js +1 -1
  61. package/.next/server/app/api/mcp/route.js +2 -2
  62. package/.next/server/app/api/model-roles/route.js +1 -1
  63. package/.next/server/app/api/models/route.js +1 -1
  64. package/.next/server/app/api/models-config/catalog/route.js +1 -1
  65. package/.next/server/app/api/models-config/discover/route.js +1 -1
  66. package/.next/server/app/api/models-config/route.js +2 -2
  67. package/.next/server/app/api/models-config/test/route.js +1 -1
  68. package/.next/server/app/api/plugins/route.js +1 -1
  69. package/.next/server/app/api/project-trust/route.js +1 -1
  70. package/.next/server/app/api/projects/route.js +2 -2
  71. package/.next/server/app/api/runs/[runId]/route.js +1 -1
  72. package/.next/server/app/api/runs/route.js +1 -1
  73. package/.next/server/app/api/sessions/[id]/auto-name/route.js +1 -1
  74. package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
  75. package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js +1 -1
  76. package/.next/server/app/api/sessions/[id]/export/route.js +1 -1
  77. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  78. package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
  79. package/.next/server/app/api/sessions/route.js +1 -1
  80. package/.next/server/app/api/settings/route.js +1 -1
  81. package/.next/server/app/api/sidecars/[service]/[...path]/route.js +1 -1
  82. package/.next/server/app/api/skills/check/route.js +1 -1
  83. package/.next/server/app/api/skills/install/route.js +2 -2
  84. package/.next/server/app/api/skills/route.js +2 -2
  85. package/.next/server/app/api/skills/search/route.js +1 -1
  86. package/.next/server/app/api/skills/update/route.js +1 -1
  87. package/.next/server/app/api/theme/route.js +1 -1
  88. package/.next/server/app/api/tool-image/route.js +1 -0
  89. package/.next/server/app/api/tool-image/route.js.nft.json +1 -0
  90. package/.next/server/app/api/tool-image/route_client-reference-manifest.js +1 -0
  91. package/.next/server/app/api/update-maintenance/route.js +127 -114
  92. package/.next/server/app/api/updates/route.js +1 -1
  93. package/.next/server/app/api/web-access/recovery/route.js +1 -1
  94. package/.next/server/app/api/web-access/route.js +1 -1
  95. package/.next/server/app/api/web6/consults/route.js +1 -1
  96. package/.next/server/app/api/worktrees/route.js +1 -1
  97. package/.next/server/app/favicon.ico/route.js +1 -1
  98. package/.next/server/app/index.html +1 -1
  99. package/.next/server/app/index.rsc +5 -5
  100. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  101. package/.next/server/app/index.segments/_full.segment.rsc +5 -5
  102. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  103. package/.next/server/app/index.segments/_index.segment.rsc +3 -3
  104. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  105. package/.next/server/app/manifest.webmanifest/route.js +2 -2
  106. package/.next/server/app/page.js +20 -14
  107. package/.next/server/app/page_client-reference-manifest.js +1 -1
  108. package/.next/server/app/recover/page.js +2 -2
  109. package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
  110. package/.next/server/app/recover.html +1 -1
  111. package/.next/server/app/recover.rsc +3 -3
  112. package/.next/server/app/recover.segments/_full.segment.rsc +3 -3
  113. package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
  114. package/.next/server/app/recover.segments/_index.segment.rsc +3 -3
  115. package/.next/server/app/recover.segments/_tree.segment.rsc +2 -2
  116. package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
  117. package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
  118. package/.next/server/app-paths-manifest.json +4 -3
  119. package/.next/server/chunks/3379.js +1 -1
  120. package/.next/server/chunks/5582.js +2 -2
  121. package/.next/server/functions-config-manifest.json +1 -0
  122. package/.next/server/middleware-build-manifest.js +1 -1
  123. package/.next/server/pages/404.html +1 -1
  124. package/.next/server/pages/500.html +1 -1
  125. package/.next/server/server-reference-manifest.json +1 -1
  126. package/.next/static/A4Y1uTUKhMRX6746EPf7m/_buildManifest.js +1 -0
  127. package/.next/static/chunks/app/_global-error/page-44cd4075b01d7a06.js +1 -0
  128. package/.next/static/chunks/app/api/agent/[id]/account/route-44cd4075b01d7a06.js +1 -0
  129. package/.next/static/chunks/app/api/agent/[id]/bash-output/route-44cd4075b01d7a06.js +1 -0
  130. package/.next/static/chunks/app/api/agent/[id]/events/route-44cd4075b01d7a06.js +1 -0
  131. package/.next/static/chunks/app/api/agent/[id]/route-44cd4075b01d7a06.js +1 -0
  132. package/.next/static/chunks/app/api/agent/new/route-44cd4075b01d7a06.js +1 -0
  133. package/.next/static/chunks/app/api/agent/running/route-44cd4075b01d7a06.js +1 -0
  134. package/.next/static/chunks/app/api/attachments/route-44cd4075b01d7a06.js +1 -0
  135. package/.next/static/chunks/app/api/auth/all-providers/route-44cd4075b01d7a06.js +1 -0
  136. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-44cd4075b01d7a06.js +1 -0
  137. package/.next/static/chunks/app/api/auth/login/[provider]/route-44cd4075b01d7a06.js +1 -0
  138. package/.next/static/chunks/app/api/auth/logout/[provider]/route-44cd4075b01d7a06.js +1 -0
  139. package/.next/static/chunks/app/api/auth/providers/route-44cd4075b01d7a06.js +1 -0
  140. package/.next/static/chunks/app/api/cwd/browse/route-44cd4075b01d7a06.js +1 -0
  141. package/.next/static/chunks/app/api/cwd/validate/route-44cd4075b01d7a06.js +1 -0
  142. package/.next/static/chunks/app/api/default-cwd/route-44cd4075b01d7a06.js +1 -0
  143. package/.next/static/chunks/app/api/display-settings/route-44cd4075b01d7a06.js +1 -0
  144. package/.next/static/chunks/app/api/document-text/route-44cd4075b01d7a06.js +1 -0
  145. package/.next/static/chunks/app/api/experiments/route-44cd4075b01d7a06.js +1 -0
  146. package/.next/static/chunks/app/api/file-index/route-44cd4075b01d7a06.js +1 -0
  147. package/.next/static/chunks/app/api/files/[...path]/route-44cd4075b01d7a06.js +1 -0
  148. package/.next/static/chunks/app/api/git/diff/route-44cd4075b01d7a06.js +1 -0
  149. package/.next/static/chunks/app/api/git/status/route-44cd4075b01d7a06.js +1 -0
  150. package/.next/static/chunks/app/api/gpt6/handles/route-44cd4075b01d7a06.js +1 -0
  151. package/.next/static/chunks/app/api/gpt6/mcp/route-44cd4075b01d7a06.js +1 -0
  152. package/.next/static/chunks/app/api/gpt6/reply/route-44cd4075b01d7a06.js +1 -0
  153. package/.next/static/chunks/app/api/gpt6/token/route-44cd4075b01d7a06.js +1 -0
  154. package/.next/static/chunks/app/api/gpt6/web6-session/route-44cd4075b01d7a06.js +1 -0
  155. package/.next/static/chunks/app/api/home/route-44cd4075b01d7a06.js +1 -0
  156. package/.next/static/chunks/app/api/live/call/[callId]/route-44cd4075b01d7a06.js +1 -0
  157. package/.next/static/chunks/app/api/live/events/route-44cd4075b01d7a06.js +1 -0
  158. package/.next/static/chunks/app/api/live/offer/route-44cd4075b01d7a06.js +1 -0
  159. package/.next/static/chunks/app/api/live/voices/route-44cd4075b01d7a06.js +1 -0
  160. package/.next/static/chunks/app/api/mcp/route-44cd4075b01d7a06.js +1 -0
  161. package/.next/static/chunks/app/api/model-roles/route-44cd4075b01d7a06.js +1 -0
  162. package/.next/static/chunks/app/api/models/route-44cd4075b01d7a06.js +1 -0
  163. package/.next/static/chunks/app/api/models-config/catalog/route-44cd4075b01d7a06.js +1 -0
  164. package/.next/static/chunks/app/api/models-config/discover/route-44cd4075b01d7a06.js +1 -0
  165. package/.next/static/chunks/app/api/models-config/route-44cd4075b01d7a06.js +1 -0
  166. package/.next/static/chunks/app/api/models-config/test/route-44cd4075b01d7a06.js +1 -0
  167. package/.next/static/chunks/app/api/plugins/route-44cd4075b01d7a06.js +1 -0
  168. package/.next/static/chunks/app/api/project-trust/route-44cd4075b01d7a06.js +1 -0
  169. package/.next/static/chunks/app/api/projects/route-44cd4075b01d7a06.js +1 -0
  170. package/.next/static/chunks/app/api/runs/[runId]/route-44cd4075b01d7a06.js +1 -0
  171. package/.next/static/chunks/app/api/runs/route-44cd4075b01d7a06.js +1 -0
  172. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-44cd4075b01d7a06.js +1 -0
  173. package/.next/static/chunks/app/api/sessions/[id]/context/route-44cd4075b01d7a06.js +1 -0
  174. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-44cd4075b01d7a06.js +1 -0
  175. package/.next/static/chunks/app/api/sessions/[id]/export/route-44cd4075b01d7a06.js +1 -0
  176. package/.next/static/chunks/app/api/sessions/[id]/route-44cd4075b01d7a06.js +1 -0
  177. package/.next/static/chunks/app/api/sessions/[id]/state/route-44cd4075b01d7a06.js +1 -0
  178. package/.next/static/chunks/app/api/sessions/route-44cd4075b01d7a06.js +1 -0
  179. package/.next/static/chunks/app/api/settings/route-44cd4075b01d7a06.js +1 -0
  180. package/.next/static/chunks/app/api/sidecars/[service]/[...path]/route-44cd4075b01d7a06.js +1 -0
  181. package/.next/static/chunks/app/api/skills/check/route-44cd4075b01d7a06.js +1 -0
  182. package/.next/static/chunks/app/api/skills/install/route-44cd4075b01d7a06.js +1 -0
  183. package/.next/static/chunks/app/api/skills/route-44cd4075b01d7a06.js +1 -0
  184. package/.next/static/chunks/app/api/skills/search/route-44cd4075b01d7a06.js +1 -0
  185. package/.next/static/chunks/app/api/skills/update/route-44cd4075b01d7a06.js +1 -0
  186. package/.next/static/chunks/app/api/theme/route-44cd4075b01d7a06.js +1 -0
  187. package/.next/static/chunks/app/api/tool-image/route-44cd4075b01d7a06.js +1 -0
  188. package/.next/static/chunks/app/api/update-maintenance/route-44cd4075b01d7a06.js +1 -0
  189. package/.next/static/chunks/app/api/updates/route-44cd4075b01d7a06.js +1 -0
  190. package/.next/static/chunks/app/api/web-access/recovery/route-44cd4075b01d7a06.js +1 -0
  191. package/.next/static/chunks/app/api/web-access/route-44cd4075b01d7a06.js +1 -0
  192. package/.next/static/chunks/app/api/web6/consults/route-44cd4075b01d7a06.js +1 -0
  193. package/.next/static/chunks/app/api/worktrees/route-44cd4075b01d7a06.js +1 -0
  194. package/.next/static/chunks/app/{layout-4bd9f2a2ab63537d.js → layout-40ba82e77e62ae9d.js} +1 -1
  195. package/.next/static/chunks/app/manifest.webmanifest/route-44cd4075b01d7a06.js +1 -0
  196. package/.next/static/chunks/app/page-282a18bb2d229455.js +22 -0
  197. package/.next/static/chunks/next/dist/client/components/builtin/app-error-44cd4075b01d7a06.js +1 -0
  198. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-44cd4075b01d7a06.js +1 -0
  199. package/.next/static/chunks/next/dist/client/components/builtin/not-found-44cd4075b01d7a06.js +1 -0
  200. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-44cd4075b01d7a06.js +1 -0
  201. package/.next/static/css/{fd16d1946bb04a1f.css → bbe00993de567f95.css} +1 -1
  202. package/.next/trace +104 -104
  203. package/.next/trace-build +1 -1
  204. package/.next/types/app/api/{thinking-translate → attachments}/route.ts +3 -3
  205. package/.next/types/app/api/tool-image/route.ts +351 -0
  206. package/.next/types/routes.d.ts +3 -2
  207. package/.next/types/validator.ts +12 -3
  208. package/README.md +4 -5
  209. package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
  210. package/Tools/OMP_Global_Config/agent/RULES.md +7 -4
  211. package/Tools/OMP_Global_Config/agent/agents/maker.md +2 -2
  212. package/Tools/OMP_Global_Config/agent/extensions/character-voice.ts +13 -1
  213. package/Tools/OMP_Global_Config/agent/extensions/image-question-router.ts +25 -126
  214. package/Tools/OMP_Global_Config/agent/extensions/skim.ts +227 -0
  215. package/Tools/OMP_Global_Config/agent/extensions/steering-reply-gate.ts +3 -6
  216. package/Tools/OMP_Global_Config/agent/extensions/turn-end-guard.ts +4 -4
  217. package/Tools/OMP_Global_Config/agent/prompt-copies/RULES.en.md +4 -3
  218. package/Tools/OMP_Global_Config/agent/rules/harness-policy.json +2 -15
  219. package/Tools/OMP_Global_Config/agent/rules/subagent.md +9 -6
  220. package/Tools/OMP_Global_Config/agent/sop/maker.md +1 -1
  221. package/next.config.ts +7 -0
  222. package/package.json +1 -1
  223. package/public/audio/completion/hikari/01.wav +0 -0
  224. package/public/audio/completion/hikari/02.wav +0 -0
  225. package/public/audio/completion/hikari/03.wav +0 -0
  226. package/public/audio/completion/hikari/04.wav +0 -0
  227. package/public/audio/completion/hikari/05.wav +0 -0
  228. package/public/audio/completion/hikari/06.wav +0 -0
  229. package/public/audio/completion/hikari/approval/01.wav +0 -0
  230. package/public/audio/completion/hikari/approval/02.wav +0 -0
  231. package/public/audio/completion/hikari/approval/03.wav +0 -0
  232. package/public/audio/completion/hikari/choice/01.wav +0 -0
  233. package/public/audio/completion/hikari/choice/02.wav +0 -0
  234. package/public/audio/completion/hikari/choice/03.wav +0 -0
  235. package/public/audio/completion/hikari/failed/01.wav +0 -0
  236. package/public/audio/completion/hikari/failed/02.wav +0 -0
  237. package/public/audio/completion/hikari/failed/03.wav +0 -0
  238. package/public/audio/completion/hikari/working/01.wav +0 -0
  239. package/public/audio/completion/hikari/working/02.wav +0 -0
  240. package/public/audio/completion/hikari/working/03.wav +0 -0
  241. package/public/audio/completion/voices.json +198 -0
  242. package/public/avatars/hikari.webp +0 -0
  243. package/public/stickers/hikari/approval/01.webp +0 -0
  244. package/public/stickers/hikari/approval/02.webp +0 -0
  245. package/public/stickers/hikari/approval/03.webp +0 -0
  246. package/public/stickers/hikari/choice/01.webp +0 -0
  247. package/public/stickers/hikari/choice/02.webp +0 -0
  248. package/public/stickers/hikari/choice/03.webp +0 -0
  249. package/public/stickers/hikari/done/01.webp +0 -0
  250. package/public/stickers/hikari/done/02.webp +0 -0
  251. package/public/stickers/hikari/done/03.webp +0 -0
  252. package/public/stickers/hikari/failed/01.webp +0 -0
  253. package/public/stickers/hikari/failed/02.webp +0 -0
  254. package/public/stickers/hikari/failed/03.webp +0 -0
  255. package/public/stickers/hikari/working/01.webp +0 -0
  256. package/.next/server/app/api/thinking-translate/route.js +0 -1
  257. package/.next/server/app/api/thinking-translate/route_client-reference-manifest.js +0 -1
  258. package/.next/static/VLaxuGka8zMlnDdnf5Sw0/_buildManifest.js +0 -1
  259. package/.next/static/chunks/app/_global-error/page-56af6776c3d7d9c8.js +0 -1
  260. package/.next/static/chunks/app/api/agent/[id]/account/route-56af6776c3d7d9c8.js +0 -1
  261. package/.next/static/chunks/app/api/agent/[id]/bash-output/route-56af6776c3d7d9c8.js +0 -1
  262. package/.next/static/chunks/app/api/agent/[id]/events/route-56af6776c3d7d9c8.js +0 -1
  263. package/.next/static/chunks/app/api/agent/[id]/route-56af6776c3d7d9c8.js +0 -1
  264. package/.next/static/chunks/app/api/agent/new/route-56af6776c3d7d9c8.js +0 -1
  265. package/.next/static/chunks/app/api/agent/running/route-56af6776c3d7d9c8.js +0 -1
  266. package/.next/static/chunks/app/api/auth/all-providers/route-56af6776c3d7d9c8.js +0 -1
  267. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-56af6776c3d7d9c8.js +0 -1
  268. package/.next/static/chunks/app/api/auth/login/[provider]/route-56af6776c3d7d9c8.js +0 -1
  269. package/.next/static/chunks/app/api/auth/logout/[provider]/route-56af6776c3d7d9c8.js +0 -1
  270. package/.next/static/chunks/app/api/auth/providers/route-56af6776c3d7d9c8.js +0 -1
  271. package/.next/static/chunks/app/api/cwd/browse/route-56af6776c3d7d9c8.js +0 -1
  272. package/.next/static/chunks/app/api/cwd/validate/route-56af6776c3d7d9c8.js +0 -1
  273. package/.next/static/chunks/app/api/default-cwd/route-56af6776c3d7d9c8.js +0 -1
  274. package/.next/static/chunks/app/api/display-settings/route-56af6776c3d7d9c8.js +0 -1
  275. package/.next/static/chunks/app/api/document-text/route-56af6776c3d7d9c8.js +0 -1
  276. package/.next/static/chunks/app/api/experiments/route-56af6776c3d7d9c8.js +0 -1
  277. package/.next/static/chunks/app/api/file-index/route-56af6776c3d7d9c8.js +0 -1
  278. package/.next/static/chunks/app/api/files/[...path]/route-56af6776c3d7d9c8.js +0 -1
  279. package/.next/static/chunks/app/api/git/diff/route-56af6776c3d7d9c8.js +0 -1
  280. package/.next/static/chunks/app/api/git/status/route-56af6776c3d7d9c8.js +0 -1
  281. package/.next/static/chunks/app/api/gpt6/handles/route-56af6776c3d7d9c8.js +0 -1
  282. package/.next/static/chunks/app/api/gpt6/mcp/route-56af6776c3d7d9c8.js +0 -1
  283. package/.next/static/chunks/app/api/gpt6/reply/route-56af6776c3d7d9c8.js +0 -1
  284. package/.next/static/chunks/app/api/gpt6/token/route-56af6776c3d7d9c8.js +0 -1
  285. package/.next/static/chunks/app/api/gpt6/web6-session/route-56af6776c3d7d9c8.js +0 -1
  286. package/.next/static/chunks/app/api/home/route-56af6776c3d7d9c8.js +0 -1
  287. package/.next/static/chunks/app/api/live/call/[callId]/route-56af6776c3d7d9c8.js +0 -1
  288. package/.next/static/chunks/app/api/live/events/route-56af6776c3d7d9c8.js +0 -1
  289. package/.next/static/chunks/app/api/live/offer/route-56af6776c3d7d9c8.js +0 -1
  290. package/.next/static/chunks/app/api/live/voices/route-56af6776c3d7d9c8.js +0 -1
  291. package/.next/static/chunks/app/api/mcp/route-56af6776c3d7d9c8.js +0 -1
  292. package/.next/static/chunks/app/api/model-roles/route-56af6776c3d7d9c8.js +0 -1
  293. package/.next/static/chunks/app/api/models/route-56af6776c3d7d9c8.js +0 -1
  294. package/.next/static/chunks/app/api/models-config/catalog/route-56af6776c3d7d9c8.js +0 -1
  295. package/.next/static/chunks/app/api/models-config/discover/route-56af6776c3d7d9c8.js +0 -1
  296. package/.next/static/chunks/app/api/models-config/route-56af6776c3d7d9c8.js +0 -1
  297. package/.next/static/chunks/app/api/models-config/test/route-56af6776c3d7d9c8.js +0 -1
  298. package/.next/static/chunks/app/api/plugins/route-56af6776c3d7d9c8.js +0 -1
  299. package/.next/static/chunks/app/api/project-trust/route-56af6776c3d7d9c8.js +0 -1
  300. package/.next/static/chunks/app/api/projects/route-56af6776c3d7d9c8.js +0 -1
  301. package/.next/static/chunks/app/api/runs/[runId]/route-56af6776c3d7d9c8.js +0 -1
  302. package/.next/static/chunks/app/api/runs/route-56af6776c3d7d9c8.js +0 -1
  303. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-56af6776c3d7d9c8.js +0 -1
  304. package/.next/static/chunks/app/api/sessions/[id]/context/route-56af6776c3d7d9c8.js +0 -1
  305. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-56af6776c3d7d9c8.js +0 -1
  306. package/.next/static/chunks/app/api/sessions/[id]/export/route-56af6776c3d7d9c8.js +0 -1
  307. package/.next/static/chunks/app/api/sessions/[id]/route-56af6776c3d7d9c8.js +0 -1
  308. package/.next/static/chunks/app/api/sessions/[id]/state/route-56af6776c3d7d9c8.js +0 -1
  309. package/.next/static/chunks/app/api/sessions/route-56af6776c3d7d9c8.js +0 -1
  310. package/.next/static/chunks/app/api/settings/route-56af6776c3d7d9c8.js +0 -1
  311. package/.next/static/chunks/app/api/sidecars/[service]/[...path]/route-56af6776c3d7d9c8.js +0 -1
  312. package/.next/static/chunks/app/api/skills/check/route-56af6776c3d7d9c8.js +0 -1
  313. package/.next/static/chunks/app/api/skills/install/route-56af6776c3d7d9c8.js +0 -1
  314. package/.next/static/chunks/app/api/skills/route-56af6776c3d7d9c8.js +0 -1
  315. package/.next/static/chunks/app/api/skills/search/route-56af6776c3d7d9c8.js +0 -1
  316. package/.next/static/chunks/app/api/skills/update/route-56af6776c3d7d9c8.js +0 -1
  317. package/.next/static/chunks/app/api/theme/route-56af6776c3d7d9c8.js +0 -1
  318. package/.next/static/chunks/app/api/thinking-translate/route-56af6776c3d7d9c8.js +0 -1
  319. package/.next/static/chunks/app/api/update-maintenance/route-56af6776c3d7d9c8.js +0 -1
  320. package/.next/static/chunks/app/api/updates/route-56af6776c3d7d9c8.js +0 -1
  321. package/.next/static/chunks/app/api/web-access/recovery/route-56af6776c3d7d9c8.js +0 -1
  322. package/.next/static/chunks/app/api/web-access/route-56af6776c3d7d9c8.js +0 -1
  323. package/.next/static/chunks/app/api/web6/consults/route-56af6776c3d7d9c8.js +0 -1
  324. package/.next/static/chunks/app/api/worktrees/route-56af6776c3d7d9c8.js +0 -1
  325. package/.next/static/chunks/app/manifest.webmanifest/route-56af6776c3d7d9c8.js +0 -1
  326. package/.next/static/chunks/app/page-bd3b1ea55910637f.js +0 -15
  327. package/.next/static/chunks/next/dist/client/components/builtin/app-error-56af6776c3d7d9c8.js +0 -1
  328. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-56af6776c3d7d9c8.js +0 -1
  329. package/.next/static/chunks/next/dist/client/components/builtin/not-found-56af6776c3d7d9c8.js +0 -1
  330. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-56af6776c3d7d9c8.js +0 -1
  331. package/Tools/OMP_Global_Config/agent/extensions/lib/visible-text.ts +0 -27
  332. /package/.next/server/app/api/{thinking-translate → attachments}/route.js.nft.json +0 -0
  333. /package/.next/static/{VLaxuGka8zMlnDdnf5Sw0 → A4Y1uTUKhMRX6746EPf7m}/_ssgManifest.js +0 -0
@@ -0,0 +1,22 @@
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>s,IN:()=>i,getPresetFromTools:()=>o,xG:()=>l});let r=[],i=["read","bash","edit","write"],s=["read","bash","edit","write","grep","glob"],a=Object.fromEntries(s.map(e=>[e,!0]));function o(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===a[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...s].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...r]:"full"===e?[...s]:[...i]}},64830:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>dU});var r=n(95155),i=n(12115),s=n(73321),a=n(16871),o=n(81886),l=n(68890),d=n(6057);let c=["chat","process","subagents","files","resource","sidechat","efficiency"],u=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let p=Object.freeze({navigator:791,deck:1176}),h=Object.freeze({activeView:"chat",transientLayer:null}),m=Object.fromEntries(c.map(e=>[e,!0]));function f(e){return"string"==typeof e&&!0===m[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":return{activeView:f(t.view),transientLayer:null};case"open-layer":return{activeView:f(e.activeView),transientLayer:t.layer};case"toggle-layer":return{activeView:f(e.activeView),transientLayer:e.transientLayer===t.layer?null:t.layer};case"close-layer":return{activeView:f(e.activeView),transientLayer:null}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,b=!1,y=-1/0;function w(e,t=Date.now()){b=e,e||(y=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"];function I(e){let t=e.trim().replace(/\\/g,"/");return"/"===(t=t.startsWith("//")?`//${t.slice(2).replace(/\/{2,}/g,"/")}`:t.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(t)||(t=t.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}function T(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=I(e),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{project:e,modified:n.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function N(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(I(e.key),e.order);let r=[...e],i=new Set(e.map(I));for(let e of t){let t=I(e.key);!t||i.has(t)||(r.push(e.path??e.key),i.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(I(e))})).sort((e,t)=>{let n=void 0!==e.order,r=void 0!==t.order;return n!==r?n?-1:1:n&&r&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let M=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function R(e){let t=e.match(M);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var E=n(96244);let $=`(max-width: ${p.navigator-1}px)`;function L(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let A=L("(max-width: 640px)"),P=L($);function z(){return!1}function W(){return(0,i.useSyncExternalStore)(A.subscribe,A.getSnapshot,z)}var F=n(47650);async function D(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}function _(){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 B(){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 O({onCancel:e,onSelect:t,busy:n=!1,error:s}){let{t:a}=(0,E.s)(),[o,l]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)([]),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(!0),j=(0,i.useCallback)(async e=>{k(!0),y(null);try{let t=await D(e),n=t.path??e??"/";c(n),p(t.parentPath??null),m(n),g(t.directories??[]),v(t.drives??null)}catch(e){y(e instanceof Error?e.message:String(e))}finally{k(!1)}},[]);(0,i.useEffect)(()=>{l(document.body),j()},[j]);let S=h.trim()!==d,C=!!d&&!S&&!n,I=!!u||/^[a-zA-Z]:[\\/]?$/.test(d);return o?(0,F.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},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:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},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:e,disabled:n,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:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=h.trim();t&&j(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 j(u??void 0),disabled:w||!I,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:I?"pointer":"default",opacity:I?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:h,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{m(e.target.value),y(null)},style:{minWidth:0,flex:1,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}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:w||!h.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||!h.trim()?"default":"pointer",opacity:w||!h.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!==x?(0,r.jsx)(r.Fragment,{children:x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void j(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)(B,{}),(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")})}):f.length>0?f.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void j(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)(_,{}),(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")}),(b||s)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:b??s})]}),(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:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:a("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(d),disabled:!C,title:a(S?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:C?1:.6,cursor:C?"pointer":"default"},children:a(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}function H({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:s}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:'"Plus Jakarta Sans", Geist, ui-sans-serif, system-ui, sans-serif',fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...s},children:e})]})}let U="omp-web:unread-session-ids",q="omp-web:pinned-session-ids",V="omp-web:removed-projects";function K(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function J({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function G({open:e,children:t,style:n}){let[s,a]=(0,i.useState)(e),[o,l]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(a(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),n=setTimeout(()=>a(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),s)?(0,r.jsx)("div",{style:{...n,opacity:+!!o,transform:o?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let Y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function Z(){let[e,t]=(0,i.useState)(!1),[n,s]=(0,i.useState)(!1),a=(0,i.useRef)(null),o=function(e,t){let[n,r]=(0,i.useState)(e),s=(0,i.useRef)(null),a=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);a.current=0;let n=4*e.length,i=()=>{a.current+=1;let t=Math.floor(a.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:Y[Math.floor(Math.random()*Y.length)]).join("")),a.current<n?s.current=requestAnimationFrame(i):r(e)};return s.current=requestAnimationFrame(i),()=>{s.current&&cancelAnimationFrame(s.current)}},[e,t]),n}(e?"0.5.9/18.3.5":"CUELO",n),l=(0,i.useCallback)(e=>{t(e),s(!0),setTimeout(()=>s(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{a.current&&clearTimeout(a.current);let t=!e;l(t),t&&(a.current=setTimeout(()=>l(!1),3e3))},[e,l]);return(0,i.useEffect)(()=>()=>{a.current&&clearTimeout(a.current)},[]),(0,r.jsx)("button",{className:"navigator-brand",onClick:d,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",minWidth:"6ch"},children:(0,r.jsx)(H,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",letterSpacing:"-0.01em"}:void 0})})}async function X(e){let t=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e})});if(!t.ok)throw Error(`HTTP ${t.status}`)}function Q({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:s,initialSessionId:a,skipInitialProjectSelection:o,onInitialRestoreDone:l,refreshKey:d,onSessionDeleted:c,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h}){var m;let f,{t:g,locale:x}=(0,E.s)(),v=W(),[b,y]=(0,i.useState)([]),w=t&&!b.some(e=>e.id===t.id)?[t,...b]:b,[M,R]=(0,i.useState)(!0),[$,L]=(0,i.useState)(null),[A,P]=(0,i.useState)(null),[z,F]=(0,i.useState)(""),[D,_]=(0,i.useState)(""),[B,H]=(0,i.useState)("projects"),[Y,et]=(0,i.useState)(()=>new Set),[es,ea]=(0,i.useState)(()=>new Set),[el,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)({version:1,projects:[]}),[em,ef]=(0,i.useState)(!1),[eg,ex]=(0,i.useState)(!1),[ev,eb]=(0,i.useState)(!1),[ey,ew]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(""),[eS,eC]=(0,i.useState)(!1),[eI,eT]=(0,i.useState)(null),[eN,eM]=(0,i.useState)(""),[eR,eE]=(0,i.useState)(!1),[e$,eL]=(0,i.useState)(null),[eA,eP]=(0,i.useState)(!1),[ez,eW]=(0,i.useState)(null),[eF,eD]=(0,i.useState)(!1),[e_,eB]=(0,i.useState)(!1),[eO,eH]=(0,i.useState)(""),[eU,eq]=(0,i.useState)(null),[eV,eK]=(0,i.useState)(!1),[eJ,eG]=(0,i.useState)(null),eY=(0,i.useRef)(null),eZ=(0,i.useRef)(null),eX=(0,i.useRef)(null),eQ=(0,i.useRef)(!1),e0=(0,i.useRef)(!1),[e1,e2]=(0,i.useState)(!1),[e8,e4]=(0,i.useState)(()=>new Set),[e5,e6]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(U);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),[e3,e7]=(0,i.useState)(()=>new Set),e9=(0,i.useRef)(new Set),te=(0,i.useRef)(!1),tt=(0,i.useRef)(null);(0,i.useEffect)(()=>{e7(function(){try{let e=window.localStorage.getItem(q);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]);let tn=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);eh(await e.json())}catch{eh({version:1,projects:[]})}finally{ef(!0)}},[]);(0,i.useEffect)(()=>{tn()},[tn,d]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(V)}catch{return}if(!e)return;let t=[];try{let n=JSON.parse(e);Array.isArray(n)&&(t=n.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let n=t.slice(e,e+500);await X(n.map(e=>({key:I(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(V)}catch{}await tn()})()},[tn]);let tr=(0,i.useCallback)(async e=>{if(e0.current)throw Error("Project update in progress");e0.current=!0,eC(!0);try{await X(e),await tn()}finally{e0.current=!1,eC(!1)}},[tn]);(0,i.useEffect)(()=>{ey&&eX.current?.select()},[ey]);let ti=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&R(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();y(r.sessions),te.current||e4(new Set(r.runningSessionIds??[])),L(null),e||(e2(!0),tt.current&&clearTimeout(tt.current),tt.current=setTimeout(()=>e2(!1),2e3))}catch(e){L(String(e))}finally{e&&R(!1)}},[]),ts=(0,i.useCallback)(e=>{e6(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),e7(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),c?.(e),ti()},[ti,c]),[ta,to]=(0,i.useState)(null),[tl,td]=(0,i.useState)(!1),[tc,tu]=(0,i.useState)(null),tp=(0,i.useCallback)(()=>{tl||(to(null),tu(null))},[tl]),th=(0,i.useCallback)(async e=>{td(!0),tu(null);let t=[],n=[],r=[];for(let i of e)if(!i.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(i.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){n.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{r.push(i.name?.trim()||i.id.slice(0,8))}if(n.length>0&&(te.current=!0,e4(e=>{if(n.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of n)t.add(e);return t})),t.length>0){let e=new Set(t),n=n=>t.some(e=>n.has(e))?new Set([...n].filter(t=>!e.has(t))):n;for(let e of(e6(n),e7(n),t))c?.(e)}(await ti(),td(!1),r.length>0)?tu(g("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||to(null)},[ti,c,g]),[tm,tf]=(0,i.useState)(0),tg=(0,i.useCallback)(()=>{tf(e=>e+1),ti()},[ti]),tx=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tx.current;tx.current=!0,ti(e,!e)},[ti,d]),(0,i.useEffect)(()=>{try{H(function(e,t){return"gpt6"===e?"projects":"string"==typeof e&&k.includes(e)?e:"1"===t?"priority":"projects"}(window.localStorage.getItem(j),window.localStorage.getItem(S)))}catch{}},[]);let tv=(0,i.useCallback)(e=>{H(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==B)return;let e=()=>{"visible"===document.visibilityState&&ti(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[ti,B]),(0,i.useEffect)(()=>{try{0===e5.size?window.localStorage.removeItem(U):window.localStorage.setItem(U,JSON.stringify([...e5]))}catch{}},[e5]),(0,i.useEffect)(()=>{try{0===e3.size?window.localStorage.removeItem(q):window.localStorage.setItem(q,JSON.stringify([...e3]))}catch{}},[e3]);let tb=(0,i.useCallback)(e=>{e7(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(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;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(!t.ok)return;let r=await t.json();if(e||n!==s)return;te.current=!0,e4(new Set(r.runningSessionIds??[]))}catch{}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},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)}},[]),(0,i.useEffect)(()=>{let t=e9.current,n=[...t].filter(t=>!e8.has(t)&&t!==e),r=[...e8].filter(e=>!t.has(e));(n.length>0||r.length>0)&&e6(e=>{let t=new Set(e);return e8.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!b.some(t=>t.id===e));(n.length>0||i)&&ti(!1,!0),n.length>0&&h?.(),e9.current=e8},[e8,e,b,ti,h]),(0,i.useEffect)(()=>{e&&e6(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&F(e.home)}).catch(()=>{})},[]);let ty=(0,i.useRef)(!1),tw=(0,i.useCallback)(e=>{if(!e)return null;if(ez&&ez.forCwd===e||ez?.worktrees.some(t=>t.path===e))return ez.projectRoot;let t=w.find(t=>t.cwd===e);return t?.projectRoot??e},[ez,w]),tk=(0,i.useRef)(null);(0,i.useEffect)(()=>{tk.current!==A&&(tk.current=A,p?.(A,tw(A)))},[A,p,tw]);let tj=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tj.current&&(tj.current=u,P(u))},[u]);let[tS,tC]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!A)return void eW(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(A)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eW(null);eW({forCwd:A,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eW(null)}),()=>{e=!0}},[A,tS,d]),(0,i.useEffect)(()=>{if(0!==b.length&&!o&&null===A){if(a&&!ty.current){ty.current=!0;let e=b.find(e=>e.id===a);if(e){P(e.cwd),n(e,!0);return}l?.()}if(!em)return;let e=new Map(ep.projects.map(e=>[e.key,e])),t=N(b.length>0?T(b):[],ep.projects).filter(t=>!e.get(I(t))?.hidden);t.length>0&&P(t[0])}},[b,A,a,o,n,l,ep,em]);let tI=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eA){eP(!0),eL(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),n=await e.json().catch(()=>({}));if(!e.ok||n.error)return void eL(n.error??g("workspace.unable"));let r=n.cwd??t,i=I(r),s=ep.projects.find(e=>e.key===i);if(s?.hidden===!0)try{await tr([{key:i,path:r,hidden:!1}])}catch{}P(r),eE(!1)}catch{eL(g("workspace.unable"))}finally{eP(!1)}}},[tr,eA,ep.projects,g]),tT=(0,i.useCallback)(()=>{eE(!0),eL(null)},[]),tN=(0,i.useCallback)(async()=>{let e=eO.trim();if(e&&!eV&&ez){eK(!0),eq(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:ez.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eq(n.error??`HTTP ${t.status}`);eB(!1),eH(""),eD(!1),eW(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),P(n.path),tC(e=>e+1)}catch(e){eq(e instanceof Error?e.message:String(e))}finally{eK(!1)}}},[eO,eV,ez]),tM=(0,i.useCallback)(async(e,t)=>{if(ez&&!eV){eK(!0),eq(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:ez.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void eG(e);eq(r.error??`HTTP ${n.status}`);return}eG(null),A===e&&P(ez.projectRoot),tC(e=>e+1)}catch(e){eq(e instanceof Error?e.message:String(e))}finally{eK(!1)}}},[ez,eV,A]);(0,i.useEffect)(()=>{let e=e=>{eY.current&&!eY.current.contains(e.target)&&(eu(null),eD(!1),eB(!1),eH(""),eq(null),eG(null),eM(""),ed(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tR=(0,i.useCallback)(e=>{e.cwd&&P(e.cwd),n(e)},[n]),tE=(0,i.useCallback)((e=A)=>{if(!e)return;let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;P(e),s?.(t,e)},[A,s]),t$=(0,i.useCallback)(e=>{ea(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),tL=tw(A),tA=null===tL?null:I(tL),tP=(0,i.useMemo)(()=>new Map(ep.projects.map(e=>[e.key,e])),[ep.projects]),tz=T(w);if(null!==tL){let e=I(tL);tz.some(t=>I(t)===e)||tz.unshift(tL)}let tW=N(tz,ep.projects),tF=tW.filter(e=>eg||!tP.get(I(e))?.hidden),tD=tW.some(e=>tP.get(I(e))?.hidden),t_=()=>{eu(null),eD(!1),eB(!1),eH(""),eq(null),eG(null),eM("")},tB=async(e,t)=>{t_();try{await tr([{key:I(e),path:e,hidden:t}]),t&&tA&&tA===I(e)&&P(null),t||tW.some(t=>I(t)!==I(e)&&tP.get(I(t))?.hidden)||ex(!1)}catch{}},tO=async e=>{if(eQ.current){eQ.current=!1,ew(null);return}let t=ek.trim();if(t===(tP.get(I(e))?.alias??""))return void ew(null);eT(null);try{await tr([{key:I(e),path:e,alias:t||null}]),ew(null)}catch{eT(g("sidebar.projectUpdateFailed"))}},tH=async(e,t)=>{if(D)return;let n=tF.indexOf(e),r=n+t;if(n<0||r<0||r>=tF.length)return;let i=new Set(tF),s=tW.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),a=[...tW],o=s[n],l=s[r];[a[o],a[l]]=[a[l],a[o]],t_();try{await tr(a.map((e,t)=>({key:I(e),path:e,order:t})))}catch{}},tU=new Map;for(let e of w){let t=e.projectRoot??e.cwd;if(!t)continue;let n=I(t),r=tU.get(n);r?r.push(e):tU.set(n,[e])}let tq=(0,i.useMemo)(()=>{let e=new Map;for(let t of w){let n=t.projectRoot??t.cwd;if(!n)continue;let r=I(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),e8.has(t.id)&&i.running++,e5.has(t.id)&&i.unread++}return e},[w,e8,e5]),tV=D.trim().toLowerCase(),tK=D.length>0,tJ=tF.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=I(e),r=tP.get(n),i=r?.alias??t,s=(tU.get(n)??[]).slice().sort((e,t)=>{let n=Number(e3.has(t.id))-Number(e3.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!tV)return[{project:e,key:n,name:i,sessions:s,hidden:r?.hidden===!0}];let a=i.toLowerCase().includes(tV)||t.toLowerCase().includes(tV),o=s.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(tV));return a||0!==o.length?[{project:e,key:n,name:i,sessions:a?s:o,hidden:r?.hidden===!0}]:[]}),tG=[],tY=[];for(let e of tJ){let t=e.key===tA||(tq.get(e.key)?.running??0)>0;(function(e){let t=e.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(t)||"/"===t||/(^|\/)appdata\/local\/temp(\/|$)/.test(t)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(t)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(t)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(t))||t.split("/").some(e=>C.some(t=>e.startsWith(t)))})(e.project)&&!t?tY.push(e):tG.push(e)}let tZ={running:0,unread:0};for(let e of tY){let t=tq.get(e.key);t&&(tZ.running+=t.running,tZ.unread+=t.unread)}let tX=tK||ev,tQ=[...tG.map(e=>({kind:"project",group:e})),...tY.length>0?[{kind:"temporary"}]:[],...tX?tY.map(e=>({kind:"project",group:e})):[]],t0=function(e){let t=new Map;for(let n of e){let e=n.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(tQ.flatMap(e=>"project"===e.kind?[e.group.name]:[])),t1=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",s=new Set,a="Pinned"){let o=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),l=o.filter(e=>s.has(e.id)),d=[],c=new Map,u=0;for(let e of o){if(s.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(u>=10)continue;u+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=c.get(r);i?i.push(e):c.set(r,[e])}let p=[];for(let e of(l.length>0&&p.push({key:"pinned",label:a,running:!1,sessions:l}),d.length>0&&p.push({key:"priority",label:i,running:!0,sessions:d}),[...c.keys()].sort().reverse()))p.push({key:e,label:function(e,t,n){let[r,i,s]=e.split("-").map(Number),a=new Date(r,i-1,s),o=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(a.getFullYear(),a.getMonth(),a.getDate()))/864e5);return 0===o||1===o?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-o,"day"):o>=0&&o<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(a):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(a)}(e,n,r),running:!1,sessions:c.get(e)??[]});return p})(w,e8,new Date,x,g("navigator.priority"),e3,g("sidebar.pinned")),[x,e3,e8,w,g]),t2=!!(ez?.isGit&&ez.isTopLevel&&A&&tL===ez.projectRoot),t8=ez?.worktrees.find(e=>e.path===A)??ez?.worktrees.find(e=>e.isMain),t4=(ez?.worktrees.length??0)>=8,t5=t4&&eN.trim()?(ez?.worktrees??[]).filter(e=>(e.branch??K(e.path,z)).toLowerCase().includes(eN.trim().toLowerCase())):ez?.worktrees??[],t6=(()=>{if(!ta)return[];let e="project"===ta.kind?tU.get(I(ta.project))??[]:t1.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),t3=t6.filter(e=>!e8.has(e.id)),t7=e=>{let t=new Set;for(let n of e)n.transient||e8.has(n.id)||t.has(n.id)||t.add(n.id);return t.size};return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eR&&(0,r.jsx)(O,{busy:eA,error:e$,onCancel:()=>{eE(!1),eL(null)},onSelect:e=>void tI(e)}),ta&&(0,r.jsx)(ee,{scope:ta,eligible:t3.length,runningExcluded:t6.length-t3.length,busy:tl,error:tc,onCancel:tp,onConfirm:()=>void th(t3)}),(0,r.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(Z,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>tE(),disabled:!A,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:A?"var(--text-muted)":"var(--text-dim)",cursor:A?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:7,fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:A?g("sidebar.newSessionTitle",{path:A}):g("sidebar.selectProject"),"aria-label":A?g("sidebar.newSessionTitle",{path:A}):g("sidebar.selectProject"),onMouseEnter:e=>{A&&(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=A?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,r.jsx)("button",{className:`navigator-icon-action${e1?" is-success":""}`,onClick:()=>ti(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:e1?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${e1?"rgba(74,222,128,0.4)":"var(--border)"}`,color:e1?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:7,padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:e=>{e1||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e1||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:g("sidebar.refresh"),children:e1?(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",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:"15",height:"15",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 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"})]})})]})]})}),(0,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.jsx)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":g("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:k.map(e=>{let t="projects"===e?g("sidebar.projects"):g("navigator.priority"),n=B===e;return(0,r.jsx)("button",{type:"button","aria-label":g("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>tv(e),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)})}),"projects"===B&&(0,r.jsx)("button",{type:"button",onClick:()=>ex(e=>!e),disabled:!tD,title:g("sidebar.projectShowHidden"),"aria-label":g("sidebar.projectShowHidden"),"aria-pressed":eg,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:eg?"var(--bg-selected)":"transparent",color:eg?"var(--accent)":"var(--text-dim)",cursor:tD?"pointer":"default",opacity:tD?1:.45,flexShrink:0},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:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eg&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),"projects"===B&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tT,title:g("sidebar.addProject"),"aria-label":g("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",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="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("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:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,r.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),"projects"===B&&(0,r.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,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-3.5-3.5"})]}),(0,r.jsx)("input",{className:"navigator-search-input",type:"search",value:D,onChange:e=>_(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),_(""),e.currentTarget.blur())},placeholder:g("sidebar.searchProjectsAndSessions"),"aria-label":g("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:"1px solid var(--border)",borderRadius:7,outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),"projects"===B&&(0,r.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(M||!em)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:g("sidebar.loading")}),$&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:$}),eI&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eI}),!M&&em&&!$&&0===tJ.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:tV?g("sidebar.noMatchingProjects"):g("sidebar.noSessions")}),!M&&em&&!$&&tQ.map(t=>{let n,i,s;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":tX,title:g("sidebar.temporaryProjects"),onClick:()=>eb(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},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:{transform:tX?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10,flexShrink:0},children:tY.length}),eo(tZ,g)]})},"navigator-temporary-projects");let{project:a,key:o,name:l,sessions:d,hidden:c}=t.group,u=o===tA,p=t0.has(l.toLowerCase())&&K((i=Math.max((n=a.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),z)||null,h=!es.has(a)&&!tV,m=Y.has(a),f=ey===a,x=tF.indexOf(a),b=eS||tK||x<=0,y=eS||tK||x>=tF.length-1,w=function(e){let t=new Map;for(let n of e)t.set(n.id,{session:n,children:[]});let n=new Map;for(let t of e)t.parentSessionId&&n.set(t.id,t.parentSessionId);let r=[];for(let e of t.values()){let i=function(e){let r=n.get(e),i=new Set;for(;r&&!i.has(r);){if(i.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);i?t.get(i).children.push(e):r.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(r),r}(m?d:d.slice(0,5)),k=d.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ec===a?eY:void 0,onMouseEnter:()=>ed(a),onMouseLeave:()=>ed(e=>e===a&&ec!==a?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:u?"var(--bg-hover)":"transparent",opacity:c?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t$(a),title:h?g("sidebar.expandProject"):g("sidebar.collapseProject"),"aria-label":h?g("sidebar.expandProject"):g("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},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:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},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",style:{flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("input",{ref:eX,value:ek,onChange:e=>ej(e.target.value),onBlur:()=>void tO(a),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),eQ.current=!0,ew(null))},"aria-label":g("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>P(a),title:a,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},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",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),null===p?null:(0,r.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),eo(tq.get(o),g)]}),(0,r.jsx)("button",{type:"button",onClick:()=>tE(a),title:g("sidebar.newSessionTitle",{path:a}),"aria-label":g("sidebar.newSessionTitle",{path:a}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:v||el===a?1:0,pointerEvents:v||el===a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ed(a),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eu(ec===a?null:a),eD(!1),eB(!1),eq(null),u||P(a)},title:g("sidebar.projectActions"),"aria-label":g("sidebar.projectActions"),"aria-expanded":ec===a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ec===a?"var(--bg-selected)":"transparent",color:u&&t8&&!t8.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:v||el===a||ec===a?1:0,pointerEvents:v||el===a||ec===a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ed(a),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(G,{open:ec===a,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[t2&&ez&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eD(e=>!e),title:t8?g("sidebar.switchWorktreeTitle",{path:t8.path}):g("sidebar.switchWorktree"),"aria-label":g("sidebar.worktrees"),"aria-expanded":eF,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eF?"1px solid var(--border)":"none",background:eF?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},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)("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",{style:{flex:1},children:g("sidebar.worktrees")}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,r.jsxs)(G,{open:eF,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderTop:"1px solid var(--border)",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[t4&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eN,onChange:e=>eM(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eM(""),eD(!1))},placeholder:g("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[t5.map(e=>{let t=e.path===A||e.isMain&&!ez.worktrees.some(e=>e.path===A);return eJ===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tM(e.path,!0),disabled:eV,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:g("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>eG(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:g("sidebar.cancel")})]},e.path):(0,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{P(e.path),eD(!1),eq(null),eM("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},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},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)(J,{text:e.branch??K(e.path,z),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:g("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tM(e.path,!1),disabled:eV,title:g("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(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)("polyline",{points:"3 6 5 6 21 6"}),(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"})]})})]},e.path)}),t4&&0===t5.length&&eN.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:g("sidebar.noMatchingWorktrees")})]}),e_?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:eZ,value:eO,onChange:e=>{eH(e.target.value),eq(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tN()),"Escape"===e.key&&(eB(!1),eH(""),eq(null))},placeholder:g("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void tN(),disabled:eV||!eO.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:eV||!eO.trim()?"not-allowed":"pointer",opacity:eV||!eO.trim()?.65:1},children:eV?g("sidebar.creating"):g("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eB(!1),eH(""),eq(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:g("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),eB(!0),eq(null),setTimeout(()=>eZ.current?.focus(),0)},title:g("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:g("sidebar.newWorktree")})]}),eU&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eU})]})]}),(0,r.jsxs)("button",{type:"button",disabled:eS,onClick:()=>{let e;return e=tP.get(I(a))?.alias??"",void(eQ.current=!1,eT(null),ej(e),ew(a),t_())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:eS?"default":"pointer",textAlign:"left",fontSize:11,opacity:eS?.55:1},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:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,r.jsx)("path",{d:"m13.5 8 3 3"})]}),g(tP.get(I(a))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:b,title:tK?g("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void tH(a,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:b?"default":"pointer",textAlign:"left",fontSize:11,opacity:b?.55:1},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:"m6 15 6-6 6 6"})}),g("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:y,title:tK?g("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void tH(a,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:y?"default":"pointer",textAlign:"left",fontSize:11,opacity:y?.55:1},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:"m6 9 6 6 6-6"})}),g("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:eS,onClick:()=>void tB(a,!c),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:eS?"default":"pointer",textAlign:"left",fontSize:11,opacity:eS?.55:1},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:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!c&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),g(c?"sidebar.projectUnhide":"sidebar.projectHide")]}),(s=0===t7(tU.get(o)??[])||tl,(0,r.jsxs)("button",{type:"button",disabled:s,onClick:()=>{t_(),tu(null),to({kind:"project",project:a,label:l})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:s?"default":"pointer",textAlign:"left",fontSize:11,opacity:s?.55:1},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:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),g("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===d.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:g("sidebar.noSessions")}),!h&&w.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:w.map(t=>(0,r.jsx)(ei,{node:t,selectedSessionId:e,runningSessionIds:e8,unreadSessionIds:e5,pinnedSessionIds:e3,onSelectSession:tR,onTogglePinnedSession:tb,onRenamed:ti,onSessionDeleted:ts,onSessionArchived:tg,depth:0},t.session.id))}),!h&&k&&(0,r.jsx)("button",{type:"button",onClick:()=>{et(e=>{let t=new Set(e);return t.has(a)?t.delete(a):t.add(a),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?g("sidebar.showLess"):g("sidebar.showMore")})]},a)})]}),(0,r.jsx)(er,{refreshKey:tm,selectedSessionId:e,onSelectSession:tR,onRestored:tg}),"priority"===B&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[M&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:g("sidebar.loading")}),$&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:$}),!M&&!$&&0===t1.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:g("sidebar.noSessions")}),!M&&!$&&t1.length>0&&(f=t7(t1.flatMap(e=>e.sessions)),(0,r.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",padding:"8px 2px 2px"},children:(0,r.jsx)("button",{type:"button",disabled:0===f||tl,onClick:()=>{tu(null),to({kind:"priority"})},style:{minHeight:v?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:(m=0===f||tl)?"var(--text-dim)":"var(--text-muted)",cursor:m?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"},children:g("sidebar.clearPriorityList")})})),!M&&!$&&t1.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,r.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===n?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,r.jsx)(en,{session:t,selected:t.id===e,running:e8.has(t.id),unread:e5.has(t.id),pinned:e3.has(t.id),onSelect:tR,onTogglePin:tb},t.id))]},t.key))]})]})}function ee({scope:e,eligible:t,runningExcluded:n,busy:s,error:a,onCancel:o,onConfirm:l}){let{t:d}=(0,E.s)(),c=s||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(s);h.current=s;let m=(0,i.useRef)(o);return m.current=o,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],s=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),s.focus()):t.shiftKey||r!==s&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{s||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,r.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:d("sidebar.clearSessionsTitle")}),(0,r.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?d("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):d("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsNone")})]}),a&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:a})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:o,disabled:s,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:s?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:d("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:l,disabled:c,"aria-busy":s,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:c?"var(--text-dim)":"var(--danger)",cursor:c?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:d(s?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function et({filled:e=!1}){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function en({session:e,selected:t,running:n,unread:i,pinned:s,onSelect:a,onTogglePin:o}){let{t:l}=(0,E.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),c=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>a(e),title:`${d}
2
+ ${e.cwd}
3
+ ${new Date(e.modified).toLocaleString()}`,style:{minWidth:0,flex:1,display:"block",padding:"7px 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12.5,fontWeight:500,lineHeight:1.4},children:d}),n&&(0,r.jsx)(es,{}),!n&&i&&(0,r.jsx)(ea,{})]}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:c})]}),(0,r.jsx)("button",{type:"button","aria-pressed":s,"aria-label":l(s?"sidebar.unpin":"sidebar.pin"),title:l(s?"sidebar.unpin":"sidebar.pin"),onClick:()=>o(e.id),style:{width:30,border:"none",background:"transparent",color:s?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(et,{filled:s})})]})}function er({refreshKey:e,selectedSessionId:t,onSelectSession:n,onRestored:s}){let{t:a}=(0,E.s)(),[o,l]=(0,i.useState)(!1),[d,c]=(0,i.useState)([]);(0,i.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/sessions?archived=1",{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e||c(n.sessions)}catch{}})(),()=>{e=!0}},[e]);let u=(0,i.useCallback)(async(e,t)=>{e.stopPropagation();try{await fetch(`/api/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!1})}),s(t)}catch{}},[s]);return 0!==d.length||o?(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>l(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"7px 12px",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:600,textAlign:"left"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:o?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),a("sidebar.archived")," (",d.length,")"]}),o&&(0,r.jsxs)("div",{style:{paddingLeft:12},children:[0===d.length&&(0,r.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:a("sidebar.noArchivedSessions")}),d.map(e=>{let i=R(e.firstMessage)??e.firstMessage,s=e.name||i.slice(0,50)||e.id.slice(0,12);return(0,r.jsxs)("div",{onClick:()=>n(e),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:e.id===t?"2px solid var(--accent)":"2px solid transparent",background:e.id===t?"var(--bg-selected)":"transparent"},children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),(0,r.jsx)("button",{onClick:t=>u(t,e.id),title:a("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:a("sidebar.restore")})]},e.id)})]})]}):null}function ei({node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:s,pinnedSessionIds:a,onSelectSession:o,onRenamed:l,onSessionDeleted:d,onTogglePinnedSession:c,onSessionArchived:u,depth:p}){let[h,m]=(0,i.useState)(!1),f=e.children.length>0;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[p>0&&(0,r.jsx)("div",{style:{position:"absolute",left:10*p+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,r.jsx)(el,{session:e.session,isSelected:e.session.id===t,isRunning:n.has(e.session.id),isUnread:s.has(e.session.id),isPinned:a.has(e.session.id),onClick:()=>o(e.session),onTogglePin:()=>c(e.session.id),onRenamed:l,onDeleted:e=>d?.(e),onArchived:e=>u?.(e),depth:p,hasChildren:f,collapsed:h,onToggleCollapse:()=>m(e=>!e)})]}),f&&!h&&(0,r.jsx)("div",{children:e.children.map(e=>(0,r.jsx)(ei,{node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:s,pinnedSessionIds:a,onSelectSession:o,onTogglePinnedSession:c,onRenamed:l,onSessionDeleted:d,onSessionArchived:u,depth:p+1},e.session.id))})]})}function es(){let{t:e}=(0,E.s)();return(0,r.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("svg",{className:"session-running-spinner",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function ea(){let{t:e}=(0,E.s)();return(0,r.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,r.jsx)("circle",{className:"session-unread-ring",cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4"})]})})}function eo(e,t){return e&&(0!==e.running||0!==e.unread)?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[e.running>0&&(0,r.jsxs)("span",{title:t("sidebar.agentRunning"),"aria-label":`${t("sidebar.agentRunning")} (${e.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("svg",{className:"session-running-spinner",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})}),e.running]}),e.unread>0&&(0,r.jsxs)("span",{title:t("sidebar.newSessionActivity"),"aria-label":`${t("sidebar.newSessionActivity")} (${e.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),e.unread]})]}):null}function el({session:e,isSelected:t,isRunning:n,isUnread:s,isPinned:a,onClick:o,onTogglePin:l,onRenamed:d,onDeleted:c,onArchived:u,depth:p=0,hasChildren:h=!1,collapsed:m=!1,onToggleCollapse:f}){let{t:g}=(0,E.s)(),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(""),[j,S]=(0,i.useState)(!1),[C,I]=(0,i.useState)(!1),T=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(b){let e=requestAnimationFrame(()=>T.current?.select());return()=>cancelAnimationFrame(e)}},[b]);let N=R(e.firstMessage)??e.firstMessage,M=e.name||N.slice(0,50)||e.id.slice(0,12),$=(0,i.useCallback)(t=>{t.stopPropagation(),e.transient||(k(e.name||N.slice(0,50)||e.id.slice(0,12)),y(!0))},[e.name,e.transient,N,e.id]),L=(0,i.useCallback)(async()=>{let t=w.trim();if(y(!1),w!==M&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),d?.()}catch{}},[w,e.id,e.name,d,M]),A=(0,i.useCallback)(async()=>{if(!e.transient){S(!1),I(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),c?.(e.id)}catch{I(!1)}}},[e.id,e.transient,c]),P=(0,i.useCallback)(async t=>{if(t.stopPropagation(),!e.transient)try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!0})}),u?.(e.id)}catch{}},[e.id,e.transient,u]),z=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?A():S(!0)},[A]),W=(0,i.useCallback)(e=>{e.stopPropagation(),A()},[A]),F=(0,i.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),D=(0,i.useCallback)(t=>{(function(e,t=window){let n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)})({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{d?.()}})&&(t.preventDefault(),t.stopPropagation())},[d,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${n?" is-running":""}${s?" is-unread":""}${j?" is-confirming":""}`,onClick:j||b?void 0:o,onContextMenu:j||b?void 0:D,onMouseEnter:()=>v(!0),onMouseLeave:()=>{v(!1)},style:{height:40,display:"flex",alignItems:"center",paddingLeft:p>0?10*p+8:8,paddingRight:4,cursor:j||b?"default":"pointer",background:t?"var(--bg-selected)":x?"var(--bg-hover)":"transparent",borderLeft:"2px solid transparent",transition:"background 0.1s",opacity:C?.5:1,gap:4,overflow:"hidden"},children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:W,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(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)("polyline",{points:"3 6 5 6 21 6"}),(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"})]}),g("sidebar.delete")]}),(0,r.jsx)("button",{onClick:F,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:g("sidebar.cancel")})]})]}):b?(0,r.jsx)("input",{ref:T,value:w,onChange:e=>k(e.target.value),onBlur:L,onKeyDown:e=>{"Enter"===e.key&&L(),"Escape"===e.key&&y(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,r.jsxs)(r.Fragment,{children:[p>0&&(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{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"})]}),(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),o()},"aria-current":t?"page":void 0,title:M,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,color:"var(--text)",fontSize:12.5,fontWeight:t?500:400,lineHeight:1.35,padding:0,border:"none",background:"transparent",fontFamily:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),n&&(0,r.jsx)(es,{}),!n&&s&&(0,r.jsx)(ea,{}),e.worktreeBranch&&(0,r.jsx)("span",{title:g("sidebar.worktreePath",{path:e.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},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)("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"})]})})]}),h&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),f?.()},title:g(m?"sidebar.expandForks":"sidebar.collapseForks"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:m?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),!e.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),l?.()},title:g(a?"sidebar.unpin":"sidebar.pin"),"aria-label":g(a?"sidebar.unpin":"sidebar.pin"),"aria-pressed":a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:a?"var(--bg-selected)":"transparent",border:"none",borderRadius:5,color:a?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||a?1:0,pointerEvents:x||a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,r.jsx)(et,{filled:a})}),(0,r.jsx)("button",{onClick:$,title:g("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,r.jsx)("button",{onClick:P,title:g("sidebar.archive"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(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)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]})}),(0,r.jsx)("button",{onClick:z,title:g("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(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)("polyline",{points:"3 6 5 6 21 6"}),(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"})]})})]})]})})}let ed=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,ec=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eu=/\x1B\[([0-9;]*)m/g,ep=/\x1B_pi:c\x07/g,eh=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],em=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function ef(e){return e.replace(ep,"").replace(ed,"")}function eg(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(ec);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 ex(e,t){let n=eg(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function ev(e){return eg(e)[0]?.char}function eb(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(ep,""),i=ef(e).trimEnd();if(t.test(i))continue;let s=e,a=ev(s);("│"===a||"┃"===a)&&" "===ev(s=ex(s,0))&&(s=ex(s,0));let o=function(e){let t=eg(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),l=o>=0?eg(s)[o]?.char:void 0;("│"===l||"┃"===l)&&(s=ex(s,o)),n.push(function(e){let t=e;for(;;){let e=eg(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&&""===ef(n[0]).trim();)n.shift();for(;n.length>0&&""===ef(n[n.length-1]).trim();)n.pop();return n.length?n:e}function ey(e){let t,n=[],r={},i=0;for(eu.lastIndex=0;null!==(t=eu.exec(e));)t.index>i&&n.push({text:e.slice(i,t.index),style:r}),r=function(e,t){let n={...e};for(let e=0;e<t.length;e++){let r=t[e];if(0===r)for(let e of Object.keys(n))delete n[e];else if(1===r)n.fontWeight=700;else if(2===r)n.opacity=.65;else if(3===r)n.fontStyle="italic";else if(4===r)n.textDecoration="underline";else if(22===r)delete n.fontWeight,delete n.opacity;else if(23===r)delete n.fontStyle;else if(24===r)delete n.textDecoration;else if(39===r)delete n.color;else if(49===r)delete n.backgroundColor;else if(r>=30&&r<=37)n.color=eh[r-30];else if(r>=90&&r<=97)n.color=em[r-90];else if(r>=40&&r<=47)n.backgroundColor=eh[r-40];else if(r>=100&&r<=107)n.backgroundColor=em[r-100];else if((38===r||48===r)&&2===t[e+1]){let[i,s,a]=[t[e+2],t[e+3],t[e+4]];[i,s,a].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?n.color=`rgb(${i}, ${s}, ${a})`:n.backgroundColor=`rgb(${i}, ${s}, ${a})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let i=function(e){if(e>=0&&e<8)return eh[e];if(e>=8&&e<16)return em[e-8];if(e>=16&&e<=231){let t=e-16,n=Math.floor(t/36),r=Math.floor(t%36/6),i=e=>0===e?0:55+40*e;return`rgb(${i(n)}, ${i(r)}, ${i(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);i&&(38===r?n.color=i:n.backgroundColor=i),e+=2}}return n}(r,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),i=t.index+t[0].length;return i<e.length&&n.push({text:e.slice(i),style:r}),n}let ew={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:""},ek={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},ej={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"},eS={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",webm:"audio/webm"};function eC(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eI(e){return null!==(ej[eC(e)]??null)}function eT(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function eN(e,t={}){return!!t.hideThinking&&"thinking"===e.type||function(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}(e,t)}function eM(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eR(e,t={}){let n=[];for(let r of function(e,t={}){return(e.content??[]).filter(e=>!eN(e,t))}(e,t)){let e="image"===r.type||"text"===r.type&&r.text.trim().length>0?"answer":"process",t=n[n.length-1];t?.kind===e?t.blocks.push(r):n.push({kind:e,blocks:[r]})}return n}function eE(e){return e.filter(e=>"toolCall"===e.type).length}function e$(e,t,n){let r=new URLSearchParams({sessionId:e,toolCallId:t});return void 0!==n&&r.set("index",String(n)),`/api/tool-image?${r}`}function eL(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=[],r=-1;return{collect(e,i){for(let s of i)"toolCall"===s.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let n=e.input??{};return"generate_image"===e.toolName||("write"===e.toolName?"xd://generate_image"===n.path:"read"===e.toolName&&"string"==typeof n.path&&eI(n.path))}(s,t.get(s.toolCallId))&&(n.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:s.toolCallId}}),r=e)},attach(e){if(0===n.length)return e;let t=[...n,...e];return n=[],t},takeRemaining(){if(0===n.length)return null;let e={idx:r,blocks:n};return n=[],e}}}let eA=new Map,eP=new Map,ez="command",eW="local-command:";function eF(e){return e?.startsWith(eW)===!0}function eD(e,t,n){let r=new Set(n.map(e=>e.message)),i=[],s=[];for(let n=0;n<e.length;n++){let a=n<t.length;!(r.has(e[n])||a&&eF(t[n]))&&(i.push(e[n]),a&&s.push(t[n]))}for(let e of n){let t=0;if(null!==e.baseEntryId){let n=s.indexOf(e.baseEntryId);if(-1===n)continue;t=n+1}let n=e.message.timestamp??0;for(;t<i.length;){let e=i[t];if(!r.has(e)&&"number"==typeof e.timestamp&&e.timestamp>n)break;t+=1}i.splice(t,0,e.message),t<=s.length&&s.splice(t,0,e.entryId)}return{messages:i,entryIds:s}}function e_(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}function eB(e){try{return decodeURIComponent(e)}catch{return e}}function eO(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function eH(e){let t=eO(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,s=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){s.length>0&&".."!==s[s.length-1]?s.pop():i||n||r||s.push(e);continue}s.push(e)}let a=s.join("/");return n?a:r?`//${a}`:i?`/${a}`:a}function eU(e,t,n=t){let r,i,s,a,o;if(!e)return null;let l=e.split("#",1)[0].split("?",1)[0].trim();if(!l)return null;let d=null,c=null,u=eB(l),p=u.startsWith("\\\\"),h=eO(u),m=h.toLowerCase();if(m.startsWith("/api/")||m.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!m.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(m.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=eB(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}}(h))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(d=h,c="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(d=`${eO(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let f=eH(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&n&&(r=eH(f).replace(/\/+$/,""),i=eH(n).replace(/\/+$/,""),a=(s=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(a===(o=s?i.toLowerCase():i)||a.startsWith(`${o}/`)))?null:f}function eq(e,t){var n;let r;if(t){let e=t.details,n=e&&"object"==typeof e&&"phases"in e?e.phases:void 0;if(!Array.isArray(n))return{kind:"unknown"};let{phases:r,malformed:i}=function(e){let t=[];for(let n of e){if(!n||"object"!=typeof n||!("name"in n)||!("tasks"in n))return{phases:t,malformed:!0};let{name:e,tasks:r}=n;if("string"!=typeof e||!Array.isArray(r))return{phases:t,malformed:!0};let i=Array.isArray(r)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("content"in e)||!("status"in e))return[];let{content:t,status:n}=e;return"string"!=typeof t||"pending"!==n&&"in_progress"!==n&&"completed"!==n&&"abandoned"!==n&&"blocked"!==n?[]:[{content:t,status:n,blocker:"blocker"in e&&"string"==typeof e.blocker?e.blocker:void 0}]}):[];if(i.length!==r.length)return{phases:t,malformed:!0};i.length>0&&t.push({name:e,tasks:i})}return{phases:t,malformed:!1}}(n);return i?{kind:"unknown"}:{kind:"authoritative",phases:r}}let i=Array.isArray(r=(n=e.input)&&"object"==typeof n&&"list"in n?n.list:void 0)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("phase"in e)||!("items"in e))return[];let{phase:t,items:n}=e;if("string"!=typeof t||!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e).map(e=>({content:e,status:"pending"}));return r.length>0?[{name:t,tasks:r}]:[]}):[];return i.length>0?{kind:"preview",phases:i}:{kind:"unknown"}}var eV=n(65063),eK=n(7644),eJ=n(32316);function eG(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function eY(e){return eG(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function eZ(e){let t=eG(e).replace(/\/+$/,"");return t.split("/").pop()??t}function eX(e,t){if(!t)return e;let n=eG(e),r=eG(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}var eQ=n(88374),e0=n(63280),e1=n(94764),e2=n(63835),e8=n(54152),e4=n(84678),e5=n(98164);let e6={...e1.j,attributes:{...e1.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...e1.j.strip||[],"iframe","object","style","form"]};function e3(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,s=0,a=null,o=new Map;for(let e=0;e<n.length;e++){var l;let t=n[e];if(a){r.push(t),RegExp(`</${a}\\s*>`,"i").test(t)&&(a=null);continue}let d=t.match(/^ {0,3}(`{3,}|~{3,})/);if(d){let e=d[1][0],n=d[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 c=t.match(/<(code|pre|script|style)\b/i);if(c){let e=c[1].toLowerCase(),n=t.slice((c.index??0)+c[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(a=e),s=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){s=0,r.push(t);continue}if(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 u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){r.push(`${u[1]}$$`,`${u[1]}${e}`,`${u[1]}$$`);continue}}let p=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(p){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(`${p[1]}$$`,...n.slice(e+1,t).map(e=>e9(e,p[1])),`${p[1]}$$`),e=t;continue}}let h=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(h){let e=h[2].trim();if(e){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(m){let t=m[1],i=m[2].trimEnd();if(i&&!i.includes("$$")){let s=e7(n,e+1,t,o);if(s){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<s.index;i++)r.push(e9(n[i],t));s.content&&r.push(`${t}${s.content}`),r.push(`${t}$$`),e=s.index;continue}}}let f=t.match(/^([ \t]{0,3})\$\$\s*$/);if(f){let t=f[1],i=e7(n,e+1,t,o);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let s=e+1;s<i.index;s++)r.push(e9(n[s],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((l=t,/^\s{0,3}\[[^\]]+\]:/.test(l)||/]\s*\(/.test(l)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(l)||/\b(?:https?|file|mailto):/i.test(l)||/\b[A-Za-z]:\\/.test(l)?l:l.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return r.join(t)}function e7(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,a,o,l;let t=e[i];if(s=t,""===(a=n)?/^ {0,3}\$\$\s*$/.test(s):s.startsWith(a)&&/^\$\$\s*$/.test(s.slice(a.length)))return{index:i,content:"",glued:!1};if(o=t,/^ {0,3}(`{3,}|~{3,})/.test(o)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(o)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(o)||/^ {0,3}>/.test(o)||/<(code|pre|script|style)\b/i.test(o)||(l=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(l)))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 e9(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 te={singleTilde:!1},tt=[[e8.A,["yaml"]],[e4.A,te],e5.A],tn=[[e8.A,["yaml"]],[e4.A,te],e5.A],tr=[e0.A,[e2.A,e6],[eQ.A,{throwOnError:!1,strict:!1}]],ti=[e0.A,[e2.A,e6],[eQ.A,{throwOnError:!1,strict:!1}]],ts="pi-theme",ta=["light","dark","auto"],to={preference:"auto",theme:"light"},tl="omp-theme",td=null,tc=0,tu=new Set,tp=null,th=!1;function tm(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function tf(e){return"auto"===e?tm():e}let tg="--omp-md-";function tx(e){let t=document.documentElement,n=td?.palettes[e];t.dataset.ompThemeMode=e,t.setAttribute("data-seed-color-mode","dark"===e?"dark-only":"light-only"),t.classList.toggle("dark","dark"===e);for(let e=t.style.length-1;e>=0;e-=1){let n=t.style.item(e);n.startsWith("--")&&!n.startsWith(tg)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(tg)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(tl,e)}catch{}}function tv(){if(tp)return tp;let e=function(){try{let e=localStorage.getItem(ts);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(tl);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=tf(e);return tx(t),tp={preference:e,theme:t}}function tb(e,t,n){if(tx(t),n)try{localStorage.setItem(ts,e)}catch{}tp={preference:e,theme:t},tu.forEach(e=>e())}function ty(){let e=tv();if("auto"!==e.preference)return;let t=tm();t!==e.theme&&tb("auto",t,!1)}function tw(e){return tu.add(e),tv(),th||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",ty),window.addEventListener("focus",ty),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&ty()}),th=!0),ty(),()=>{tu.delete(e)}}function tk(){return tv()}function tj(){return to}async function tS(e){let t=++tc,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/theme${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Theme request failed (${r.status})`);let i=await r.json();if(t===tc){td=i;try{localStorage.setItem("omp-theme-config",JSON.stringify(td))}catch{}tx(tv().theme)}}function tC(e){let t=(0,i.useSyncExternalStore)(tw,tk,tj);(0,i.useEffect)(()=>{e?.syncWithOmp&&tS(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let n=(0,i.useCallback)((e,t)=>{let n=tf(e),r=()=>{tb(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,a=t?.y??window.innerHeight/2,o=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(a,window.innerHeight-a));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${a}px)`,`circle(${o}px at ${s}px ${a}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),r=(0,i.useCallback)(e=>{var t;let r;n((t=tv().preference,r=ta.indexOf(t),ta[(r+1)%ta.length]),e)},[n]),s=(0,i.useCallback)((e,t)=>{n(e,t)},[n]);return{theme:t.theme,preference:t.preference,toggleTheme:r,setPreference:s,isDark:"dark"===t.theme}}function tI(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()}}function tT({code:e,isStreaming:t,defaultPreview:s=!1}){let{isDark:a}=tC(),{t:o}=(0,E.s)(),[l,d]=(0,i.useState)(s),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),m=`${a?"dark":"light"}
4
+ ${e}`,f=l&&!t;(0,i.useEffect)(()=>{if(!f)return;let t=!1;return u({key:m,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:a?"dark":"default"}),!await r.parse(e,{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,e);t||u({key:m,status:"ready",svg:s.svg})})().catch(()=>{t||u({key:m,status:"error"})}),()=>{t=!0}},[e,m,a,f]);let g=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>d(e=>!e),disabled:t,title:t?o("i18n.previewAfterStreaming"):f?o("i18n.showMermaidSource"):o("i18n.previewMermaid"),className:["markdown-code-action",f?"is-active":""].filter(Boolean).join(" "),children:f?o("i18n.source"):o("i18n.preview")}),[t,f,o]);if(!f)return(0,r.jsx)(tM,{code:e,lang:"mermaid",headerAction:g,isStreaming:t});let x=c?.key===m&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:o("i18n.invalidMermaid")}):c?.key!==m||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":o("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!p&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:o("i18n.openMermaidViewer"),"aria-label":o("i18n.openMermaidViewer"),onClick:()=>h(!0),dangerouslySetInnerHTML:{__html:c.svg}}),p&&(0,r.jsx)(tN,{svg:c.svg,onClose:()=>h(!1)})]});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:"mermaid"}),g]}),x]})}function tN({svg:e,onClose:t}){let{t:n}=(0,E.s)(),s=(0,i.useRef)(null),[a,o]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=s.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:s,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},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:n("i18n.mermaidDiagram")}),(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:()=>o(e=>Math.max(.5,e-.25)),disabled:a<=.5,title:n("i18n.zoomOut"),"aria-label":n("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*a),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>Math.min(3,e+.25)),disabled:a>=3,title:n("i18n.zoomIn"),"aria-label":n("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:()=>o(1),title:n("i18n.fitToWidth"),"aria-label":n("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:t,title:n("i18n.close"),"aria-label":n("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&&t()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*a}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let tM=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:s}){let{isDark:a}=tC(),{t:o}=(0,E.s)(),[l,d]=(0,i.useState)(!1);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||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[n,(0,r.jsx)("button",{onClick:()=>{tI(e).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action",children:o(l?"i18n.copied":"i18n.copy")})]})]}),s?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(eV.A,{language:t||"text",style:a?eK.xJ:eK.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal"},customStyle:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,borderRadius:0,background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e})]})});function tR({children:e,className:t,isStreaming:n,cwd:s,onOpenFile:a}){let o=(0,i.useMemo)(()=>e3(e),[e]),l=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let s=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===s?(0,r.jsx)(tT,{code:a.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(tM,{code:a.replace(/\n$/,""),lang:s,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let i=a?eU(e,s):null;return i&&a?(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),a(i))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?eU(e,s):null,a=i?`/api/files/${eY(i)}?type=read`:e;return(0,r.jsx)("img",{src:a,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[s,n,a]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(eJ.oz,{remarkPlugins:tt,rehypePlugins:tr,components:l,children:o})})}let tE=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,t$=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/,tL={hideThinkingBlock:!1},tA=new Set,tP=tL,tz=0;function tW(e){return tA.add(e),()=>{tA.delete(e)}}function tF(){return tP}function tD(){return tL}async function t_(e){let t=++tz,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/display-settings${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Display settings request failed (${r.status})`);let i=await r.json();t!==tz||i.hideThinkingBlock!==tP.hideThinkingBlock&&(tP={hideThinkingBlock:!0===i.hideThinkingBlock},tA.forEach(e=>e()))}function tB(){return(0,i.useSyncExternalStore)(tW,tF,tD)}let tO="/api/sidecars/resource";function tH(e){if("string"==typeof e.status&&"unknown"!==e.status)return"exhausted"===e.status;let t=e.amount??{},n=e=>{let n=t[e];return"number"==typeof n&&Number.isFinite(n)?n:null},r=n("usedFraction");if(null!==r&&r>=1)return!0;let i=n("remainingFraction");if(null!==i&&i<=0)return!0;let s=n("used"),a=n("limit");if(null!==s&&null!==a&&s>=a)return!0;let o=n("remaining");return null!==o&&o<=0||"percent"===t.unit&&null!==s&&s>=100}let tU=[{alias:"RIN(린)",file:"rin.webp"},{alias:"MIO(미오)",file:"mio.webp"},{alias:"NOVA(노바)",file:"nova.webp",provider:"opencode-go"},{alias:"YUKI(유키)",file:"yuki.webp",provider:"openai-codex"},{alias:"ISANA(이사나)",file:"isana.webp",provider:"b-ai"},{alias:"SHION(시온)",file:"shion.webp",provider:"web6"},{alias:"HIKARI(히카리)",file:"hikari.webp",provider:"google-antigravity"}],tq=[{seed:3,alias:tU[3].alias,provider:"openai-codex",model:"gpt-6-astra",voice:"빠른 판단\xb7선명한 결론\xb7영리한 장난기",summonExample:"유키 불러와",switchExample:"유키로 교체해"},{seed:4,alias:tU[4].alias,provider:"b-ai",model:"deepseek-v4.1-flash",voice:"호기심과 실행력\xb7생기 있는 관찰\xb7솔직함",summonExample:"이사나 불러와",switchExample:"이사나로 교체해"},{seed:0,alias:tU[0].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:0,voice:"조용한 집중\xb7날카로운 분석\xb7건조한 유머",summonExample:"린 불러와",switchExample:"린으로 교체해"},{seed:1,alias:tU[1].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:1,voice:"따뜻하고 세심함\xb7부드럽고 안정적인 설명",summonExample:"미오 불러와",switchExample:"미오로 교체해"},{seed:2,alias:tU[2].alias,provider:"opencode-go",model:"muse-spark-1.3-contributor",voice:"번뜩이는 발상\xb7즉흥적 시제품\xb7낙천적 재도전",summonExample:"노바 불러와",switchExample:"노바로 교체해"},{seed:5,alias:tU[5].alias,provider:"web6",model:"gpt-6-pro",voice:"우아한 전략\xb7넓은 시야\xb7은근한 장난기",summonExample:"시온 불러와",switchExample:null,summonNote:"WEB6 상담으로 호출합니다.",switchNote:"SHION은 WEB6 상담 전용이라 Main으로 교체할 수 없습니다."}],tV=tq.filter(e=>null!==e.switchExample),tK=tU.filter(e=>!("provider"in e)).length,tJ=new Map(tU.flatMap((e,t)=>"provider"in e?[[e.provider,t]]:[])),tG=new Map([...tJ].map(([e,t])=>[e,{seed:t,alias:tU[t].alias}]));function tY(e){return tU[e%tU.length].alias}function tZ(e){return`/avatars/${tU[e%tU.length].file}`}function tX(e){return 0===e.length?"":1===e.length?"•••":2===e.length?`${e[0]}•••`:`${e[0]}•••${e[e.length-1]}`}function tQ(e){return({"openai-codex":"OpenAI Codex",anthropic:"Anthropic","google-gemini":"Google Gemini","github-copilot":"GitHub Copilot","opencode-go":"OpenCode Go",devin:"Devin","b-ai":"B.AI",web6:"WEB6"})[e]??e.replace(/(^|-)(\w)/g,(e,t,n)=>`${t?" ":""}${n.toUpperCase()}`)}function t0(e){let t=new Map;return e.map(e=>{var n;let r=e.metadata?.email,i=e.metadata?.accountId,s="string"==typeof r&&r.length>0?r:"string"==typeof i?i:"",a=s.length>0?function(e){let t=e.lastIndexOf("@");if(t<=0)return tX(e);let n=e.slice(t+1),r=n.lastIndexOf("."),i=r<0?n:n.slice(0,r),s=r<0?"":n.slice(r);return`${tX(e.slice(0,t))}@${0===i.length?"":`${i[0]}•••`}${s}`}(s):"",o=(n=e.provider,tJ.get(n)??-1);if(o>=0)return{seed:o,alias:tU[o].alias,masked:a,raw:s};let l=t.get(e.provider)??0;t.set(e.provider,l+1);let d=l%tK,c=l<tK?tU[d].alias:`${tU[d].alias}${l+1}`;return{seed:d,alias:c,masked:a,raw:s}})}class t1 extends Error{constructor(e,t,n,r){super(e,r),this.kind=t,this.status=n,this.name="ResourceClientError",this.code=r?.code,this.outcomeUnknown=r?.outcomeUnknown}}function t2(e,t){return`${tO}${e}${t?"?refresh=1":""}`}function t8(e,t,n=!1){return e instanceof t1?e:t?new t1("요청 시간이 초과되었습니다.","timeout",void 0,{cause:e}):n||e instanceof DOMException&&"AbortError"===e.name?new t1("요청이 취소되었습니다.","aborted",void 0,{cause:e}):new t1(e instanceof Error?e.message:String(e),"network",void 0,{cause:e})}function t4(e,t){return null==e?{status:"error",data:null,error:t}:{status:"stale",data:e,error:t}}async function t5(e,t){let n,r=t.fetchImpl??fetch,i=new AbortController,s=!1,a=()=>i.abort(t.signal?.reason);t.signal?.aborted?a():t.signal?.addEventListener("abort",a,{once:!0}),null!=t.timeoutMs&&(n=setTimeout(()=>{s=!0,i.abort(new DOMException("Timeout","TimeoutError"))},t.timeoutMs));try{let t,n=await r(e,{signal:i.signal});try{t=await n.json()}catch(e){throw new t1("리소스 서버 응답이 JSON이 아닙니다.","invalid-response",n.status,{cause:e})}let s=t&&"object"==typeof t?t:null,a="string"==typeof s?.error?s.error:null;if(!n.ok||a)throw new t1(a??`HTTP ${n.status}`,"http",n.status,{code:"string"==typeof s?.code?s.code:void 0,outcomeUnknown:s?.outcomeUnknown===!0});return t}catch(e){throw t8(e,s,i.signal.aborted)}finally{clearTimeout(n),t.signal?.removeEventListener("abort",a)}}let t6="google-antigravity",t3=`${t6}:google:`;function t7(e){if(e.provider!==t6||!Array.isArray(e.limits))return e;let t=e.limits.filter(e=>"string"==typeof e.id&&e.id.startsWith(t3));return t.length===e.limits.length?e:{...e,limits:t}}async function t9(e={}){try{let t=await t5(t2("/usage",!0===e.refresh),e);if(!t||!Array.isArray(t.reports))throw new t1("사용량 응답 형식이 올바르지 않습니다.","invalid-response");let n=t.reports.map(t7);return{status:"fresh",data:n.every((e,n)=>e===t.reports[n])?t:{...t,reports:n},error:null}}catch(t){return t4(e.previous,t8(t,!1))}}async function ne(e,t={}){if(!e)return t4(void 0,new t1("세션 id가 올바르지 않습니다.","invalid-response"));try{let n=await t5(`/api/agent/${encodeURIComponent(e)}/account`,t),r=n?.state==="resolved"||n?.state==="unresolved"||n?.state==="not-running"||n?.state==="unsupported";if(!n||n.sessionId!==e||"number"!=typeof n.observedAt||!r||!Array.isArray(n.resetRecommendations))throw new t1("현재 계정 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:n,error:null}}catch(e){return t4(void 0,t8(e,!1))}}async function nt(e={}){try{let t=await t5(t2("/models",!0===e.refresh),{...e,timeoutMs:e.timeoutMs??12e4});if(!t||!Array.isArray(t.models)||!Array.isArray(t.agents)||!Array.isArray(t.daily))throw new t1("모델 집계 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return t4(e.previous,t8(t,!1))}}async function nn(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new t1("credential id가 올바르지 않습니다.","invalid-response");let r=await t5(`${tO}/credential/${e}/${t?"enable":"disable"}`,{...n,timeoutMs:n.timeoutMs??2e4,fetchImpl:async(e,t)=>(n.fetchImpl??fetch)(e,{...t,method:"POST"})});if(!r||!0!==r.ok||r.credentialId!==e||!t!==r.disabled)throw new t1("계정 전환 응답 형식이 올바르지 않습니다.","invalid-response");return r}async function nr(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new t1("credential id가 올바르지 않습니다.","invalid-response");if(!t)throw new t1("credit id가 올바르지 않습니다.","invalid-response");let r=await t5(`${tO}/credential/${e}/reset`,{...n,timeoutMs:n.timeoutMs??2e4,fetchImpl:async(e,r)=>{let i=new Headers(r?.headers);return i.set("Content-Type","application/json"),(n.fetchImpl??fetch)(e,{...r,method:"POST",headers:i,body:JSON.stringify({confirm:!0,creditId:t})})}});if(!r||"boolean"!=typeof r.ok||r.credentialId!==e||r.creditId!==t||"string"!=typeof r.code||r.ok!==("reset"===r.code))throw new t1("리셋 사용 응답 형식이 올바르지 않습니다.","invalid-response");return r}function ni(e,t){if(e.has(t))return null;e.add(t);let n=!1;return()=>{n||(n=!0,e.delete(t))}}let ns={faces:new Map,pins:new Map},na=[],no=ns,nl=null,nd=new Map,nc=new Set;function nu(e){return nc.add(e),()=>{nc.delete(e)}}function np(e){no=e,nc.forEach(e=>e())}function nh(e){return Number.isSafeInteger(e)&&e>0}function nm(e,t){return`${e}:${t}`}function nf(e,t,n){if(!t)return null;if(nh(n)){let e=no.faces.get(nm(t,n));if(e)return e}let r=e?no.pins.get(e):void 0;if(r&&r.provider===t){let e=no.faces.get(nm(t,r.credentialId));if(e)return e}return tG.get(t)??null}function ng(e,t,n){let r=!!t&&!nh(n)&&!!e;return(0,i.useEffect)(()=>{r&&e&&t&&function(e,t){let n=Date.now(),r=no.pins.get(e);if(r&&r.provider===t&&n-r.observedAt<3e4)return;let i=`${e}\u0000${t}`,s=nd.get(i);void 0!==s&&n-s<3e4||(nd.set(i,n),ne(e).then(t=>{let n=t.data;if(!n||"resolved"!==n.state)return;let{provider:r,credentialId:i}=n;if("string"!=typeof r||""===r||!nh(i))return;let s=new Map(no.pins);s.set(e,{provider:r,credentialId:i,observedAt:Date.now()}),np({faces:no.faces,pins:s})}).catch(()=>{}))}(e,t)},[r,e,t]),(0,i.useSyncExternalStore)(nu,()=>nf(e,t,n),()=>null)}function nx({seed:e,size:t,provider:n}){let[s,a]=(0,i.useState)(!1),[o,l]=(0,i.useState)(!1);return s?(0,r.jsx)("span",{className:"account-avatar account-avatar-mono","data-tone":e%6,style:{width:t,height:t,fontSize:Math.round(.46*t)},"aria-hidden":"true",children:tY(e).slice(0,1)}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"account-avatar-button",style:{width:t,height:t},onClick:e=>{e.stopPropagation(),l(!0)},"aria-label":tY(e),children:(0,r.jsx)("img",{className:"account-avatar",src:tZ(e),width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>a(!0)})}),o&&(0,r.jsx)(nv,{seed:e,provider:n,onClose:()=>l(!1)})]})}function nv({seed:e,provider:t,onClose:n}){let{t:s}=(0,E.s)(),a=(0,i.useRef)(null);(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()}},[]);let o=tY(e);return(0,F.createPortal)((0,r.jsxs)("dialog",{ref:a,className:"account-avatar-dialog","aria-label":o,onCancel:e=>{e.preventDefault(),n()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),n())},onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&n()},children:[(0,r.jsx)("img",{className:"account-avatar-full",src:tZ(e),width:256,height:256,alt:o,draggable:!1}),(0,r.jsxs)("p",{className:"account-avatar-caption",children:[(0,r.jsx)("span",{className:"account-avatar-caption-alias",children:o}),t?(0,r.jsx)("span",{className:"account-avatar-caption-provider",children:tQ(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:s("i18n.close")})]}),document.body)}function nb(e){let t,n=[],r=null,i=0,s=0,a=0,o=0,l=[],d=[],c=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){l=[],d=[];return}let e=Math.max(l.length,d.length);for(let t=0;t<e;t++){let e=l[t]?{lineNo:l[t].lineNo,text:l[t].text,type:"removed"}:c(),n=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"added"}:c();r.rows.push({type:"line",left:e,right:n})}l=[],d=[]};for(let c of e.split(/\r?\n/)){if(!(a>0||o>0)){if(c.startsWith("--- ")){u(),t=ny(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:ny(c.slice(4)),rows:[]},n.push(r);continue}}let e=c.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),i=Number(e[1]),s=Number(e[3]),a=void 0===e[2]?1:Number(e[2]),o=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:c});continue}if(!r)continue;if(c.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:c});continue}let p=c[0],h=c.slice(1);" "===p?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:h,type:"context"},right:{lineNo:s++,text:h,type:"context"}}),a>0&&a--,o>0&&o--):"-"===p?(l.push({lineNo:i++,text:h}),a>0&&a--):"+"===p?(d.push({lineNo:s++,text:h}),o>0&&o--):""!==c&&(u(),r.rows.push({type:"hunk",text:c}))}u();let p=n.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function ny(e){return e.split(" ")[0].trim()}function nw({task:e}){let t="completed"===e.status,n="abandoned"===e.status,i="in_progress"===e.status,s="blocked"===e.status;return(0,r.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}`,className:`todo-checklist-row ${t?"is-completed":n?"is-abandoned":s?"is-blocked":i?"is-active":"is-pending"}`,children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:t?"✓":n?"\xd7":s?"!":i?"›":""}),(0,r.jsxs)("span",{className:"todo-checklist-content",children:[e.content,s&&e.blocker?(0,r.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null]})]})}let nk="/icons/catppuccin";function nj({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${nk}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${nk}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function nS({size:e=14,open:t=!1}){return(0,r.jsx)(nj,{name:t?"_folder_open":"_folder",size:e})}function nC({size:e=14}){return(0,r.jsx)(nj,{name:"_file",size:e})}let nI={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",markdown:"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 nT(e,t=14){let 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)(nj,{name:i,size:t});let s=nI[n.split(".").pop()??""];return s?(0,r.jsx)(nj,{name:s,size:t}):(0,r.jsx)(nC,{size:t})}function nN({files:e,onOpenFile:t}){let{t:n}=(0,E.s)();return 0===e.length?null:(0,r.jsx)("div",{"aria-label":n("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let i=eZ(e);return(0,r.jsxs)("button",{type:"button",title:e,"aria-label":n("chat.openWrittenFile",{name:i}),onClick:()=>t?.(e),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:[nT(i,12),(0,r.jsx)("span",{children:i})]},e)})})}class nM extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let nR={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},nE={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},n$={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function nL(e){let t=e.name.toLocaleLowerCase();if(t.endsWith(".md")||t.endsWith(".markdown"))return"markdown";if(t.endsWith(".pdf"))return"pdf";let n=t.lastIndexOf(".");if(n>0&&nE[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&n$[r]?"text":null}let nA={".mp3":"audio/mpeg",".wav":"audio/wav",".wave":"audio/wav",".m4a":"audio/mp4",".ogg":"audio/ogg",".oga":"audio/ogg",".opus":"audio/ogg",".flac":"audio/flac",".webm":"audio/webm",".aac":"audio/aac",".aif":"audio/aiff",".aiff":"audio/aiff"};function nP(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?nA[t.slice(n)]:void 0;if(r)return r;let i=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return i?.startsWith("audio/")?i:null}function nz(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function nW(e){if(!Array.isArray(e))return[];let t=[],n=0,r=0;for(let i of e){if(i&&"object"==typeof i&&"string"==typeof i.name&&i.name.length>0&&("text/markdown"===i.mimeType||"text/plain"===i.mimeType||"application/pdf"===i.mimeType)&&"number"==typeof i.size&&Number.isSafeInteger(i.size)&&i.size>=0&&i.size<=8388608&&"string"==typeof i.text&&i.text.length<=12e4){if(t.length>=3)break;!(n+i.size>0x1000000)&&(r+i.text.length>24e4||(t.push({name:i.name,mimeType:i.mimeType,size:i.size,text:i.text}),n+=i.size,r+=i.text.length))}}return t}async function nF(e){let t,n=nL(e);if(!n)throw new nM("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new nM("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await nq(e);else{try{t=await e.text()}catch(e){throw new nM("read_failed",e instanceof Error?e.message:String(e))}nV(t)}return{name:e.name,mimeType:nR[n],size:e.size,text:t}}function nD(e,t){let n=nW(t);if(0===n.length)return e;let r={userMessageLength:e.length,documents:n.map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,textLength:r.length}))},i=`${nK}${JSON.stringify(r)}${nJ}
5
+ ${nG}${e}${nY}`;return n.forEach((e,t)=>{i+=nZ(t,e),i+=e.text,i+=nX(t)}),i}function n_(e){let t;if(!e.startsWith(nK))return null;let n=e.indexOf("\n");if(n<0)return null;let r=e.slice(0,n);if(!r.endsWith(nJ))return null;try{t=JSON.parse(r.slice(nK.length,-nJ.length))}catch{return null}if(!function(e){if(!e||"object"!=typeof e||!Number.isSafeInteger(e.userMessageLength)||(e.userMessageLength??-1)<0||!Array.isArray(e.documents)||0===e.documents.length||e.documents.length>3)return!1;let t=0,n=0;for(let r of e.documents){if(!r||"object"!=typeof r||"string"!=typeof r.name||0===r.name.length||"text/markdown"!==r.mimeType&&"text/plain"!==r.mimeType&&"application/pdf"!==r.mimeType||!Number.isSafeInteger(r.size)||(r.size??-1)<0||(r.size??0)>8388608||!Number.isSafeInteger(r.textLength)||(r.textLength??-1)<0||(r.textLength??0)>12e4)return!1;t+=r.size??0,n+=r.textLength??0}return t<=0x1000000&&n<=24e4}(t))return null;let i=n+1;if(!e.startsWith(nG,i))return null;let s=(i+=nG.length)+t.userMessageLength;if(s>e.length)return null;let a=e.slice(i,s);if(i=s,!e.startsWith(nY,i))return null;i+=nY.length;let o=[];for(let n=0;n<t.documents.length;n+=1){let r=t.documents[n],s=nZ(n,r);if(!e.startsWith(s,i))return null;let a=(i+=s.length)+r.textLength;if(a>e.length)return null;let l=e.slice(i,a);i=a;let d=nX(n);if(!e.startsWith(d,i))return null;i+=d.length,o.push({name:r.name,mimeType:r.mimeType,size:r.size,text:l})}return i===e.length?{message:a,documents:o}:null}function nB(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(+(e<10240))} KB`:`${(e/1048576).toFixed(1)} MB`}let nO="\n[transcript truncated to fit the attachment limit]",nH="File saved at: ";async function nU(e,t){let n=new FormData;n.append("file",e,e.name),t&&n.append("sessionId",t);let r=await fetch("/api/attachments",{method:"POST",body:n}),i=await r.json().catch(()=>null);if(!r.ok||"string"!=typeof i?.path||"number"!=typeof i.size||"string"!=typeof i.mimeType)throw Error("string"==typeof i?.error?i.error:`HTTP ${r.status}`);return{path:i.path,size:i.size,mimeType:i.mimeType,..."string"==typeof i.transcript?{transcript:i.transcript}:{},..."string"==typeof i.transcriptError?{transcriptError:i.transcriptError}:{}}}async function nq(e){let t;try{t=await fetch("/api/document-text",{method:"POST",headers:{"Content-Type":"application/pdf"},body:e})}catch(e){throw new nM("read_failed",e instanceof Error?e.message:String(e))}let n=await t.json().catch(()=>null);if(!t.ok){var r;throw new nM("string"==typeof n?.code&&("unsupported"===(r=n.code)||"file_too_large"===r||"text_too_large"===r||"too_many_pages"===r||"no_extractable_text"===r||"password_protected"===r||"invalid_pdf"===r||"read_failed"===r)?n.code:"invalid_pdf","string"==typeof n?.error?n.error:`Unable to read ${e.name}`)}if("string"!=typeof n?.text)throw new nM("invalid_pdf",`Unable to read ${e.name}`);return nV(n.text),n.text}function nV(e){if(e.length>12e4)throw new nM("text_too_large","Document exceeds the extracted text limit")}let nK="\x3c!-- omp-web-document-context-v1:",nJ=" --\x3e",nG="User message:\n",nY="\n\nAttached documents (locally extracted text supplied by the user):\n";function nZ(e,t){return`
6
+ --- Begin attached document ${e+1}: ${JSON.stringify(t.name)} (${t.mimeType}, ${t.size} bytes) ---
7
+ `}function nX(e){return`
8
+ --- End attached document ${e+1} ---`}let nQ=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function n0(e){let t=0,n=0;for(let r of e)nQ.test(r)?t++:n++;return t+n/4}let n1=new Map;function n2({children:e,className:t,...n}){let{t:s}=(0,E.s)(),[a,o]=(0,i.useState)(!1);if(e.length<=1e5)return(0,r.jsx)(tR,{className:t,...n,children:e});if(!a){var l;return(0,r.jsxs)("button",{onClick:()=>o(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",s("i18n.largeMessageReveal",{size:(l=e.length)>=1e6?`${(l/1e6).toFixed(1)} MB`:l>=1e3?`${Math.round(l/1e3)} KB`:`${l} B`})]})}return(0,r.jsx)("div",{className:t,style:{maxHeight:420,overflow:"auto",fontSize:12,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:e})})}function n8(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 n4=(0,i.memo)(function({message:e,isStreaming:t,toolResults:n,modelNames:i,cwd:s,onOpenFile:a,entryId:o,onFork:l,forking:d,onNavigate:c,prevAssistantEntryId:u,onEditContent:p,showTimestamp:h,prevTimestamp:m,sessionId:f,writtenFiles:g}){return"user"===e.role?(0,r.jsx)(n5,{message:e,cwd:s,onOpenFile:a,entryId:o,onFork:l,forking:d,onNavigate:c,prevAssistantEntryId:u,onEditContent:p}):"assistant"===e.role?(0,r.jsx)(n6,{message:e,isStreaming:t,toolResults:n,modelNames:i,cwd:s,onOpenFile:a,showTimestamp:h,prevTimestamp:m,sessionId:f,entryId:o,writtenFiles:g}):"toolResult"===e.role?null:"custom"===e.role?"compaction"===e.customType?(0,r.jsx)(rx,{message:e}):(0,r.jsx)(ry,{message:e,cwd:s,onOpenFile:a}):"bashExecution"===e.role?(0,r.jsx)(rj,{message:e,sessionId:f}):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.entryId===t.entryId&&e.onFork===t.onFork&&e.forking===t.forking&&e.onNavigate===t.onNavigate&&e.prevAssistantEntryId===t.prevAssistantEntryId&&e.onEditContent===t.onEditContent&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.sessionId===t.sessionId);function n5({message:e,cwd:t,onOpenFile:n,entryId:s,onFork:a,forking:o,onNavigate:l,prevAssistantEntryId:d,onEditContent:c}){let{t:u}=(0,E.s)(),[p,h]=(0,i.useState)(!1),[m,f]=(0,i.useState)(!1),g="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),x=n_(g),v=x?.message??g,b=x?.documents??[],y="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),w=n8(e.timestamp),k=!!s&&!!a,j=!!d&&!!l;return(0,r.jsxs)("div",{className:"message-user",style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,r.jsxs)("div",{className:"message-user-bubble",style:{flex:1,minWidth:0,background:"var(--user-bg)",border:"1px solid var(--accent-line)",borderRadius:"var(--seed-radius-r3)",padding:"8px 12px",fontSize:14,lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",maxHeight:300,overflowY:"auto"},children:[y.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!v},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)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t)})}),b.length>0&&(0,r.jsx)("div",{role:"list","aria-label":u("chat.attachments"),style:{display:"flex",flexDirection:"column",gap:5,marginBottom:8*!!v},children:b.map((e,t)=>{var n;return(0,r.jsxs)("div",{role:"listitem",style:{display:"flex",alignItems:"center",gap:7,minWidth:0,padding:"5px 7px",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",background:"color-mix(in srgb, var(--user-bg) 70%, var(--bg-panel))"},children:[nT(e.name,14),(0,r.jsx)("span",{title:e.name,style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:[(n="application/pdf"===e.mimeType?"pdf":"text/markdown"===e.mimeType?"markdown":e.text.startsWith(nH)?nP({name:e.name,type:""})?"audio":"file":"text","pdf"===n?"PDF":"markdown"===n?"Markdown":"audio"===n?u("chat.attachKindAudio"):"file"===n?u("chat.attachKindFile"):"Text")," \xb7 ",nB(e.size)]})]},`${e.name}-${t}`)})}),v&&(0,r.jsx)(n2,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:v})]})}),(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:+!!p,pointerEvents:p?"auto":"none",transition:"opacity 0.12s"},children:(0,r.jsxs)("button",{onClick:()=>{tI(function(e){let t=n_(e);if(!t)return e;let n=t.documents.map(e=>e.name).join(", ");return t.message.trim()?`${t.message}
9
+
10
+ Attached: ${n}`:`Attached: ${n}`}(g)).then(()=>{f(!0),setTimeout(()=>f(!1),1500)})},title:u("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:m?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{m||(e.currentTarget.style.color="var(--text-dim)")},children:[m?(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"})]}),m?u("i18n.copied"):u("i18n.copy")]})}),(k||j)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:p||o?1:0,pointerEvents:p||o?"auto":"none",transition:"opacity 0.12s"},children:[j&&(0,r.jsxs)("button",{onClick:()=>{l(d),c?.(e)},title:u("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"})]}),u("i18n.editFromHere")]}),k&&(0,r.jsxs)("button",{onClick:()=>{a(s)},disabled:o,title:o?u("i18n.creatingSession"):u("i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:o?"var(--accent)":"var(--text-dim)",cursor:o?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{o||(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"})]}),o?u("i18n.creating"):u("i18n.newSession")]})]}),w&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:w})]})]})}function n6({message:e,isStreaming:t,toolResults:n,modelNames:s,cwd:a,onOpenFile:o,showTimestamp:l,prevTimestamp:d,sessionId:c,entryId:u,writtenFiles:p}){var h;let m,{t:f}=(0,E.s)(),{hideThinkingBlock:g}=tB(),x=l?n8(e.timestamp):null,v=ng(c,e.provider,e.credentialId),b=s?.[`${e.provider}:${e.model}`]??s?.[e.model]??e.model,y=(0,i.useMemo)(()=>(e.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(({block:e})=>!eN(e,{isStreaming:t,hideThinking:g})),[e.content,t,g]),w=(0,i.useMemo)(()=>y.map(({block:e})=>e),[y]),k=eM(e,{isStreaming:t}),[j,S]=(0,i.useState)(!1),[C,I]=(0,i.useState)(!1),[T,N]=(0,i.useState)(!1),M=(0,i.useRef)(null),[R,$]=(0,i.useState)(null),L=(0,i.useRef)(y);L.current=y;let A=(0,i.useRef)(new Map),P=(0,i.useMemo)(()=>{if(!t)return A.current=new Map,0;let e=new Map,n=0;for(let{block:t,originalIndex:r}of y){let i="text"===t.type?t.text:"thinking"===t.type?t.thinking:"toolCall"===t.type?JSON.stringify(t.input??{})??"":null;if(null===i)continue;let s=function(e,t){var n,r;if(!e||!t.startsWith(e.text))return n0(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-=1/4,s--),i+n0(t.slice(s))}(A.current.get(r),i);e.set(r,{text:i,tokens:s}),n+=s}return A.current=e,n},[y,t]),z=(0,i.useRef)(P);z.current=P;let W=(0,i.useRef)(new Map),[F,D]=(0,i.useState)(new Map),_=(0,i.useMemo)(()=>{if(!e.timestamp||!d)return;let t=Math.round((e.timestamp-d)/1e3);return t>0?t:void 0},[e.timestamp,d]),B=(0,i.useMemo)(()=>{let t=new Map;if(!n||!e.timestamp)return t;for(let[r,i]of n)if(i.timestamp&&e.timestamp){let n=Math.round((i.timestamp-e.timestamp)/1e3);n>0&&t.set(r,n)}return t},[n,e.timestamp]),O=w.filter(e=>"text"===e.type).map(e=>e.text).join("\n");return((0,i.useEffect)(()=>{if(!t){let e=new Date().getTime();D(t=>{let n=new Map(t);for(let[t,r]of W.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),M.current=null,$(null);return}let e=setInterval(()=>{let e=L.current,t=Date.now();e.forEach(({originalIndex:e})=>{W.current.has(e)||W.current.set(e,t)}),D(n=>{let r=!1,i=new Map(n);for(let n=0;n<e.length-1;n++){let s=e[n].originalIndex,a=e[n+1].originalIndex;if(!i.has(s)&&W.current.has(s)){let e=W.current.get(s),n=W.current.get(a)??t;i.set(s,Math.round((n-e)/1e3)),r=!0}}return r?i:n});let n=z.current;if(0===n)return;null===M.current&&(M.current=t);let r=(t-M.current)/1e3;r>.5&&$(n/r)},300);return()=>clearInterval(e)},[t]),0!==w.length||t||k)?(0,r.jsxs)("div",{className:`message-assistant${t?" is-streaming":""}`,style:{marginBottom:16},onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),children:[(0,r.jsx)("div",{className:"message-assistant-role",style:{fontSize:11,color:"var(--text-dim)",marginBottom:2,display:"flex",alignItems:"center",gap:9,...v?{minHeight:40}:null},children:e.provider&&(0,r.jsxs)(r.Fragment,{children:[v&&(0,r.jsx)(nx,{seed:v.seed,size:40,provider:e.provider}),v&&(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:v.alias}),(0,r.jsx)("span",{children:`${tQ(e.provider)} \xb7 ${b}`})]})}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:y.map(({block:e,originalIndex:i})=>(0,r.jsx)(n3,{block:e,toolResults:n,isStreaming:t,streamingDuration:F.get(i)??("thinking"===e.type?_:void 0),toolCallDurations:B,cwd:a,onOpenFile:o,sessionId:c,entryId:u,blockIndex:i},`${u??"stream"}-${i}`))}),k&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(w.length>0),padding:"7px 10px",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",background:"var(--danger-soft)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",k]}),p&&p.length>0&&(0,r.jsx)(nN,{files:p,onOpenFile:o}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[e.usage&&!t&&(0,r.jsx)("button",{type:"button",onClick:()=>N(e=>!e),onFocus:()=>S(!0),onBlur:()=>S(!1),"aria-expanded":T,title:f("i18n.messageUsageTitle"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:T?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:j||T?1:0,pointerEvents:j||T?"auto":"none",transition:"opacity 0.12s, color 0.12s"},children:T?(h=e.usage,m=[],h.input&&m.push(`${h.input.toLocaleString()} in`),h.output&&m.push(`${h.output.toLocaleString()} out`),h.cacheRead&&m.push(`${h.cacheRead.toLocaleString()} cache R`),h.cacheWrite&&m.push(`${h.cacheWrite.toLocaleString()} cache W`),h.cost?.total&&m.push(`$${h.cost.total.toFixed(4)}`),m.join(" \xb7 ")):f("i18n.messageUsage")}),t&&Math.round(P)>0&&(0,r.jsx)("button",{type:"button",onClick:()=>N(e=>!e),"aria-expanded":T,title:f("i18n.estimatedTokens"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:T?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:T?`~${Math.round(P)}${null!==R?` \xb7 ${R.toFixed(1)} t/s`:""}`:f("i18n.messageUsage")}),O&&!t&&(0,r.jsxs)("button",{onClick:()=>{tI(O).then(()=>{I(!0),setTimeout(()=>I(!1),1500)})},title:f("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:C?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!j,pointerEvents:j?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{C||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{C||(e.currentTarget.style.color="var(--text-dim)")},children:[C?(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"})]}),f(C?"i18n.copied":"i18n.copy")]}),x&&!t&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto"},children:x})]})]}):null}function n3({block:e,toolResults:t,isStreaming:n,streamingDuration:i,toolCallDurations:s,cwd:a,onOpenFile:o,sessionId:l,entryId:d,blockIndex:c}){if("text"===e.type)return(0,r.jsx)(rt,{block:e,isStreaming:n,cwd:a,onOpenFile:o});if("thinking"===e.type)return(0,r.jsx)(rn,{block:e,duration:i,sessionId:l,entryId:d,blockIndex:c});if("toolCall"===e.type){let n=t?.get(e.toolCallId),i=s?.get(e.toolCallId);return(0,r.jsx)(rr,{block:e,result:n,duration:i})}if("image"===e.type)return"image"===e.type&&"toolImage"in e?l?(0,r.jsx)(n9,{sessionId:l,toolCallId:e.toolImage.toolCallId}):null:(0,r.jsx)(n7,{block:e});return null}function n7({block:e}){let t=rk(e);return t?(0,r.jsx)("img",{src:t,alt:"",style:{maxWidth:"100%",maxHeight:420,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}}):null}function n9({sessionId:e,toolCallId:t}){let{t:n}=(0,E.s)(),[s,a]=(0,i.useState)(()=>eA.get(`${e}
11
+ ${t}`)),[o,l]=(0,i.useState)(null),[d,c]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{if(void 0!==s)return;let n=!0;return(function(e,t){let n=`${e}
12
+ ${t}`,r=eA.get(n);if(void 0!==r)return Promise.resolve(r);let i=eP.get(n);if(i)return i;let s=fetch(e$(e,t),{cache:"no-store"}).then(async e=>{if(!e.ok)return 0;let t=await e.json(),r=Number.isSafeInteger(t.count)&&t.count>=0?t.count:0;return eA.set(n,r),r}).catch(()=>0).finally(()=>eP.delete(n));return eP.set(n,s),s})(e,t).then(e=>{n&&a(e)}),()=>{n=!1}},[s,e,t]),!s)return null;let u=Array.from({length:s},(e,t)=>t).filter(e=>!d.has(e));return 0===u.length?null:(0,r.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":t,children:[u.map(i=>(0,r.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":n("i18n.zoomIn"),onClick:()=>l(i),children:(0,r.jsx)("img",{src:e$(e,t,i),alt:"",loading:"lazy",draggable:!1,onError:()=>c(e=>new Set(e).add(i))})},i)),null!==o&&(0,r.jsx)(re,{src:e$(e,t,o),onClose:()=>l(null)})]})}function re({src:e,onClose:t}){let{t:n}=(0,E.s)(),s=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=s.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,F.createPortal)((0,r.jsxs)("dialog",{ref:s,className:"tool-image-dialog",onCancel:e=>{e.preventDefault(),t()},onClick:e=>{e.target===e.currentTarget&&t()},children:[(0,r.jsx)("img",{className:"tool-image-full",src:e,alt:"",draggable:!1}),(0,r.jsx)("button",{type:"button",className:"tool-image-close",onClick:t,children:n("i18n.close")})]}),document.body)}function rt({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(n2,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function rn({block:e,duration:t,sessionId:n,entryId:s,blockIndex:a}){let{t:o}=(0,E.s)(),[l,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0===e.deferred),[p,h]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!e.deferred){d(null),u(!1),h(null);return}let t=!1;return n&&s?(u(!0),h(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=n1.get(r);if(i)return n1.delete(r),n1.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 n1.delete(r),e});if(n1.set(r,s),n1.size>100){let e=n1.keys().next().value;e&&n1.delete(e)}return s})(n,s,a).then(e=>{t||d(e)}).catch(e=>{t||h(e instanceof Error?e.message:String(e))}).finally(()=>{t||u(!1)}),()=>{t=!0}):(u(!1),h(o("i18n.thinkingUnavailable")),()=>{t=!0})},[e.deferred,e.thinking,a,s,n,o]);let m=e.deferred?l:e.thinking,f="string"==typeof m&&m.trim().length>0;return(0,r.jsxs)("div",{className:"markdown-thinking","aria-label":o("i18n.thinking"),children:[(0,r.jsx)("div",{className:"markdown-thinking-content",children:c?(0,r.jsx)("span",{className:"markdown-thinking-status",children:o("i18n.loadingThinking")}):p?(0,r.jsx)("span",{className:"markdown-thinking-error",children:p}):f?(0,r.jsx)(tR,{className:"markdown-thinking-body",children:m}):(0,r.jsx)("span",{className:"markdown-thinking-status",children:o("chat.thinking")})}),void 0!==t&&f&&(0,r.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function rr({block:e,result:t,duration:n}){let s,a=e.toolName.toLowerCase(),o="edit"===a||a.startsWith("edit_")||a.endsWith(".edit")||a.endsWith("_edit")||a.includes("str_replace")||a.includes("replace_editor"),[l,d]=(0,i.useState)(o),c=JSON.stringify(e.input,null,2),u="todo"===a||a.endsWith(".todo")||a.endsWith("_todo"),p="bash"===a||a.startsWith("bash ")||a.endsWith(".bash")||a.endsWith("_bash"),h=t&&!t.isError?function(e){let t=e.details;if(!rf(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}(t):null,m=u?"unknown"===(s=eq(e,t)).kind||0===s.phases.length?null:s.phases:null,f=h?h.text.split(/\r?\n/).reduce((e,t)=>(t.startsWith("+")&&!t.startsWith("+++")&&(e.added+=1),t.startsWith("-")&&!t.startsWith("---")&&(e.removed+=1),e),{added:0,removed:0}):null,g=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,x=null!==g&&("(no output)"===g.trim()||""===g.trim()),v=t?.isError??!1;if(p)return(0,r.jsx)(rd,{command:rf(e.input)&&"string"==typeof e.input.command?e.input.command:"",output:g??"",pending:!t,isError:v,duration:n,local:a.includes("(local)")});if(u&&m)return(0,r.jsx)(rl,{phases:m});let b=!!(m||h),y=function(e,t){if(t){let e=t.flatMap(e=>e.tasks),n=e.filter(e=>"completed"===e.status||"abandoned"===e.status).length;return`${n}/${e.length} tasks`}return function(e){var t;let n=e.input;if(!n||"object"!=typeof n)return"";let r=Object.keys(n);if(0===r.length)return"";let i=e.toolName.toLowerCase();if(t=i,["grep","read","write","glob"].some(e=>t===e||t.endsWith(`.${e}`)||t.endsWith(`_${e}`))&&"string"==typeof n.i){let e=n.i.trim();if(e)return e.slice(0,120)}if(("eval"===i||i.endsWith(".eval")||i.endsWith("_eval"))&&"string"==typeof n.title){let e=n.title.trim();if(e)return e.slice(0,120)}if("command"in n)return String(n.command).slice(0,120);if("path"in n)return String(n.path).slice(0,120);if("file_path"in n)return String(n.file_path).slice(0,120);if("pattern"in n)return String(n.pattern).slice(0,120);if("query"in n)return String(n.query).slice(0,120);let s=r.map(e=>n[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==s)return String(s).slice(0,120);try{return JSON.stringify(n).slice(0,120)}catch{return r.join(", ").slice(0,120)}}(e)}(e,m);return(0,r.jsxs)("div",{className:`tool-call-card${v?" is-error":" is-success"}`,style:{borderRadius:7,overflow:"hidden",fontSize:12,border:v?"1px solid var(--danger-line)":"1px solid var(--success-line)",background:v?"var(--danger-soft)":"var(--success-soft)"},children:[(0,r.jsxs)("button",{className:"tool-call-header",onClick:()=>d(e=>!e),"aria-expanded":l,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",minWidth:0},children:[(0,r.jsx)(ra,{toolName:e.toolName,isError:v}),(0,r.jsx)("span",{className:"tool-call-name",style:{color:v?"var(--danger)":"var(--success)",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:e.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:y}),f&&(0,r.jsxs)("span",{title:`${f.added} lines added, ${f.removed} lines removed`,"aria-label":`${f.added} lines added, ${f.removed} lines removed`,style:{display:"inline-flex",alignItems:"center",gap:6,flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,fontVariantNumeric:"tabular-nums"},children:[(0,r.jsxs)("span",{style:{color:"var(--success)"},children:["+",f.added]}),(0,r.jsxs)("span",{style:{color:"var(--danger)"},children:["−",f.removed]})]}),void 0!==n&&(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:[n,"s"]}),(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:l?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),h&&(0,r.jsx)("div",{style:{maxHeight:l?560:260,overflowY:"auto",overflowX:"hidden",borderTop:"1px solid var(--success-line)"},children:(0,r.jsx)(rc,{diff:h})}),t&&v&&(0,r.jsx)(rg,{text:g??"",isEmpty:x,isError:!0}),l&&!b&&(0,r.jsx)("pre",{className:"tool-call-input",style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",background:"var(--bg-subtle)",borderTop:v?"1px solid var(--danger-line)":"1px solid var(--success-line)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:c}),l&&t&&!b&&!v&&(0,r.jsx)(rg,{text:g??"",isEmpty:x,isError:!1})]})}let ri={read:"var(--accent)",write:"var(--warning)",glob:"var(--accent-hover)",grep:"var(--accent)",edit:"var(--warning)",bash:"var(--success)",todo:"var(--warning)",eval:"var(--accent-hover)",task:"var(--accent)",browser:"var(--accent-hover)",image:"var(--success)",generic:"var(--text-dim)"};function rs(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function ra({toolName:e,isError:t}){let n,i=(n=e.trim().toLowerCase()).includes("str_replace")||n.includes("replace_editor")||rs(n,"edit")?"edit":rs(n,"read")||rs(n,"cat")?"read":rs(n,"write")||rs(n,"save")?"write":rs(n,"glob")||rs(n,"find")?"glob":rs(n,"grep")||rs(n,"search")?"grep":rs(n,"bash")||rs(n,"shell")||rs(n,"exec")?"bash":rs(n,"todo")?"todo":rs(n,"eval")?"eval":rs(n,"task")||rs(n,"agent")?"task":rs(n,"browser")||rs(n,"web_search")||rs(n,"fetch")?"browser":rs(n,"image")||rs(n,"inspect_image")?"image":"generic",s=t?"var(--danger)":ri[i];return(0,r.jsx)("span",{"aria-hidden":"true","data-tool-icon":i,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:s},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.15",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)(ro,{kind:i})})})}function ro({kind:e}){switch(e){case"read":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"M4.2 9.1c1.1-1.4 3.6-1.4 4.7 0-1.1 1.4-3.6 1.4-4.7 0Z"}),(0,r.jsx)("circle",{cx:"6.55",cy:"9.1",r:"0.7",fill:"currentColor",stroke:"none"})]});case"write":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"M6.55 6.25v4.15m-1.7-1.55 1.7 1.7 1.7-1.7"})]});case"glob":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M1.75 4.5A1.25 1.25 0 0 1 3 3.25h2.25l1.35 1.35h4.4A1.25 1.25 0 0 1 12.25 5.85v5.1A1.25 1.25 0 0 1 11 12.2H3a1.25 1.25 0 0 1-1.25-1.25V4.5Z"}),(0,r.jsx)("path",{d:"M9 7.1v3.8M7.1 9h3.8M7.65 7.65l2.7 2.7m0-2.7-2.7 2.7"})]});case"grep":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"5.9",cy:"5.9",r:"3.25"}),(0,r.jsx)("path",{d:"m8.35 8.35 3.25 3.25"}),(0,r.jsx)("path",{d:"M4.6 5.2h2.5M4.6 6.8h1.7"})]});case"edit":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"m4.45 10.55 4.75-4.75 1.45 1.45-4.75 4.75-1.95.5.5-1.95Z"}),(0,r.jsx)("path",{d:"m8.45 6.55 1.45 1.45"})]});case"bash":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.5",y:"2.1",width:"11",height:"9.8",rx:"1.3"}),(0,r.jsx)("path",{d:"m4 5.2 1.8 1.8L4 8.8M7.2 8.8h2.3"})]});case"todo":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7"}),(0,r.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9"})]});case"eval":return(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"m5 2.5-3 4.5 3 4.5M9 2.5l3 4.5-3 4.5M7.8 2 6.2 12"})});case"task":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"3.1",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"10.8",r:"1.25"}),(0,r.jsx)("path",{d:"M4.35 3.2h2.1a2.9 2.9 0 0 1 2.9 2.9v3.45"}),(0,r.jsx)("path",{d:"M9.35 3.2h-1.1"})]});case"browser":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"5.2"}),(0,r.jsx)("path",{d:"M1.9 7h10.2M7 1.8c1.45 1.4 2.2 3.15 2.2 5.2S8.45 10.8 7 12.2C5.55 10.8 4.8 9.05 4.8 7S5.55 3.2 7 1.8Z"})]});case"image":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2.25",width:"10.5",height:"9.5",rx:"1.15"}),(0,r.jsx)("circle",{cx:"4.8",cy:"5.1",r:"1"}),(0,r.jsx)("path",{d:"m2.6 10 2.6-2.7 1.8 1.8 1.45-1.45 2.95 2.95"})]});case"generic":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2",width:"10.5",height:"10",rx:"1.3"}),(0,r.jsx)("path",{d:"M4.35 5h5.3M4.35 7.35h3.8M4.35 9.7h4.6"})]})}}function rl({phases:e}){let t=e.reduce((e,t)=>e+t.tasks.length,0),n=e.reduce((e,t)=>e+t.tasks.filter(e=>"completed"===e.status).length,0);return(0,r.jsxs)("div",{className:"todo-checklist-preview",role:"list","aria-label":`Todo ${t} tasks`,children:[(0,r.jsxs)("div",{className:"todo-checklist-header",children:[(0,r.jsxs)("svg",{className:"todo-checklist-icon",width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),(0,r.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),(0,r.jsx)("span",{className:"todo-checklist-title",children:"Todo"}),(0,r.jsxs)("span",{className:"todo-checklist-count",children:[t," ",1===t?"task":"tasks"]}),n>0&&n<t&&(0,r.jsxs)("span",{className:"todo-checklist-progress",children:[n,"/",t]})]}),(0,r.jsx)("div",{className:"todo-checklist-body",children:e.map((t,n)=>(0,r.jsxs)("div",{className:"todo-checklist-phase",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),t.tasks.map((e,t)=>(0,r.jsx)(nw,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function rd({command:e,output:t,pending:n,isError:i,duration:s,local:a}){let{isDark:o}=tC(),{t:l}=(0,E.s)(),d=eb(t.split(/\r?\n/)),c=1===d.length&&""===d[0]?[]:d,u=n?l("chat.runningCommand"):i?"failed":"";return(0,r.jsxs)("div",{className:`shell-output-preview${i?" is-error":""}`,children:[(0,r.jsxs)("div",{className:"shell-command-line",children:[(0,r.jsx)("span",{className:"shell-command-prompt","aria-hidden":"true",children:"$"}),(0,r.jsx)(eV.A,{className:"shell-command-code",language:"bash",style:o?eK.xJ:eK.vs,PreTag:"span",CodeTag:"span",wrapLongLines:!0,customStyle:{flex:1,minWidth:0,margin:0,padding:0,border:"none",overflow:"visible",background:"transparent",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e||" "}),a&&(0,r.jsx)("span",{className:"shell-local-label",children:"local"})]}),(0,r.jsxs)("div",{className:"shell-output-panel",children:[(0,r.jsxs)("div",{className:"shell-output-divider",children:[(0,r.jsx)("span",{className:"shell-output-label",children:"Output"}),u&&(0,r.jsx)("span",{className:`shell-output-status${i?" is-error":n?" is-pending":""}`,children:u})]}),(0,r.jsxs)("div",{className:"shell-output-body","aria-live":n?"polite":void 0,children:[0===c.length&&!n&&(0,r.jsx)("span",{className:"shell-output-empty",children:l("i18n.noOutput")}),c.map((e,t)=>{let n=ef(e).trimStart(),s=i||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(n)?"is-error":/^(?:warning|warn|!)/i.test(n)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(n)?"is-success":"";return(0,r.jsxs)("div",{className:`shell-output-line ${s}`.trim(),children:[ey(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},t):(0,r.jsx)("span",{children:e.text},t)),""===e?"\xa0":null]},t)}),n&&(0,r.jsx)("span",{className:"shell-output-pending","aria-label":l("chat.runningCommand"),children:"▋"})]})]}),void 0!==s&&(0,r.jsxs)("div",{className:"shell-output-footer",children:[s,"s"]})]})}function rc({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,r.jsx)(ru,{text:e.text})})}function ru({text:e}){let{t}=(0,E.s)(),n=(0,i.useMemo)(()=>nb(e),[e]);if(!n)return(0,r.jsx)(rm,{text:e});let s=n.length>1;return(0,r.jsx)("div",{style:{background:"var(--bg)"},children:n.map((e,n)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===n?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[s&&(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)(rp,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(rp,{title:e.newPath||t("i18n.after"),side:"right"})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(rh,{cell:e.left,side:"left"}),(0,r.jsx)(rh,{cell:e.right,side:"right"})]},t))})]},n))})}function rp({title:e,side:t}){return(0,r.jsx)("div",{title:e,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===t?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function rh({cell:e,side:t}){let n="added"===e.type?"var(--success-soft)":"removed"===e.type?"var(--danger-soft)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"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:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:s,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function rm({text:e}){let t=e.split(/\r?\n/);return(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:0},children:t.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?"var(--success-soft)":"removed"===n?"var(--danger-soft)":"hunk"===n?"var(--accent-soft)":"transparent",borderLeft:"added"===n?"3px solid var(--success)":"removed"===n?"3px solid var(--danger)":"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?"var(--success)":"removed"===n?"var(--danger)":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function rf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rg({text:e,isEmpty:t,isError:n}){let{t:i}=(0,E.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${n?"var(--danger-line)":"var(--success-line)"}`,background:n?"var(--danger-soft)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:n?"var(--danger)":t?"var(--text-dim)":"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:t?"italic":"normal",opacity:t?.6:1},children:t?i("i18n.noOutput"):e})})}function rx({message:e}){let{t}=(0,E.s)(),n=rw(e.content),s=(0,i.useMemo)(()=>{let e,t,r,i,s;return e=[],t=[],r=n.match(t$),i=r?.[1]??"",s=r?.index===void 0?n:n.slice(0,r.index),i.replace(tE,(n,r,i)=>{let s=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...s):t.push(...s),""}),{body:s.trim(),readFiles:e,modifiedFiles:t}},[n]),a=n8(e.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.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.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),s.body?(0,r.jsx)(tR,{className:"markdown-compaction-message",children:s.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(rv,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})]})})}function rv({readFiles:e,modifiedFiles:t}){let{t:n}=(0,E.s)();if(0===e.length+t.length)return null;let i=[];return e.length>0&&i.push(`${e.length} read`),t.length>0&&i.push(`${t.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:n("i18n.fileContext",{details:i.join(", ")})}),t.length>0&&(0,r.jsx)(rb,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(rb,{title:n("i18n.readFiles"),files:e})]})}function rb({title:e,files:t}){return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:e}),(0,r.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function ry({message:e,cwd:t,onOpenFile:n}){var s;let a,{t:o}=(0,E.s)(),l=!1===e.display,[d,c]=(0,i.useState)(!l),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1),f=rw(e.content),g="string"==typeof(s=e.content)?[]:s.filter(e=>"image"===e.type),x=void 0!==e.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",b=e.customType||"extension",y=n8(e.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:l?"var(--bg-subtle)":"var(--bg)",opacity:l&&!d?.82:1},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)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:b}),l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:o("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),d?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!f},children:g.map((e,t)=>{let n=rk(e);return n?(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t):null})}),f?(0,r.jsx)(tR,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:f}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:o("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>c(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?(a=f.replace(/\s+/g," ").trim())?a.length>140?`${a.slice(0,140)}...`:a:"Show extension message":o("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[f||v?(0,r.jsx)("button",{onClick:()=>{tI(f||v).then(()=>{m(!0),setTimeout(()=>m(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(h?"i18n.copied":"i18n.copy")}):null,(x||l)&&(0,r.jsx)("button",{onClick:()=>{l?c(e=>!e):p(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(l?d?"i18n.collapse":"i18n.expand":u?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(l&&d||!l&&u)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:v})]})})}function rw(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function rk(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}`:""}function rj({message:e,sessionId:t}){let[n,s]=(0,i.useState)(null),[a,o]=(0,i.useState)(!1),[l,d]=(0,i.useState)(null),c=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,p=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,h=e.truncated&&p&&null===n,m=n??e.output;async function f(){if(p){o(!0),d(null);try{let e=await fetch(p),t=await e.json();t.success?s(t.data?.output??""):d(t.error??"failed")}catch(e){d(String(e))}finally{o(!1)}}}let g=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:g,input:{command:e.command}},v=c?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:g,content:m?[{type:"text",text:m}]:[],isError:u,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(rr,{block:x,result:v}),e.truncated&&p&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,r.jsx)("button",{onClick:f,disabled:a,style:{background:"none",border:"none",color:"var(--accent)",cursor:a?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:a?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${p}&download=1`,style:{marginLeft:10*!!h,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),l&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",l,")"]})]})]})}var rS=n(39092),rC=n.n(rS);let rI=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","NOVA(노바)","SHION(시온)","HIKARI(히카리)"],rT={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","NOVA(노바)":"nova","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},rN=["approval","choice","done","failed","blocked","working"],rM={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},rR={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0};function rE(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function r$(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(rM,e)?e:null}function rL(e,t){let n=new Map,r=new Map;if(!Array.isArray(e))return{files:n,lines:r};for(let i of e){if("object"!=typeof i||null===i)continue;let{file:e,tag:s,ko:a}=i;if("string"!=typeof e||""===e)continue;let o=r$(s);if(null===o)continue;let l=t+e.replace(/^\/+/,""),d=n.get(o);d?d.push(l):n.set(o,[l]),"string"==typeof a&&""!==a.trim()&&r.set(l,a.trim())}return{files:n,lines:r}}function rA(e,t,n){if(!t||!Object.hasOwn(rT,t))return null;let r=rT[t];return e.get(r)?.get(n)??null}async function rP(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return function(e){let t=new Map;if("object"!=typeof e||null===e)return t;let{characters:n}=e;if(!Array.isArray(n))return t;for(let e of n){if("object"!=typeof e||null===e)continue;let{id:n,clips:r,stickers:i,captions:s}=e;if("string"!=typeof n||""===n)continue;let a=rL(r,"/audio/completion/"),o=rL(i,"/stickers/"),l=function(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){if("object"!=typeof n||null===n)continue;let{tag:e,ko:r}=n;if("string"!=typeof r||""===r.trim())continue;let i=r$(e);if(null===i)continue;let s=t.get(i);s?s.push(r.trim()):t.set(i,[r.trim()])}return t}(s),d=new Map;for(let e of rN){let t=a.files.get(e)??[],n=new Map;for(let e of t){let t=a.lines.get(e);void 0!==t&&n.set(e,t)}d.set(e,{voices:t,stickers:o.files.get(e)??[],lines:n,captions:l.get(e)??[]})}t.set(n,d)}return t}(await t.json())}catch{return new Map}}function rz(e,t,n=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let r=null===t?-1:e.indexOf(t),i=-1===r?e.length:e.length-1,s=Math.min(i-1,Math.max(0,Math.floor(n()*i)));return e[-1!==r&&s>=r?s+1:s]}function rW(e){let t=[];if("bashExecution"!==e.role){if("string"==typeof e.content)t.push(e.content.trim());else for(let n of e.content)if("text"===n.type)t.push(n.text.trim());else if("toolCall"===n.type){let e="id"in n&&"string"==typeof n.id?n.id:"";t.push(`toolCall:${n.toolCallId||e}`)}}let n="toolResult"===e.role?e.toolCallId:"custom"===e.role?e.customType:"bashExecution"===e.role?e.command:null;return JSON.stringify([e.role,n,t.filter(Boolean)])}let rF=["01","02","03"];function rD(e,t,n){if(!e||"streaming"===t||!rI.includes(e))return null;let r="failed"===t?"failed":"done",i=e.slice(0,e.indexOf("(")).toLowerCase(),s=rz(rF.map(e=>`/stickers/${i}/${r}/${e}.webp`),null,()=>(function(e){let t=0x811c9dc5;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),0x1000193);return(t>>>0)/0x100000000})(n));return s?{src:s,alt:rM[r]}:null}let r_=new Map,rB=(0,i.createContext)(r_);function rO({utterances:e,children:t}){return(0,r.jsx)(rB.Provider,{value:e,children:t})}function rH({turnIndex:e,turnEntryId:t,sessionId:n,cwd:s,onOpenFile:a}){let o=(0,i.useContext)(rB).get(e);return o&&0!==o.length?(0,r.jsx)("div",{className:"inline-utterance-thread","data-turn":e,"data-turn-entry":t,style:{display:"contents"},children:o.map(e=>(0,r.jsx)(rU,{utterance:e,sessionId:n,cwd:s,onOpenFile:a},e.key))}):null}function rU({utterance:e,sessionId:t,cwd:n,onOpenFile:s}){let a=ng(null===e.accountSessionId?void 0:e.accountSessionId??t,e.provider,e.credentialId),[o,l]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=u.current;e&&!o&&c(e.scrollHeight>e.clientHeight+1)},[e.text,o]);let p=e.text.trim().length>0,h=e.label?.trim(),m=a?.alias??h??tQ(e.provider),f=a?.alias.split("(",1)[0]?.trim(),g=a&&h&&h!==a.alias&&h!==f?`작업 \xb7 ${h}`:null,x=rD(a?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&p?"작업 중":null;return(0,r.jsxs)("div",{className:"inline-utterance","data-status":e.status,style:{marginBottom:16},children:[(0,r.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...a?{minHeight:40}:null},children:[a&&(0,r.jsx)(nx,{seed:a.seed,size:40,provider:e.provider}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:m}),v&&(0,r.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),g&&(0,r.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:g})]})]}),p?(0,r.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...o?null:{maxHeight:240,overflow:"hidden"}},children:(0,r.jsx)(tR,{isStreaming:"streaming"===e.status,cwd:n,onOpenFile:s,children:e.text})}):(0,r.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(d||o)&&(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>!e),"aria-expanded":o,style:{marginTop:4,padding:"3px 9px",height:22,border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:o?"접기":"더보기"}),x&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("img",{src:x.src,alt:x.alt,style:{display:"block",width:"min(148px, 34vw)",maxWidth:"100%",height:"auto"},className:"jsx-8e1a78d1ba768be9 inline-utterance-sticker"}),(0,r.jsx)(rC(),{id:"8e1a78d1ba768be9",children:".inline-utterance-sticker{transform-origin:center 75%;animation:inline-utterance-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes inline-utterance-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.inline-utterance-sticker{animation:none}}"})]})]})}let rq=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function rV(e,t,n,r){if("string"!=typeof n)return[];let i=rq.exec(n),s=i?.[1],a=i?.[2];return s&&a?[{toolCallId:e,...t?{name:t}:{},alias:s,model:a,batchSize:r}]:[]}function rK(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[]){if("toolCall"!==n.type||"task"!==n.toolName)continue;let e=n.input,r=+(void 0!==e.task)+(Array.isArray(e.tasks)?e.tasks.length:0);if(t.push(...rV(n.toolCallId,"string"==typeof e.name?e.name:void 0,e.task,r)),Array.isArray(e.tasks))for(let i of e.tasks)!i||"object"!=typeof i||Array.isArray(i)||t.push(...rV(n.toolCallId,"name"in i&&"string"==typeof i.name?i.name:void 0,"task"in i?i.task:void 0,r))}return t}function rJ(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[])"toolCall"===n.type&&"task"===n.toolName&&t.push(n.toolCallId);return t}let rG=/^agent:\/\/([^/?#]+)\/?$/i;function rY(e,t){if(!e||"assistant"!==e.role)return[];let n=[];for(let r of e.content??[]){if("toolCall"!==r.type||"write"!==r.toolName)continue;let e=r.input,i="string"==typeof e.path?rG.exec(e.path):null,s=i?.[1],a=e.content;if(!s||"string"!=typeof a)continue;let o=t?.get(r.toolCallId);n.push({toolCallId:r.toolCallId,to:s,message:a,...o?.from?{from:o.from}:{},...o?.receipts?{receipts:o.receipts}:{}})}return n}let rZ=/^[\t ]*(?:WORK_CLASS|PURPOSE|BLOCKS_PRIMARY|PRIMARY_DELIVERABLE|OWNED_PATHS|FINDING_ID)[\t ]*:[^\r\n]*$/i;function rX(e){if(!e)return null;let t=/^\s*TASK_GUARD\s*:\s*$/im.exec(e),n=e;if(t){let r=t.index+t[0].length;"\r"===e[r]&&(r+=1),"\n"===e[r]&&(r+=1);let i=r;for(;r<e.length;){let t=e.indexOf("\n",r),n=-1===t?e.length:t,s=n>r&&"\r"===e[n-1]?n-1:n;if(!rZ.test(e.slice(r,s)))break;i=s,r=-1===t?e.length:t+1}let s=t[0].length-t[0].trimStart().length;n=`${e.slice(0,t.index+s)}${e.slice(i)}`}let r=[...n.matchAll(/^\s*TASK_TITLE\s*:\s*(.*?)\s*$/gim)].map(e=>e[1]??"");return 1===r.length&&r[0]&&r[0]===r[0].trim()&&/[가-힣]/u.test(r[0])?r[0]:null}class rQ extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SubagentClientError"}}async function r0(e){try{return await e.json()}catch{throw new rQ("invalid-response","응답 JSON을 해석할 수 없습니다.",e.status)}}function r1(e){return!!e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.bytes&&"number"==typeof e.modified&&(null===e.messages||"number"==typeof e.messages)&&(void 0===e.taskTitle||"string"==typeof e.taskTitle)&&"string"==typeof e.firstTask}function r2(e){return!!e&&"object"==typeof e&&"string"==typeof e.role&&("message"===e.kind||"custom"===e.kind)&&"string"==typeof e.text&&(null===e.at||"number"==typeof e.at)}function r8(e){return!!e&&"object"==typeof e&&!!("id"in e&&"string"==typeof e.id)&&!!("index"in e&&"number"==typeof e.index)&&!!("agent"in e&&"string"==typeof e.agent)&&!!("agentSource"in e&&("bundled"===e.agentSource||"user"===e.agentSource||"project"===e.agentSource))&&!!("status"in e&&("pending"===e.status||"running"===e.status||"completed"===e.status||"failed"===e.status||"aborted"===e.status||"unknown"===e.status))&&!!("lastUpdate"in e&&"number"==typeof e.lastUpdate)&&!0}function r4(e){return!!e&&"object"==typeof e&&(!("id"in e)||void 0===e.id||"string"==typeof e.id)&&(!("type"in e)||void 0===e.type||"string"==typeof e.type)&&(!("message"in e)||void 0===e.message||null!==e.message&&"object"==typeof e.message)}function r5(e=(e,t)=>fetch(e,t),t="/api/sidecars/subagent"){let n=async(t,n,r)=>{let i;try{i=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new rQ(r,"sidecar-unreachable"===r?"Subagent 기록 사이드카(30144)에 연결할 수 없습니다.":"실시간 Subagent 상태에 연결할 수 없습니다.")}let s=await r0(i);if(!i.ok)throw new rQ("http",function(e,t){if(e&&"object"==typeof e&&"error"in e){let t=e.error;if("string"==typeof t&&t)return t}return t}(s,`HTTP ${i.status}`),i.status);return{response:i,body:s}};return{async getLiveSnapshots(e,t){let{body:r}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"GET",signal:t},"live-unreachable");if(!r||"object"!=typeof r)throw new rQ("invalid-response","실시간 Subagent 응답이 올바르지 않습니다.");if("string"==typeof r.error&&r.error)throw new rQ("http",r.error);if(!0!==r.running)return{runtime:"detached",subagents:[]};let i=r.state?.subagents;if(void 0!==i&&(!Array.isArray(i)||!i.every(r8)))throw new rQ("invalid-response","실시간 Subagent 목록이 올바르지 않습니다.");return{runtime:"running",subagents:i??[]}},async getLiveTranscript(e,t,r,i){let{body:s}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"get_subagent_messages",subagentId:t,fromByte:r}),signal:i},"live-unreachable");if(!s||"object"!=typeof s)throw new rQ("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");if("string"==typeof s.error&&s.error)throw new rQ("http",s.error);if(!0!==s.success||!s.data||"object"!=typeof s.data)throw new rQ("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");let a=s.data;if(!Array.isArray(a.entries)||!a.entries.every(r4)||"number"!=typeof a.fromByte||"number"!=typeof a.nextByte||"boolean"!=typeof a.reset)throw new rQ("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");return{fromByte:a.fromByte,nextByte:a.nextByte,reset:a.reset,entries:a.entries}},async getArchive(e,r){let i=`${t}/archive?session=${encodeURIComponent(e)}`,{body:s}=await n(i,{method:"GET",signal:r},"sidecar-unreachable");if(!s||"object"!=typeof s||"string"!=typeof s.sessionId||"string"!=typeof s.dir||"boolean"!=typeof s.found||!Array.isArray(s.subagents)||!s.subagents.every(r1))throw new rQ("invalid-response","Subagent 기록 목록 응답이 올바르지 않습니다.");return{sessionId:s.sessionId,dir:s.dir,found:s.found,subagents:s.subagents,...!0===s.listTruncated?{listTruncated:!0}:{}}},async getArchiveTranscript(e,r,i=400,s){let a=`${t}/transcript?session=${encodeURIComponent(e)}&name=${encodeURIComponent(r)}&limit=${encodeURIComponent(String(i))}`,{body:o}=await n(a,{method:"GET",signal:s},"sidecar-unreachable");if(!o||"object"!=typeof o||"string"!=typeof o.sessionId||"string"!=typeof o.name||"number"!=typeof o.bytes||"boolean"!=typeof o.truncated||!Array.isArray(o.entries)||!o.entries.every(r2))throw new rQ("invalid-response","Subagent 디스크 기록 응답이 올바르지 않습니다.");return{sessionId:o.sessionId,name:o.name,bytes:o.bytes,truncated:o.truncated,entries:o.entries}}}}function r6(e){if("assistant"!==e.role)return e;let t=e.content;if(!Array.isArray(t))return e;let n=t.map(e=>("object"!=typeof e||null===e||Array.isArray(e)||"toolCall"!==e.type?null:{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})??e);return{...e,content:n}}function r3(e){return"pending"===e||"running"===e}let r7=new Map;function r9(e){return`${e.liveId??""}|${e.status??""}|${e.archiveName??""}`}function ie(e){return e instanceof rQ&&("live-unreachable"===e.kind||"sidecar-unreachable"===e.kind)?{kind:"unreachable",message:e.message}:{kind:"error",message:e instanceof Error?e.message:String(e)}}function it(e,{sessionId:t,client:n,enabled:r}){let[s,a]=(0,i.useState)(r7),o=(0,i.useRef)(new Map),l=(0,i.useRef)(e);l.current=e;let d=(0,i.useCallback)(()=>{let e=o.current;a(t=>{let n=!1,r=new Map;for(let[i,s]of e){let e=t.get(i),a=e&&e.entries===s.collected&&e.state===s.state?e:{state:s.state,entries:s.collected};a!==e&&(n=!0),r.set(i,a)}return r.size!==t.size&&(n=!0),n?r:t})},[]),c=e.map(e=>`${e.key}|${r9(e)}`).join("\n");return(0,i.useEffect)(()=>{if(!r)return;let e=!1,i=!1,s=null,a=o.current,c=new Set(l.current.map(e=>e.key));for(let e of[...a.keys()])c.has(e)||a.delete(e);for(let e of l.current){let t=r9(e);a.get(e.key)?.signature!==t&&a.set(e.key,{signature:t,nextByte:0,collected:[],state:{kind:"loading"}})}d();let u=async(r,i,s,a)=>{if(!r.archiveName){i.state={kind:"empty",source:"live",note:a};return}try{let o=await n.getArchiveTranscript(t,r.archiveName,400,s);if(e)return;0===i.collected.length&&(i.collected=o.entries.flatMap((e,t)=>{let n=`archive:${t}`;return e.message&&"assistant"===e.message.role?[{id:n,message:e.message}]:e.irc?[{id:n,irc:{from:e.irc.from||void 0,message:e.irc.message||void 0,truncated:!0===e.irc.truncated}}]:[]})),i.state=0===o.entries.length?{kind:"empty",source:"archive",note:a}:{kind:"ready-archive",entries:o.entries,truncated:o.truncated,note:a}}catch(n){if(e||s.aborted)return;let t=ie(n);i.state="unreachable"===t.kind?{kind:"unreachable",message:t.message}:{kind:"error",message:t.message}}},p=async(r,i)=>{let s=a.get(r.key);if(s){if(!r.liveId)return void await u(r,s,i);try{var o,l;let a=await n.getLiveTranscript(t,r.liveId,s.nextByte,i);if(e)return;let d=(o=a.entries,l=a.fromByte,o.flatMap((e,t)=>{let n=e.id??`${l}:${t}`;if("message"===e.type&&e.message)return[{id:n,message:r6(e.message)}];if("custom_message"===e.type&&"irc:incoming"===e.customType){let t=e.details;return!t||"object"!=typeof t||Array.isArray(t)?[]:[{id:n,irc:{from:"string"==typeof t.from?t.from:void 0,message:"string"==typeof t.message?t.message:void 0}}]}return[]}));a.reset||0===a.fromByte?s.collected=d:d.length>0&&(s.collected=[...s.collected,...d]),s.nextByte=a.nextByte,s.collected.length>0?("ready-live"!==s.state.kind||s.state.entries!==s.collected)&&(s.state={kind:"ready-live",entries:s.collected}):await u(r,s,i)}catch(t){if(e||i.aborted)return;if(r.archiveName){let e=ie(t);await u(r,s,i,`실시간 기록을 읽지 못해 디스크 기록을 표시합니다: ${e.message}`)}else{let e=ie(t);s.state="unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message}}}}},h=async()=>{if(e||i||"u">typeof document&&"visible"!==document.visibilityState)return;i=!0;let t=new AbortController;s=t;try{for(let e of l.current)await p(e,t.signal)}finally{i=!1}e||d()};h();let m=l.current.some(e=>r3(e.status))?setInterval(()=>void h(),3e3):void 0,f=()=>{"visible"===document.visibilityState&&h()};return document.addEventListener("visibilitychange",f),()=>{e=!0,s?.abort(),clearInterval(m),document.removeEventListener("visibilitychange",f)}},[n,r,d,t,c]),s}let ir=["greeting","utterance","message","text"],ii=function(e){let t=(0,i.useMemo)(()=>r5(),[]),n=function(e,t){let[n,r]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(!t)return void r(null);let n=!1,i=new AbortController;return r(null),e.getArchive(t,i.signal).then(e=>{n||r(e)}).catch(()=>{}),()=>{n=!0,i.abort()}},[e,t]),n}(t,e.sessionId),r=(0,i.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),r=[];if(n&&n.sessionId===e.sessionId){let i=e.turns.flatMap(e=>e.characterSummons);for(let s of n.subagents){if(t.has(s.name))continue;let n=[...i].reverse().find(e=>e.name===s.name);n&&r.push(function(e,t,n){let r=e.status??"unknown",i={id:e.name,index:n,agent:"",agentSource:"bundled",status:r,task:e.firstTask||void 0,lastUpdate:e.modified,parentToolCallId:t.toolCallId},s="string"==typeof e.model&&e.model.trim()?e.model.trim():void 0,a="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==s||void 0!==a)&&(i.progress={index:n,id:e.name,agent:"",status:r,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==s?{resolvedModel:s,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==a?{retryFailure:{attempt:0,errorMessage:a}}:{}}),i}(s,n,e.subagents.length+r.length))}}return function(e,t){let n=new Map;for(let t of e)for(let e of t.characterSummons){let r=n.get(e.toolCallId)??{turnIndex:t.index,requests:[]};r.requests.push(e),n.set(e.toolCallId,r)}return t.flatMap(t=>{let r=t.parentToolCallId?n.get(t.parentToolCallId):void 0;if(!r)return[];let i=r.requests.filter(e=>e.name),s="string"==typeof t.task?rq.exec(t.task):null,a=s?.[1],o=s?.[2],l=i.find(e=>e.name===t.id)??(a&&o?r.requests.find(e=>e.alias===a&&e.model===o):void 0)??(1===r.requests.length&&1===r.requests[0].batchSize?r.requests[0]:void 0);if(!l)return[];let d=e.flatMap(e=>e.peerSends.filter(e=>e.to===t.id||"all"===e.to).map(t=>({turnIndex:e.index,send:t})));return[{snapshot:t,turnIndex:r.turnIndex,summon:l,sends:d}]})}(e.turns,[...e.subagents,...r])},[e.subagents,e.turns,e.sessionId,n]),s=(0,i.useMemo)(()=>r.map(({snapshot:t})=>{let n=t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||t.id;return e.subagents.some(e=>e.id===t.id)?{key:t.id,liveId:t.id,status:t.status,archiveName:n}:{key:t.id,status:t.status,archiveName:n}}),[r,e.subagents]),a=it(s,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&s.length>0});return(0,i.useMemo)(()=>r.flatMap(t=>(function(e,t,n){var r;let{snapshot:i,summon:s}=e,a="completed"===(r=i.status)||"unknown"===r?"settled":"failed"===r||"aborted"===r?"failed":"streaming",o="failed"===a,l=s?.model.split("/",1)[0]?.trim()||void 0,d=o&&l?l:function(e,t,n){let r="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",i=r.indexOf("/");if(i>0)return r.slice(0,i);let s=t?.model.trim()??"",a=s.indexOf("/");return a>0?s.slice(0,a):n?.trim()||void 0}(i,s,n),c=i.id.trim()||void 0,u=`subagent:${i.id}`,p=[],h=e.turnIndex,m=0;if((t?.entries??[]).forEach((t,n)=>{var r;let f;if("irc"in t){let{from:n,message:r,truncated:s}=t.irc;if(s||"string"!=typeof n||"string"!=typeof r)return;for(let t=m;t<e.sends.length;t+=1){let s=e.sends[t];if(s.send.message===r&&function(e,t){if(!e.from)return!1;let n=e.receipts;return!!n&&n.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(s.send,i.id)&&s.send.from===n){h=s.turnIndex,m=t+1;break}}return}if("assistant"!==t.message.role)return;let g=t.message.provider||d;if(!g||o&&l&&g!==l)return;let x=((f=((r=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?f:function(e){let t="";for(let n of e.content??[]){if("toolCall"!==n.type||"yield"!==n.toolName)continue;let e=n.input.data,r="";if("string"==typeof e)r=e;else if("object"==typeof e&&null!==e&&!Array.isArray(e))for(let t of["report",...ir]){let n=e[t];if("string"==typeof n&&n.trim().length>0){r=n;break}}let i=r.trim();i.length>0&&(t=i)}return t}(r))||(o?t.message.errorMessage?.trim()??"":"");0!==x.length&&p.push({key:`${i.id}:${n}`,turnIndex:h,speakerId:u,provider:g,credentialId:t.message.credentialId,accountSessionId:null,label:o&&s?s.alias:c,text:x,status:a})}),0===p.length&&"settled"!==a&&d){let e=o?i.progress?.retryFailure?.errorMessage?.trim():void 0;p.push({key:`${i.id}:pending`,turnIndex:h,speakerId:u,provider:d,accountSessionId:null,label:o&&s?s.alias:c,text:e||"",status:a})}return p})(t,a.get(t.snapshot.id),e.sessionProvider)),[r,a,e.sessionProvider])},is="web6",ia=[],io=[],il=function(e){let t=(0,i.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(n,r){let i=n.trim();if(!i)throw Error("sessionId가 필요하다");let s=`${t}?sessionId=${encodeURIComponent(i)}`,a=await e(s,{signal:r});if(!a.ok)throw Error(`HTTP ${a.status}`);let o=await a.json(),l=o&&"object"==typeof o&&"consults"in o?o.consults:null;if(!Array.isArray(l))throw Error("consults 배열이 아니다");return l.flatMap(e=>{let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t="string"==typeof e.sessionId?e.sessionId.trim():"";if(!t)return null;let n=e.startedAt;if("number"!=typeof n||!Number.isFinite(n))return null;let r=e.status;if("ok"!==r&&"failed"!==r)return null;let i="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:n,{conversationId:s,text:a,error:o}=e;return{sessionId:t,startedAt:n,finishedAt:i,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:i-n,model:"string"==typeof e.model?e.model:"",status:r,conversationId:"string"==typeof s&&""!==s?s:void 0,text:"string"==typeof a&&""!==a?a:void 0,error:"string"==typeof o&&""!==o?o:void 0}}(e);return t?.sessionId===i?[t]:[]})}}})(),[]),[n,r]=(0,i.useState)(io),s=(0,i.useRef)(""),a=e.sessionId??"",o=a.length>0;return(0,i.useEffect)(()=>{if(!o){s.current="",r(io);return}let e=new AbortController,n=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let n=await t.listConsults(a,e.signal),i=n.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(i===s.current)return;s.current=i,r(n)}catch{}};n();let i=setInterval(()=>void n(),5e3);return()=>{e.abort(),clearInterval(i)}},[t,o,a]),(0,i.useMemo)(()=>(function(e,t,n){if(0===e.length)return ia;let r=function(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if("user"!==r.role)continue;let i=r.timestamp;"number"==typeof i&&Number.isFinite(i)&&t.push({index:n,openedAt:i})}return t}(t);if(0===r.length)return ia;let i=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==n||"failed"!==t.status)continue;let e=function(e,t){let n;for(let r of e)r.openedAt>t||(!n||r.openedAt>=n.openedAt)&&(n=r);return n?.index}(r,t.startedAt);if(void 0===e)continue;let s=t.error??"";0!==s.trim().length&&i.push({key:`${is}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${is}:${t.conversationId??"unknown"}`,text:s,status:"failed"})}return i.length>0?i:ia})(n,e.messages,a),[n,e.messages,a])},id=(0,r.jsxs)(r.Fragment,{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"})]}),ic=(0,r.jsxs)(r.Fragment,{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:"m22 9-6 6m0-6 6 6"})]});function iu({soundEnabled:e,onToggle:t}){let n=e?"완료음 끄기":"완료음 켜기";return(0,r.jsx)("div",{role:"group","aria-label":"오디오",style:{display:"flex",alignItems:"center",gap:6},children:(0,r.jsx)("button",{type:"button",className:`composer-icon-button${e?" is-active":""}`,onClick:t,"aria-pressed":e,title:n,"aria-label":n,children:(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:e?id:ic})})})}let ip={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0},ih={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},im=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),ig=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function ix({sessionId:e,onEnsureSession:t,onTranscriptPersisted:n}){let{t:s}=(0,E.s)(),a=function(e,t,n){let{locale:r}=(0,E.s)(),[s,a]=(0,i.useState)("idle"),[o,l]=(0,i.useState)(null),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(!1),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(null),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(0);(0,i.useEffect)(()=>{m("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let j=(0,i.useCallback)(e=>{k.current+=1;let t=w.current;for(let e of(w.current=null,y.current?.close(),y.current=null,x.current?.close(),x.current=null,v.current?.getTracks()??[]))e.stop();v.current=null;let n=b.current;b.current=null,n&&(n.srcObject=null,n.remove()),t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),a(e),p(null),g(!1)},[]),S=(0,i.useCallback)((e,t)=>{l(e),c(t??null),j("error")},[j]),C=(0,i.useCallback)(async()=>{let i,s=k.current+1;k.current=s,l(null),c(null),g(!0),a("connecting");let o=e;if(!o&&t){try{o=await t()}catch{o=void 0}if(k.current!==s)return}if(!o){k.current===s&&(g(!1),S("failed"));return}try{i=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";k.current===s&&(g(!1),S("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(k.current!==s){for(let e of i.getTracks())e.stop();return}v.current=i;try{let e,t,l=new RTCPeerConnection;for(let e of(x.current=l,i.getTracks()))l.addTrack(e,i);let c=document.createElement("audio");if(c.autoplay=!0,b.current=c,l.ontrack=e=>{let[t]=e.streams;t&&(c.srcObject=t)},await l.setLocalDescription(await l.createOffer()),await function(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:n}=Promise.withResolvers(),r=()=>{clearTimeout(s),e.removeEventListener("icegatheringstatechange",i),n()},i=()=>{"complete"===e.iceGatheringState&&r()},s=setTimeout(r,3e3);return e.addEventListener("icegatheringstatechange",i),t}(l),k.current!==s)return;let h=l.localDescription?.sdp;if(!h)throw Error("The browser produced no offer SDP.");let m=await fetch("/api/live/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:o,sdp:h,locale:r})}),f=await m.json().catch(()=>({})),v="",j="";if(f&&"object"==typeof f&&("error"in f&&(e=f.error),"message"in f&&"string"==typeof f.message&&(t=f.message),"callId"in f&&"string"==typeof f.callId&&(v=f.callId),"sdp"in f&&"string"==typeof f.sdp&&(j=f.sdp)),!m.ok||!v||!j){if(k.current===s){var d,u;g(!1),S((d=m.status,u=e,401===d||"live-auth"===u?"auth":502===d||"live-upstream"===u?"upstream":"failed"),t)}return}if(k.current!==s)return void fetch(`/api/live/call/${encodeURIComponent(v)}`,{method:"DELETE"}).catch(()=>{});if(await l.setRemoteDescription({type:"answer",sdp:j}),k.current!==s){l.close(),fetch(`/api/live/call/${encodeURIComponent(v)}`,{method:"DELETE"}).catch(()=>{});return}w.current=v;let C=new EventSource(`/api/live/events?callId=${encodeURIComponent(v)}`);y.current=C,C.onmessage=e=>{let t;if(k.current===s){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var r;"string"==typeof t.state&&(r=t.state,!0===ip[r])&&a(t.state);return}if("transcript"===t.type&&"role"in t&&"text"in t){("user"===t.role||"assistant"===t.role)&&"string"==typeof t.text&&(p({role:t.role,text:t.text}),"final"in t&&!0===t.final&&n&&Promise.resolve().then(()=>n(o)).catch(()=>{}));return}"error"===t.type&&"message"in t&&"string"==typeof t.message&&S("upstream",t.message)}}},C.onerror=()=>{k.current===s&&w.current&&S("failed")},a("live")}catch(e){k.current===s&&S("failed",e instanceof Error?e.message:String(e))}finally{k.current===s&&g(!1)}},[e,t,n,r,S]),I=(0,i.useCallback)(()=>{if("idle"===s||"closed"===s||"error"===s){f||C();return}j("idle")},[f,s,C,j]);return(0,i.useEffect)(()=>()=>j("closed"),[j]),{state:s,failure:o,detail:d,transcript:u,supported:h,toggle:I}}(e,t,n),o="connecting"===a.state||"live"===a.state||"working"===a.state,l="connecting"===a.state?"chat.liveConnecting":"working"===a.state?"chat.liveWorking":"live"===a.state?"chat.liveOn":null,d=s(o?"chat.liveStop":"chat.liveStart"),c=!1===a.supported?ih.unsupported:a.failure?ih[a.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession";return(0,r.jsxs)("div",{role:"group","aria-label":s("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6},children:[c&&(0,r.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a.detail??void 0,children:s(c)}),l&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap"},children:s(l)}),(0,r.jsx)("button",{type:"button",className:`composer-icon-button${o?" is-active":""}`,onClick:a.toggle,disabled:!a.supported||!u,"aria-pressed":o,title:p?s(p):d,"aria-label":p?s(p):d,children:(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:o?ig:im})})]})}let iv={display:"inline-flex",alignItems:"center",flexShrink:0,height:32,padding:"0 10px",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",background:"var(--accent-soft)",color:"var(--accent-hover)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600,lineHeight:1.3,whiteSpace:"nowrap"};function ib({sessionId:e}){let{t}=(0,E.s)(),[n,s]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return void s(null);let t=!1,n=0,r=!1,i=async()=>{if("visible"===document.visibilityState)try{let n=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!n.ok)return;let i=await n.json();if(t)return;let a=Array.isArray(i.handles)?i.handles:[],o=a.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;r=null!==o,s(o)}catch{}},a=async()=>{await i(),t||(n=window.setTimeout(()=>void a(),r?5e3:3e4))};return a(),document.addEventListener("visibilitychange",i),()=>{t=!0,window.clearTimeout(n),document.removeEventListener("visibilitychange",i)}},[e]),n)?(0,r.jsx)("span",{style:iv,title:t("gpt6.boundBadgeHint",{handle:n}),children:t("gpt6.boundBadge",{handle:n})}):null}function iy(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 iw=new Map,ik="ompweb-drafts-for-reload-v1",ij=!1;function iS(){if(ij||"u"<typeof sessionStorage)return;ij=!0;let e=sessionStorage.getItem(ik);if(e){sessionStorage.removeItem(ik);try{let t=JSON.parse(e);if(!Array.isArray(t))return;for(let e of t){if(!Array.isArray(e)||2!==e.length||"string"!=typeof e[0])continue;let t=e[1];t&&"string"==typeof t.value&&Array.isArray(t.images)&&Array.isArray(t.documents)&&iw.set(e[0],iI(t))}}catch{}}}function iC(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(ik,JSON.stringify([...iw.entries()].map(([e,t])=>[e,iI(t)]))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function iI(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function iT(e){return!e.value&&0===e.images.length&&0===e.documents.length}function iN(e){iS();let t=iw.get(e);return t?iI(t):null}function iM(e,t){(iS(),iT(t))?iw.delete(e):iw.set(e,iI(t))}function iR(e){iw.delete(e)}function iE(e,t,n,r,i,s=[]){let a=[...t??[],...r].filter(iy).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),o=nW([...i??[],...s]);return{value:e.trim()?n.trim()?`${e}
13
+
14
+ ${n}`:e:n,images:a,documents:o}}function i$(e,t,n){if(e===t)return n?iI(n):iN(t);let r=iN(e),i=n&&!iT(n)?iI(n):r??(n?iI(n):null),s=iN(t);if(iR(e),!i)return s;let a=s?iE(s.value,s.images,i.value,i.images,s.documents,i.documents):i;return iM(t,a),iI(a)}function iL(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 iA(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function iP(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 iz(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}function iW(e,t,n,r,i={}){let s=i.gap??8,a=i.margin??8,o=i.prefer??"above",l=Math.min(i.minHeight??120,Math.max(0,n-2*a)),d=Math.max(0,e-s-a),c=Math.max(0,n-t-s-a),u="above"===o?d:c,p="above"===o?c:d,h=u>=r||u>=p;return{side:h?o:"above"===o?"below":"above",maxHeight:Math.max(l,Math.min(r,h?u:p))}}function iF(e,t,n){return Math.min(e*t,n)}function iD(e,t,n){let{viewportFraction:r,cap:s,gap:a,margin:o,minHeight:l,prefer:d}=n,[c,u]=(0,i.useState)({side:d??"above",maxHeight:s}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),c=iW(i.top,i.bottom,n,iF(n,r,s),{gap:a,margin:o,minHeight:l,prefer:d});u(e=>e.side===c.side&&e.maxHeight===c.maxHeight?e:c)},[e,s,a,o,l,d,r]);return(0,i.useEffect)(()=>{if(!t)return;p();let n=e.current,r=n?new ResizeObserver(p):null;return n&&r&&r.observe(n),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{r?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),c}var i_=n(14755);async function iB(e,t,n,r,i,s,a){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await a?.()??[],d=[...iQ,...l].find(e=>e.name===o||"aliases"in e&&e.aliases?.includes(o));if(s&&(!d||"builtin"===d.source))return i(`/${o} cannot run with attachments. Remove them and retry.`),!1;let c=await n?.(e);if(c?.handled){if(c.error)return!1;return c.prompt&&r(c.prompt),!0}if(d&&"builtin"!==d.source)return r(e),!0;return i(`/${o} is not available in this web session.`),!1}catch(e){return i(e instanceof Error?e.message:String(e)),!1}}let iO=["off","default","full"],iH={off:"none",default:"default",full:"full"},iU=i_.IN.join(" \xb7 "),iq=i_.C1.filter(e=>!i_.IN.includes(e)).join(" \xb7 ");function iV(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let iK=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),iJ=0,iG={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function iY(e,t){return iK.compare(e.name||e.modelId,t.name||t.modelId)||iK.compare(e.provider,t.provider)||iK.compare(e.modelId,t.modelId)}let iZ=["auto","off","minimal","low","medium","high","xhigh","max"],iX={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},iQ=[{name:"compact",descriptionKey:"chat.commandCompact",source:"builtin"},{name:"reload",descriptionKey:"chat.commandReload",source:"builtin"},{name:"name",descriptionKey:"chat.commandName",source:"builtin"},{name:"session",descriptionKey:"chat.commandSession",source:"builtin"},{name:"copy",descriptionKey:"chat.commandCopy",source:"builtin"}],i0=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],i1={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},i2={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function i8(e,t,n){let r=e.name.toLowerCase(),i=i4(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function i4(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function i5(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function i6(e){return{data:e.data,mimeType:e.mimeType}}function i3(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function i7(e){return(e??[]).filter(iy).slice(0,10).map(i3)}function i9(e){return nW(e).map(e=>({...e,id:++iJ,status:"ready"}))}function se(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function st({kind:e,text:t}){let n=n_(t),i=n?[n.message,n.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):t;return(0,r.jsxs)("div",{title:i,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:"var(--seed-radius-full)",border:`1px solid ${"steer"===e?"color-mix(in srgb, var(--accent) 45%, transparent)":"var(--border)"}`,color:"steer"===e?"var(--accent)":"var(--text-dim)"},children:e}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i})]})}function sn({tone:e,title:t,body:n}){let i="error"===e?"danger":"warning";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 var(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,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},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]})]})}function sr({error:e}){return e?(0,r.jsx)(sn,{tone:"error",title:"Model error",body:e}):null}function si({warnings:e}){return e&&0!==e.length?(0,r.jsx)(sn,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let ss=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:s,isStreaming:o,model:l,isAutoModelSelection:d,modelNames:c,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:m,onMainPresetChange:f,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:b,onCompact:y,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:I,thinkingLevel:T,effectiveThinkingLevel:N,onThinkingLevelChange:M,availableThinkingLevels:R,thinkingLevelMap:$,retryInfo:L,queuedMessages:A,inputHistory:P=[],onRecallQueue:z,slashCommands:F,slashCommandsLoading:D,onLoadSlashCommands:_,onBuiltinCommand:B,soundEnabled:O,onSoundToggle:H,onAudioUnlock:U,onPromptWithStreamingBehavior:q,draftKey:V,cwd:K,sessionId:J,onEnsureSession:G,onLiveTranscriptPersisted:Y},Z){let X,Q,ee,et,en,er,{t:ei}=(0,E.s)(),es=W(),[ea,eo]=(0,i.useState)(()=>V?iN(V)?.value??"":""),[el,ed]=(0,i.useState)(!1),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(""),[em,ef]=(0,i.useState)(!1),[eg,ex]=(0,i.useState)(null),[ev,eb]=(0,i.useState)(!1),[ey,ew]=(0,i.useState)(!1),[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(()=>V?i7(iN(V)?.images):[]),[eI,eT]=(0,i.useState)(()=>V?i9(iN(V)?.documents):[]),[eN,eM]=(0,i.useState)(null),eR=(0,i.useMemo)(()=>eI.filter(e=>"ready"===e.status),[eI]),eE=eI.some(e=>"ready"!==e.status),e$=ea.trimStart(),eL=0===eS.length&&0===eI.length&&e$.startsWith("!"),eA=eL&&e$.startsWith("!!"),[eP,ez]=(0,i.useState)(!1),[eW,eF]=(0,i.useState)(0),[eD,e_]=(0,i.useState)(null),[eB,eO]=(0,i.useState)(!1),[eH,eU]=(0,i.useState)(0),[eq,eV]=(0,i.useState)(!1),[eK,eJ]=(0,i.useState)(0),[eG,eY]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(null),[e1,e2]=(0,i.useState)(null),e8=K&&e1?.cwd===K?e1.values:{},e4=(0,i.useRef)(null),e5=(0,i.useRef)(null),e6=(0,i.useRef)(null),e3=(0,i.useRef)(null),e7=(0,i.useRef)(null),e9=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(null),tr=(0,i.useRef)(null),ti=(0,i.useRef)(null),ts=(0,i.useRef)(!1),ta=(0,i.useRef)(0),to=(0,i.useRef)(!1),tl=(0,i.useRef)([]),td=(0,i.useRef)([]),tc=(0,i.useRef)([]),tu=(0,i.useRef)(null),tp=(0,i.useRef)(null),th=(0,i.useRef)(V),tm=(0,i.useRef)(ea),tf=(0,i.useRef)(eS),tg=(0,i.useRef)(0),tx=(0,i.useRef)(eI);tm.current=ea,tf.current=eS,tx.current=eI,(0,i.useImperativeHandle)(Z,()=>({insertIfEmpty(e){let t=e4.current;(t?t.value:ea).trim()||(tm.current=e,eo(e),e_(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=e4.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ea,tf.current.length,tg.current,tx.current.length))return;let i=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n_(t)?.message??t),s=i7("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 iy(r)?[r]:[]})),a=i9((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n_(n)?.documents??[]));tm.current=i,tf.current=s,tx.current=a,eo(i),e_(null),eV(!1),eC(e=>(e.forEach(se),s)),eT(a),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(th.current!==e)return void i$(e,t);let n={value:tm.current,images:tf.current.map(i6),documents:tx.current.filter(e=>"ready"===e.status).map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r}))},r=i$(e,t,n)??{value:"",images:[],documents:[]},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)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text);if(th.current=t,i)return;let s=i7(r.images),a=i9(r.documents),o=r.value;tm.current=o,tf.current=s,tx.current=a,eo(o),eC(e=>(e.forEach(se),s)),eT(a),e_(null),eV(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=th.current,s=r??i,a=s===i,o=!a&&s?iN(s):null,l=iE(e,t,a?tm.current:o?.value??"",a?tf.current.map(i6):o?.images??[],n,a?tx.current.filter(e=>"ready"===e.status).map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r})):o?.documents??[]);if(s&&iM(s,l),!a)return;let d=t?.length?[...i7(t).slice(0,Math.max(0,10-tf.current.length)),...tf.current].slice(0,10):tf.current,c=i9(l.documents);tm.current=l.value,tf.current=d,tx.current=c,eo(l.value),e_(null),eV(!1),t?.length&&eC(e=>{let n=Math.max(0,10-e.length),r=i7(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tf.current=i,i}),eT(c),requestAnimationFrame(()=>{let e=e4.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=e4.current;if(!t)return void eo(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),s=t.value.slice(r),a=i.length>0&&!i.endsWith(" ")?" ":"",o=i+a+e+s;tm.current=o,eo(o),e_(null),requestAnimationFrame(()=>{if(!t)return;let r=n+a.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tk(e)}}));let tv=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tf.current.length-tg.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eM(ei("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:nB(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.length&&eM(ei("chat.attachImageLimit",{count:10})),i.length){tg.current+=i.length;try{let e=await Promise.all(i.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result.split(",")[1];t({data:n,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},r.onerror=n,r.readAsDataURL(e)})));eC(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(se);let r=[...t,...n];return tf.current=r,r})}finally{tg.current-=i.length}}},[ei]),tb=(0,i.useCallback)(async e=>{for(let t of e){let e=nL(t);if(!e)continue;if(tx.current.length>=3){eM(ei("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eM(ei("chat.attachTooLarge",{name:t.name,limit:nB(8388608)}));continue}if(tx.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eM(ei("chat.attachTotalTooLarge",{limit:nB(0x1000000)}));continue}let n={id:++iJ,name:t.name,mimeType:nR[e],size:t.size,text:"",status:"extracting"},r=[...tx.current,n];tx.current=r,eT(r);try{let e=await nF(t);if(tx.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new nM("text_too_large","Total extracted text exceeds 240000 characters");let r=tx.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tx.current=r,eT(r)}catch(i){let e=tx.current.some(e=>e.id===n.id),r=tx.current.filter(e=>e.id!==n.id);if(tx.current=r,eT(r),!e)continue;i instanceof nM?"text_too_large"===i.code?eM(ei("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eM(ei("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eM(ei("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.code?eM(ei("chat.attachPasswordProtected",{name:t.name})):eM(ei("chat.attachExtractFailed",{name:t.name})):eM(ei("chat.attachExtractFailed",{name:t.name}))}}},[ei]),ty=(0,i.useCallback)((e,t)=>{if(!tx.current.some(t=>t.id===e))return!1;let n=t?tx.current.map(n=>n.id===e?t:n):tx.current.filter(t=>t.id!==e);return tx.current=n,eT(n),!0},[]),tw=(0,i.useCallback)(async(e,t)=>{for(let n of e){if(tx.current.length>=3){eM(ei("chat.attachLimit",{count:3}));continue}if(n.size>0x1900000){eM(ei("chat.attachStoredTooLarge",{name:n.name,limit:nB(0x1900000)}));continue}let e={id:++iJ,name:n.name,mimeType:"text/plain",size:n.size,text:"",status:"audio"===t?"transcribing":"extracting",sourceSize:n.size},r=[...tx.current,e];tx.current=r,eT(r);let i=(t,n)=>{let r=tx.current.filter(t=>t.id!==e.id);return t<=12e4&&r.reduce((e,t)=>e+t.text.length,0)+t<=24e4&&r.reduce((e,t)=>e+t.size,0)+n<=0x1000000};if("file"===t&&n.size<=8388608){let t=await n.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?nz("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?nz("utf-16be",t.subarray(2)):t.includes(0)?null:nz("utf-8",t)??nz("euc-kr",t)},()=>null);if(null!==t&&i(t.length,n.size)){ty(e.id,{...e,text:t,status:"ready"});continue}}let s={...e,stored:t,status:"audio"===t?"transcribing":"uploading"};if(ty(e.id,s))try{let r=await nU(n,J),a=tx.current.filter(t=>t.id!==e.id).reduce((e,t)=>e+t.text.length,0),o=function(e,t=12e4){let n=`${nH}${e.path}
15
+ (${e.mimeType}, ${e.size} bytes) Open it with a tool when its contents are needed.`;if(void 0!==e.transcript){let r=`${n}
16
+
17
+ Transcript of the audio (speech-to-text by Gemini; may contain recognition errors):
18
+ `,i=r+e.transcript;return i.length<=t?i:r+e.transcript.slice(0,Math.max(0,t-r.length-nO.length))+nO}return e.transcriptError?`${n}
19
+ The audio could not be transcribed: ${e.transcriptError}`:n}(r,Math.min(12e4,24e4-a)),l=new TextEncoder().encode(o).byteLength;if(!i(o.length,l)){ty(e.id,null)&&eM(ei("chat.attachTotalTooLarge",{limit:nB(0x1000000)}));continue}let d="audio"===t&&void 0===r.transcript;ty(e.id,{...s,text:o,size:l,status:"ready",transcriptFailed:d})&&d&&eM(ei("chat.attachTranscribeFailedNotice",{name:n.name,error:r.transcriptError??""}))}catch(t){ty(e.id,null)&&eM(ei("chat.attachUploadFailed",{name:n.name,error:t instanceof Error?t.message:String(t)}))}}},[ty,J,ei]),tk=(0,i.useCallback)(async e=>{eM(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let s of e)s.type.startsWith("image/")?t.push(s):null!==nL(s)?n.push(s):nP(s)?r.push(s):i.push(s);return{images:t,documents:n,audio:r,files:i}}(e);await Promise.all([tv(t),tb(n),tw(r,"audio"),tw(i,"file")])},[tb,tw,tv]),tj=(0,i.useCallback)(e=>{eC(t=>{let n=[...t],[r]=n.splice(e,1);return r&&se(r),tf.current=n,n})},[]),tS=(0,i.useCallback)(e=>{let t=tx.current.filter(t=>t.id!==e);tx.current=t,eT(t)},[]),tC=(0,i.useCallback)(()=>{tf.current=[],eC(e=>(e.forEach(se),[]))},[]),tI=(0,i.useCallback)(()=>{tx.current=[],eT([])},[]),tT=(0,i.useCallback)(()=>{tm.current="",eo(""),e_(null),eV(!1),V&&iR(V),th.current&&th.current!==V&&iR(th.current),tC(),tI(),eM(null),e4.current&&(e4.current.style.height="auto")},[tI,tC,V]);(0,i.useEffect)(()=>{V&&th.current===V&&iM(V,{value:ea,images:eS.map(i6),documents:eR.map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r}))})},[eS,V,eR,ea]),(0,i.useEffect)(()=>{let e=th.current;if(e===V)return;e&&iM(e,{value:tm.current,images:tf.current.map(i6),documents:tx.current.filter(e=>"ready"===e.status).map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r}))});let t=V?iN(V):null;th.current=V;let n=t?.value??"",r=i7(t?.images),i=i9(t?.documents);tm.current=n,tf.current=r,tx.current=i,eo(n),e_(null),eV(!1),eC(e=>(e.forEach(se),r)),eT(i)},[V]),(0,i.useEffect)(()=>{let e=e4.current;e&&(e.style.height="auto",ea&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ea]),(0,i.useEffect)(()=>()=>{tf.current.forEach(se)},[]);let tN=(0,i.useCallback)(async()=>{let t=ea.trim(),n=e$.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if((r||eS.length||eR.length)&&!o&&!eE){if(U?.(),r.startsWith("/")){await iB(r,F,B,t=>e(t,eS.length?eS:void 0,eR.length?eR:void 0),eM,!!(eS.length||eR.length),_)&&tT();return}tT(),e(r,eS.length?eS:void 0,eR.length?eR:void 0)}},[ea,e$,eS,eR,eE,o,B,F,_,e,tT,U]),tM=e$.startsWith("/")&&!/\s/.test(e$.slice(1))?e$.slice(1).toLowerCase():null,tR=(()=>{if(null===tM)return[];let e=[...o?[]:iQ,...F??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=i4(e,ei).toLowerCase();return t.includes(tM)||n.includes(tM)}).sort((e,t)=>{let n=i8(e,tM,ei)-i8(t,tM,ei);return 0!==n?n:i2[e.source]-i2[t.source]||iK.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:tE,groups:t$}=(X=0,{commands:(Q=i0.map(e=>{let t=tR.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!i5(e,e8)),...t.filter(e=>i5(e,e8))]:t;return{source:e,items:n.map(e=>({command:e,index:X++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:Q}),tL=1===tR.length?ei(tM?"chat.match":"chat.command"):ei(tM?"chat.matches":"chat.commands",{count:tR.length}),tA=!!ea.trim(),tP=!eE&&(tA||eS.length>0||eR.length>0),tz=(0,i.useCallback)((e,t)=>{if(!K)return void e_(null);let n=t??e.length;e_(iL(e.slice(0,n)))},[K]),tW=eD?.query??null,tF=i.useMemo(()=>null!==tW&&eG&&eG.cwd===K?function(e,t,n=20){let 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:iP(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:iP(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||iA(e.entry.path)-iA(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eG.entries,tW):[],[tW,eG,K]),tD=!!(tW&&eG?.truncated&&eG.cwd===K);(0,i.useEffect)(()=>{if(!tD||!K||!tW)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(K)}&q=${encodeURIComponent(tW)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e0({cwd:K,query:tW,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tD,tW,K]);let t_=tD&&null!==eQ&&eQ.cwd===K&&eQ.query===tW,tB=t_?eQ.matches:tF,tO=null===eD?null:`${eD.start}:${+!!eD.quoted}:${eD.query}`;(0,i.useEffect)(()=>{if(null===tO){eO(!1),eU(0);return}eO(!0),eU(0)},[tO]);let tH=null!==eD,tU=iD(tr,eq,{viewportFraction:.44,cap:360}),tq=iD(tr,eP,{viewportFraction:.56,cap:460}),tK=iD(tr,eB,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!tH||!K)return;let e=tu.current;e&&e.cwd===K&&Date.now()-e.fetchedAt<1e4||tp.current===K||(tp.current=K,eX(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(K)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eY({cwd:K,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)=>iA(e.path)-iA(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tu.current={cwd:K,fetchedAt:Date.now()}}).catch(()=>{tu.current=null}).finally(()=>{tp.current=null,eX(!1)}))},[tH,K]);let tJ=(0,i.useCallback)(e=>{if(!eD)return;let t=e4.current,n=t?.selectionStart??ea.length,r=ea.slice(0,eD.start),i=ea.slice(n);eD.quoted&&i.startsWith('"')&&(i=i.slice(1));let s=function(e,t,n=!1){let 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,eD.quoted),a=r+s.text+i,o=r.length+s.cursorOffset;eo(a),e_(iL(a.slice(0,o))),requestAnimationFrame(()=>{let e=e4.current;e&&(e.focus(),e.setSelectionRange(o,o),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[eD,ea]);(0,i.useEffect)(()=>{eH>=tB.length&&eU(Math.max(0,tB.length-1))},[tB.length,eH]),(0,i.useEffect)(()=>{td.current.length=tB.length},[tB.length]),(0,i.useEffect)(()=>{eB&&td.current[eH]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eH,eB]),(0,i.useEffect)(()=>{eK>=P.length&&eJ(Math.max(0,P.length-1))},[P.length,eK]),(0,i.useEffect)(()=>{tc.current.length=P.length},[P.length]),(0,i.useEffect)(()=>{eq&&tc.current[eK]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eK,eq]);let tG=(0,i.useCallback)(e=>{tm.current=e,eo(e),eV(!1),eJ(0),e_(null),requestAnimationFrame(()=>{let t=e4.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),tY=(0,i.useCallback)(e=>{let t=`/${e.name} `;tm.current=t,eo(t),ez(!1),eF(0),requestAnimationFrame(()=>{let e=e4.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),tX=(0,i.useCallback)(async e=>{let t=ea.trim(),r=e$.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,a=eE||!i&&0===eS.length&&0===eR.length?null:{message:i,images:eS.length?eS:void 0,documents:eR.length?eR:void 0};if(!a)return;U?.();let o="steer"===e?"steer":"followUp";if(i.startsWith("/")){await iB(i,F,B,e=>{if(!q)throw Error("Cannot queue this command while the session is busy.");q(e,o,a.images,a.documents)},eM,!!(a.images?.length||a.documents?.length),_)&&tT();return}tT(),"steer"===e&&n?n(a.message,a.images,a.documents):"followup"===e&&s&&s(a.message,a.images,a.documents)},[ea,e$,eS,eR,eE,F,_,B,q,n,s,tT,U]),tQ=(0,i.useCallback)(e=>{let t=tE.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eW-1);if("right"===e)return Math.min(t,eW+1);let n=tl.current[eW];if(!n)return"down"===e?Math.min(t,eW+1):Math.max(0,eW-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,a=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===eW)continue;let t=tl.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-s;if("down"===e?l<=4:l>=-4)continue;let d=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);d<o&&(a=n,o=d)}return a>=0?a:"down"===e?Math.min(t,eW+1):Math.max(0,eW-1)},[tE.length,eW]),t0=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-ta.current<100,a=ts.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(a||i)){i&&e.preventDefault();return}if(eq&&!a){if("ArrowDown"===e.key){e.preventDefault(),eJ(e=>Math.min(Math.max(0,P.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eJ(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eV(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&P[eK]){e.preventDefault(),tG(P[eK]);return}}if(eP&&null!==tM){if("ArrowDown"===e.key){e.preventDefault(),eF(tQ("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eF(tQ("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eF(tQ("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eF(tQ("left"));return}if("Escape"===e.key){e.preventDefault(),ez(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&tE[eW]){e.preventDefault(),tY(tE[eW]);return}}if(eB&&null!==eD&&!a){if("ArrowDown"===e.key){e.preventDefault(),eU(e=>Math.min(Math.max(0,tB.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eU(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eO(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&tB[eH]){e.preventDefault(),tJ(tB[eH]);return}}if("ArrowUp"===e.key&&!a&&!o&&P.length>0&&0===ea.trim().length){e.preventDefault(),ez(!1),eO(!1),eJ(P.length-1),eV(!0);return}if("Escape"===e.key&&!a&&o&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),o&&(n||s)?tX(n?"steer":"followup"):tN())},[o,n,s,t,eP,tM,tE,eW,tY,tX,tN,tQ,eB,eD,tB,eH,tJ,eq,P,eK,tG,ea]),t1=(0,i.useCallback)(()=>{let e=e4.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),t2=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let n=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&n.push(e)}return n}(e.clipboardData);t.length&&(e.preventDefault(),tk(t))},[tk]);(0,i.useEffect)(()=>{if(null===tM){ez(!1),eF(0),to.current=!1;return}ez(!0),eF(0),!to.current&&_&&(to.current=!0,Promise.resolve(_()).catch(()=>{to.current=!1}))},[tM,_]),(0,i.useEffect)(()=>{if(!eP||!K)return;let e=!1;return e2({cwd:K,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(K)}`).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;e2({cwd:K,values:n})}).catch(()=>{e||e2({cwd:K,values:{}})}),()=>{e=!0}},[eP,K]),(0,i.useEffect)(()=>{eW>=tE.length&&eF(Math.max(0,tE.length-1))},[tE.length,eW]),(0,i.useEffect)(()=>{tl.current.length=tE.length},[tE.length]),(0,i.useEffect)(()=>{eP&&tl.current[eW]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eW,eP]);let t8=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(iY):Object.entries(c??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(iY),t4=(ee=ep.trim().toLocaleLowerCase())?t8.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ee)):t8,t5=t8.length>8,t6=[];for(let e of t4){let t=t6.find(t=>t.provider===e.provider);t?t.options.push(e):t6.push({provider:e.provider,options:[e]})}let t3=(x??[]).filter(e=>!e.hidden&&e.resolved),t7=l?t3.find(e=>e.resolved?.provider===l.provider&&e.resolved?.modelId===l.modelId):void 0,t9=l?t8.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,ne=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nt=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:ei("chat.compacted")} ${iz(S.tokensBefore)} -> ${iz(S.estimatedTokensAfter)} tokens (${ei("chat.tokensSaved",{saved:iz(ne)})})`:null,nn=(()=>{let e=T??"auto";if("auto"===e){let e=N&&($?.[N]??N);return e?`auto (${e})`:"auto"}return $?$[e]??e:e})(),nr=Object.entries(iH).find(([,e])=>e===(C??"default"))?.[0]??"default",ni=g??null;return(0,i.useEffect)(()=>{let e=e=>{e5.current&&!e5.current.contains(e.target)&&e6.current&&!e6.current.contains(e.target)&&(ed(!1),eh("")),e3.current&&!e3.current.contains(e.target)&&e7.current&&!e7.current.contains(e.target)&&ef(!1),e9.current&&!e9.current.contains(e.target)&&eb(!1),te.current&&!te.current.contains(e.target)&&ew(!1),tt.current&&!tt.current.contains(e.target)&&ej(!1),!tn.current||tn.current.contains(e.target)||e4.current?.contains(e.target)||eV(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{es||ej(!1)},[es]),(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:ti,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tk(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(sr,{error:p}),(0,r.jsx)(si,{warnings:h}),(A?.steering.length??0)+(A?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",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:ei("chat.queued",{count:(A?.steering.length??0)+(A?.followUp.length??0)})}),z&&(0,r.jsxs)("button",{onClick:z,title:ei("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:"var(--radius-control)",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"})]}),ei("chat.recall")]})]}),A?.steering.map((e,t)=>(0,r.jsx)(st,{kind:"steer",text:e},`steer-${t}`)),A?.followUp.map((e,t)=>(0,r.jsx)(st,{kind:"follow-up",text:e},`followup-${t}`))]}),L&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",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"})]}),ei("chat.retrying",{attempt:L.attempt,max:L.maxAttempts}),L.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",L.errorMessage]})]}),nt&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",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"})}),nt]}),j&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eN&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eN}),(0,r.jsx)("button",{type:"button",onClick:()=>eM(null),"aria-label":ei("i18n.close"),title:ei("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eS.length>0||eI.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":ei("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eS.map((e,t)=>(0,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":ei("chat.removeImage",{index:t+1}),onClick:()=>tj(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","aria-hidden":"true",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"})]})})]},`image-${t}`)),eI.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status?(0,r.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):nT(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?ei("chat.attachKindAudio"):"file"===e.stored?ei("chat.attachKindFile"):iG[e.mimeType]," \xb7 ",nB(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${ei("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${ei("chat.attachUploading")}`:"","transcribing"===e.status?` \xb7 ${ei("chat.attachTranscribing")}`:"",e.transcriptFailed&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${ei("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>tS(e.id),"aria-label":ei("chat.removeAttachment",{name:e.name}),title:ei("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),(0,r.jsxs)("div",{ref:tr,style:{position:"relative",minWidth:0},children:[eq&&P.length>0&&(0,r.jsxs)("div",{ref:tn,style:{position:"absolute",left:0,right:0,...iV(tU.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:tU.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",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:Math.max(0,tU.maxHeight-31),overflowY:"auto",padding:4},children:P.map((e,t)=>{let n=t===eK;return(0,r.jsxs)("button",{ref:e=>{tc.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tG(e)},onMouseEnter:()=>eJ(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",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}`)})})]}),eP&&null!==tM&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...iV(tq.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:tq.maxHeight},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)"},children:[(0,r.jsx)("span",{children:D?ei("chat.loadingCommands"):ei("chat.slashCommands",{label:tL})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ei("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,tq.maxHeight-34),overflowY:"auto",padding:10},children:D||0!==tR.length?t$.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:ei(i1[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(({command:e,index:t})=>{let n=t===eW,i=i5(e,e8);return(0,r.jsxs)("button",{ref:e=>{tl.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tY(e)},onMouseEnter:()=>eF(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"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:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(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:ei("chat.dormant")})]}),i4(e,ei)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:i4(e,ei)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ei("chat.noCommands")})})]}),eB&&null!==eD&&(et=eZ&&(!eG||eG.cwd!==K),en=1===tB.length?ei("chat.match"):ei("chat.matches",{count:tB.length}),er=eG?.truncated&&!t_?eD.query?ei("chat.searchingAll"):ei("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...iV(tK.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:tK.maxHeight},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)"},children:[(0,r.jsx)("span",{children:et?ei("chat.loadingFiles"):ei("chat.files",{label:en,hint:er})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ei("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,tK.maxHeight-34),overflowY:"auto",padding:4},children:et||0!==tB.length?tB.map((e,t)=>{let n=t===eH,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{td.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tJ(e)},onMouseEnter:()=>eU(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",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)(nS,{size:14}):nT(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:tD&&!t_?ei("chat.searching"):ei("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${eL?" is-bash":""}${o?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${eL?"var(--tool-bg)":o&&(n||s)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:e4,value:ea,onChange:e=>{tm.current=e.target.value,eo(e.target.value),eV(!1),tz(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tz(t.value,t.selectionStart)},onKeyDown:t0,onCompositionStart:()=>{ts.current=!0},onCompositionEnd:e=>{ts.current=!1,ta.current=Date.now();let t=e.currentTarget;tz(t.value,t.selectionStart)},onInput:t1,onPaste:t2,placeholder:o&&(n||s)?ei("chat.steerPlaceholder"):o?ei("chat.agentPlaceholder"):ei("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),o?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>tX("steer"),disabled:!tP,title:eE?ei("chat.attachExtractingWait"):ei("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tP?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:tP?"var(--warning)":"var(--text-dim)",cursor:tP?"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"})]}),ei("chat.steer")]}),s&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>tX("followup"),disabled:!tP,title:eE?ei("chat.attachExtractingWait"):ei("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tP?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:tP?"var(--accent-hover)":"var(--text-dim)",cursor:tP?"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"})]}),ei("chat.followUp")]})]}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:tN,disabled:!tP,"aria-busy":eE||void 0,title:eE?ei("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"7px 14px",background:tP?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:tP?"var(--accent-hover)":"var(--text-dim)",cursor:tP?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 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"})]}),ei("chat.send")]})]})]}),eL&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eA?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ei("chat.shell")," \xb7 ",eA?ei("chat.outputLocal"):ei("chat.outputModel")]}),(0,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:es?"1 1 0%":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eS.length||eI.length?" is-active":""}`,onClick:()=>ti.current?.click(),title:ei("chat.attachFile"),"aria-label":ei("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:eS.length||eI.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=eS.length||eI.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eS.length||eI.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"})]})}),(t8.length>0||t9||p)&&m&&(0,r.jsxs)("div",{ref:e5,style:{position:"relative",flex:es?"1 1 0%":void 0,minWidth:0},children:[(0,r.jsxs)("button",{className:`composer-chip${el?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eu({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ed(e=>(e&&eh(""),!e))},disabled:o||b,"aria-busy":b||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:es?"flex-start":void 0,padding:es?"8px 10px":"8px 12px",height:32,width:es?"100%":void 0,maxWidth:es?"100%":220,overflow:"hidden",background:el?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=el?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:b?"Switching model":t8.length>0?"Change model":"No available models",children:[b?(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",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:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:t9??(t8.length>0?"Select model":"No models")})]}),el&&ec&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=iW(ec.top,ec.bottom,e,iF(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ec.top+6}:{top:ec.bottom+6},s=es?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ec.left,width:"max-content",minWidth:ec.width};return(0,r.jsxs)("div",{ref:e6,style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[t5&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{value:ep,onChange:e=>eh(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eh(""),ed(!1))},placeholder:ei("chat.filterModels"),"aria-label":ei("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!es,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[t3.length>0&&!ep.trim()&&v&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:ei("chat.modelRoles")}),t3.map(e=>{let t=t7?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{ed(!1),eh(""),v(e.role)},title:e.selector??n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},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},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:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)}),(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:ei("chat.allModels")})]}),0===t6.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ep.trim()?ei("chat.noMatchingModels"):"No available models"}):t6.map((e,t)=>(0,r.jsxs)("div",{children:[t6.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>{let t=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,r.jsxs)("button",{onClick:()=>{ed(!1),eh(""),(!t||d)&&m(e.provider,e.modelId)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},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},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}}),e.name]},`${e.provider}:${e.modelId}`)})]},e.provider))]})]})})()]}),f&&tV.length>0&&(0,r.jsxs)("div",{ref:e3,style:{position:"relative",flexShrink:+!!es,minWidth:0},children:[(0,r.jsxs)("button",{className:`${es?"composer-icon-button":"composer-chip"}${em?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ex({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ed(!1),eh(""),ef(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":em,onKeyDown:e=>{"Escape"===e.key&&em&&(e.stopPropagation(),ef(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:em?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=em?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:ei("chat.mainPreset"),"aria-label":ei("chat.mainPreset"),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},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),es?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ei("chat.mainPreset")})]}),em&&eg&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=iW(eg.top,eg.bottom,e,iF(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eg.top+6}:{top:eg.bottom+6},s=es?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eg.left,width:"max-content",minWidth:eg.width};return(0,r.jsx)("div",{ref:e7,role:"menu","aria-label":ei("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(ef(!1),e3.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:tV.map(e=>{let t=e.alias===ni;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{ef(!1),f({alias:e.alias,provider:e.provider,modelId:e.model,...void 0!==e.oauthPosition?{oauthPosition:e.oauthPosition}:{}})},title:`${e.provider}/${e.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},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},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)("img",{className:"account-avatar",src:tZ(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:e.alias}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}),(0,r.jsx)(ib,{sessionId:J})]}),(0,r.jsxs)("div",{ref:tt,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:es?4:2},children:[es?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${ek?" is-active":""}`,title:ei("chat.moreControls"),"aria-label":ei("chat.moreControls"),"aria-expanded":ek,onClick:()=>{ed(!1),eh(""),ej(e=>!e)},children:(0,r.jsxs)("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)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(a.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:ek?void 0:ei("chat.moreControls"),"aria-label":ei("chat.moreControls"),"aria-expanded":ek,onClick:()=>{ed(!1),eh(""),ej(e=>!e)},children:ei("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":ei("chat.moreControls"),style:{display:ek?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[!o&&M&&(0,r.jsxs)("div",{ref:te,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${ey?" is-active":""}`,onClick:()=>!o&&ew(e=>!e),disabled:o,title:ei("chat.changeReasoning",{level:nn}),"aria-label":ei("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:ey?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ey?"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"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nn})]}),ey&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:180},children:iZ.filter(e=>!R||"auto"===e||R.includes(e)).map(e=>{let t=(T??"auto")===e,n=ei(iX[e]),i="auto"!==e&&$?$[e]:void 0,s=null!=i&&i!==e?i:e,a=null!=i&&i!==e;return(0,r.jsxs)("button",{onClick:()=>{ew(!1),M(e)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},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},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.jsxs)("span",{style:{flex:1},children:[s,a&&(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)})})]}),!o&&I&&(0,r.jsxs)("div",{ref:e9,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${ev?" is-active":""}`,onClick:()=>!o&&eb(e=>!e),disabled:o,title:ei("chat.changeToolPreset")+`: ${nr}`,"aria-label":ei("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:ev?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ev?"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"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nr})]}),ev&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:iO.map(e=>{let t=iH[e],n=(C??"default")===t,i="off"===e?ei("chat.noTools"):"default"===e?ei("chat.builtInTools",{tools:iU}):ei("chat.allBuiltInTools",{tools:`${iU} + ${iq}`});return(0,r.jsxs)("button",{onClick:()=>{eb(!1),n||I(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(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:i})]},e)})})]}),!o&&y&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:o&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:o&&!k?"not-allowed":"pointer",fontSize:12,opacity:o&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!o||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?ei("chat.stopCompaction"):ei("chat.compactContext"),"aria-label":k?ei("chat.stopCompaction"):ei("chat.compactContext"),children:k?(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"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ei("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"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ei("chat.compact")})]})})}),ek&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:ei("chat.collapseControls"),"aria-label":ei("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eb(!1),ew(!1),ej(!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"})]})})]}),o&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:ei("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},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"})}),ei("chat.stop")]}),(0,r.jsx)(ix,{sessionId:J,onEnsureSession:G,onTranscriptPersisted:Y}),void 0!==H&&(0,r.jsx)(iu,{soundEnabled:O??!0,onToggle:H})]})]})]})]})});function sa({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),n=ef(t);return(0,r.jsx)("div",{role:"status","aria-label":n,title:n,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ey(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function so({phases:e}){let{t}=(0,E.s)(),[n,s]=(0,i.useState)(!1),[a,o]=(0,i.useState)(!1),{currentPhase:l,activeTask:d,remaining:c,completed:u,total:p,percent:h}=function(e){let t=0,n=0,r=null,i=null,s=null;for(let a of e)for(let e of a.tasks){if("completed"===e.status){t+=1;continue}"abandoned"!==e.status&&(n+=1,"in_progress"===e.status?r||(r={phase:a,task:e}):"blocked"===e.status?s||(s={phase:a,task:e}):i||(i={phase:a,task:e}))}let a=r??i??s,o=t+n;return{currentPhase:a?.phase??null,activeTask:a?.task??null,remaining:n,completed:t,total:o,percent:o>0?Math.round(t/o*100):null}}(e);if(0===p)return null;let m=0===c;return(0,r.jsxs)("div",{className:`todo-strip${m?" is-done":""}`,children:[(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":n,onClick:()=>s(e=>!e),children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:m?"✓":"›"}),l&&(0,r.jsx)("span",{className:"todo-strip-phase",children:l.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:m?t("todo.allDone",{count:u}):d?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:m?t("todo.progressDone",{percent:h??0,completed:u,total:p}):t("todo.progress",{percent:h??0,completed:u,total:p,remaining:c})})]}),n&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[e.map((t,n)=>{let i=t.tasks.filter(e=>a||"completed"!==e.status);return 0===i.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),i.map((e,t)=>(0,r.jsx)(nw,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`)}),u>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":a,onClick:()=>o(e=>!e),children:t(a?"todo.hideCompleted":"todo.showCompleted",{count:u})})]})]})}function sl(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function sd(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}async function sc(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,...e.tag?{tag:e.tag}:{}};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}}class su extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function sp(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 su(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let sh="ompweb-update-client-id",sm="ompweb-update-resume-intent-v2",sf="ompweb-update-return-v1",sg="cuelo-restart-return-v1",sx="ompweb:update-wake";function sv(e){return null===e||"running"===e?null:"failed"===e?3e4:8e3}function sb(){let e=sessionStorage.getItem(sh);if(e&&/^[A-Za-z0-9_-]{16,128}$/.test(e))return e;let t="function"==typeof crypto.randomUUID?crypto.randomUUID().replaceAll("-",""):Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("");return sessionStorage.setItem(sh,t),t}function sy(){let e=sessionStorage.getItem(sf);if(!e)return null;try{let t=JSON.parse(e);if(1!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"boolean"!=typeof t.dismissed)return null;return t}catch{return null}}function sw(e){let t=sy();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(sf,JSON.stringify(n))}catch{}return n}async function sk(e){let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"heartbeat",clientId:sb(),sessionId:e.sessionId,resumeUrl:e.resumeUrl,preservationError:e.preservationError??null,...e.update?{requestId:e.update.requestId,stageHash:e.update.stageHash}:{}}),cache:"no-store"});if(!t.ok)throw Error(`maintenance heartbeat HTTP ${t.status}`);return await t.json()}async function sj(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let n=await t.json().catch(()=>null);!function(e){let t=sy();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let n={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(sf,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),sessionStorage.removeItem(sm);let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(sx,{detail:{sessionId:e.sessionId}}))}function sS(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}function sC(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function sI(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.name!==i.name||r.tasks.length!==i.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=i.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker)return!1}}return!0}function sT(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(e.id,e);let r=[...n.values()];return[...r.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...r.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function sN(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function sM(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!eF(r??void 0))return{message:e[n],entryId:r}}return null}let sR=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class sE extends Error{constructor(e){super("timeout"===e?"Timed out connecting to the agent event stream. Please try again.":"Failed to connect to the agent event stream. Please try again."),this.status=e,this.name="EventStreamConnectionError"}}function s$(e){return new Promise(t=>setTimeout(t,e))}function sL(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function sA(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:sL(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:sL(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=sL(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function sP(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 sz(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(sP).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function sW(e){return"user"===e.role?`user:${sz(e)}`:"bashExecution"===e.role?JSON.stringify({role:e.role,command:e.command,output:e.output,exitCode:e.exitCode,cancelled:e.cancelled,truncated:e.truncated,fullOutputPath:e.fullOutputPath,excludeFromContext:e.excludeFromContext}):JSON.stringify({role:e.role,content:e.content,model:e.model,provider:e.provider,customType:e.customType})}function sF(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 sD(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function s_({sticker:e,text:t,tag:n,followRef:s}){let a=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!s||s.current)&&a.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:a,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:rM[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(rC(),{id:"ad10be785ccf4f7",children:".cue-bubble-sticker{transform-origin:center 75%;animation:cue-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes cue-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.cue-bubble-sticker{animation:none}}"})]}):null}function sB(e){return`omp-cues:${e}`}function sO(e,t){let n=[];for(let r of t)r.sessionId===e&&null!==r.anchorEntryId&&n.push({id:r.id,anchorEntryId:r.anchorEntryId,sticker:r.sticker,text:r.text,tag:r.tag});try{window.localStorage.setItem(sB(e),JSON.stringify(n.slice(-200)))}catch{}}let sH=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:s,messageCwd:a,onOpenFile:o,sessionBusy:l,isNew:d,isStreaming:c,displayOptions:u,handleFork:p,forkingEntryId:h,handleNavigate:m,handleEditContent:f,sessionId:g,visibleCount:x,sentinelRef:v,t:b,onProcessLogChange:y,cues:w,cueFollowRef:k}){var j;let S,C,{main:I,process:T}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],s=-1,a=null,o=(e,t,n)=>{if(0===t.length)return;let r=(a&&a.anchorIdx===e||(a={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(a)),a);for(let e of t)r.entries.push(e);r.messageCount+=t.length,r.toolCallCount+=n},l=eL(e),d=new Map,c=(e,t)=>{let n=d.get(e)??0;d.set(e,n+1),r.push({kind:"answer",anchorIdx:s,idx:e,runIndex:n,blocks:l.attach(t),precedingBlocks:[]})},u=()=>{let e=l.takeRemaining();e&&c(e.idx,e.blocks)};for(let i of t){if("answer"===i.kind){r.push(i);continue}if("process"===i.kind){o(i.anchorIdx,i.entries,i.toolCallCount);continue}let t=e[i.idx];if(!t)continue;if("user"===t.role){u(),s=i.idx,r.push(i);continue}if("custom"===t.role&&t.customType===ez){r.push(void 0!==i.anchorIdx||s<0?i:{...i,anchorIdx:s});continue}if("assistant"!==t.role){"toolResult"!==t.role&&o(s,[{idx:i.idx}],0);continue}let a=eR(t,n),d=!1;for(let e of a){if("answer"===e.kind){c(i.idx,e.blocks),d=!0;continue}o(s,[{idx:i.idx,blocks:e.blocks}],eE(e.blocks)),l.collect(i.idx,e.blocks)}!d&&eM(t,n)&&c(i.idx,[])}return u(),{main:r,process:i}})(e,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(e_(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!e_(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let s=i,a=s+1;for(;a<e.length&&!e_(e[a]);)a+=1;if((t.sessionBusy||t.isStreaming)&&a===e.length&&s===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,s+1,a)){for(let e=s;e<a;e++)r.push({kind:"message",idx:e});i=a;continue}for(let n of(r.push({kind:"message",idx:s}),function(e,t,n,r){let i=[],s=[],a=0,o=[],l=0,d=0,c=eL(e.slice(t+1,n)),u=()=>{0!==s.length&&(i.push({kind:"process",anchorIdx:t,idx:s[0].idx,groupIndex:d++,entries:s,messageCount:s.length,toolCallCount:a,turnHasAnswer:!1}),s=[],a=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:l++,blocks:c.attach(n),precedingBlocks:o}),o=[]};for(let l=t+1;l<n;l++){let n=e[l];if("assistant"!==n.role){if("custom"===n.role&&n.customType===ez){u(),i.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==n.role&&s.push({idx:l});continue}let d=eR(n,r),h=d.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of d){if("answer"===e.kind){p(l,e.blocks);continue}for(let t of(s.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),a+=eE(e.blocks),c.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&eM(n,r)&&p(l,[])}u();let h=c.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:l++,blocks:h.blocks,precedingBlocks:[]});let m=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=m);return i}(e,s,a,{hideThinking:t.hideThinking})))r.push(n);i=a}return r}(e,{sessionBusy:l,isStreaming:c,hideThinking:u.hideThinking}),u),[e,l,c,u]);(0,i.useEffect)(()=>{y({groups:T,messages:e,entryIds:t,toolResults:n,modelNames:s,cwd:a,sessionId:g})},[y,T,e,t,n,s,a,g]);let{startIndex:N,hasMore:M}=(S=Math.min(Math.max(x,0),Math.max(j=I.length,0)),{startIndex:C=Math.max(0,j-S),hasMore:C>0}),R=(i,u={})=>{let x=u.messageOverride??e[i],v=i-1;for(;v>=0&&eF(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=u.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&c&&i===e.length-1&&(w=!1)}return void 0!==u.showTimestamp&&(w=u.showTimestamp),(0,r.jsx)(n4,{message:x,toolResults:n,modelNames:s,cwd:a,onOpenFile:o,entryId:t[i],onFork:l||d||0===i&&"user"===x.role?void 0:p,forking:h===t[i],onNavigate:l?void 0:m,prevAssistantEntryId:l?void 0:b,onEditContent:f,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:g,writtenFiles:u.writtenFiles},`${y}-view-${i}`)};return(0,r.jsxs)(r.Fragment,{children:[M&&(0,r.jsx)("div",{ref:v,className:"py-3 text-center text-xs text-text-muted",children:b("chat.loadEarlier",{count:N})}),I.slice(N).map((s,l)=>{let d="message"===s.kind?s.anchorIdx??s.idx:s.anchorIdx,c=I[N+l+1],u=c?"message"===c.kind?c.anchorIdx??c.idx:c.anchorIdx:null,p=c?c.idx:1/0,h=w.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=s.idx&&r<p}).map(e=>(0,r.jsx)(s_,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:k},`cue-${e.id}`)),m=u===d?null:(0,r.jsx)(rH,{turnIndex:d,turnEntryId:t[d],sessionId:g,cwd:a,onOpenFile:o});if("message"===s.kind)return(0,r.jsxs)(i.Fragment,{children:[R(s.idx),m,h]},`message-${s.idx}`);let f=function(e,t,n){let r=new Set,i=[];for(let s of e){if("toolCall"!==s.type||!function(e){let t,n;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||"edit"===(n=e.toLowerCase())||n.startsWith("edit_")||n.endsWith(".edit")||n.endsWith("_edit")||n.includes("str_replace")||n.includes("replace_editor")}(s.toolName))continue;let e=t?.get(s.toolCallId);if(!e||e.isError)continue;let a=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(s.input);if(!a||!/^[a-zA-Z]:[\\/]/.test(a)&&/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(a))continue;let o=function(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),a=t?i(t).replace(/\/+$/,""):void 0,o=/^[a-zA-Z]:\//.test(s),l=s.startsWith("//");if(o||l)n=s;else if(s.startsWith("/")){let e=a?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??a?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!a)return null;n=`${a}/${s}`}return eH(n)}(a,n);o&&(r.has(o)||(r.add(o),i.push({filePath:o})))}return i}(s.precedingBlocks,n,a);return(0,r.jsxs)(i.Fragment,{children:[R(s.idx,{keyPrefix:`answer-${s.runIndex}`,messageOverride:eT(e[s.idx],s.blocks),writtenFiles:f}),m,h]},`answer-${s.idx}-${s.runIndex}`)})]})});function sU({session:e,newSessionCwd:t,initialSessionData:s,transitioning:a=!1,onAgentEnd:o,onAttentionNeeded:l,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsChange:f,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:b,onProcessLogChange:y,onOpenFile:w,transcriptReplacement:k,onComposerFocusChange:j,onSessionBusyChange:S,onWaitingChange:C,onAttentionChange:I,soundEnabled:T=!0,onSoundToggle:N,playCueSound:M=async()=>({sticker:null,text:null}),preloadCueSound:R,unlockAudio:$}){var L,A;let P,z,W,{t:F}=(0,E.s)(),D=(0,i.useRef)(M);D.current=M;let _=(0,i.useRef)(null),B=(0,i.useRef)(R);B.current=R;let O=(0,i.useRef)(null),[U,q]=(0,i.useState)([]),V=(0,i.useRef)(U);V.current=U;let K=(0,i.useRef)(0),J=(0,i.useRef)([]),G=(0,i.useRef)([]),Y=(0,i.useRef)(null),Z=(0,i.useRef)(0),X=(0,i.useRef)(-1),Q=(0,i.useRef)(-1),ee=(0,i.useCallback)(()=>{let e=Y.current?.current;return e?{sessionId:e,turn:Z.current}:null},[]),et=(0,i.useCallback)(e=>Y.current?.current===e.sessionId&&Z.current===e.turn,[]),en=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;K.current=Math.max(K.current+1,Date.now());let i={id:K.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},s="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};q(e=>{let t=[...e,s];return null!==s.anchorEntryId&&sO(n.sessionId,t),t})},[]),er=(0,i.useCallback)((e,t,n,r)=>{let i=()=>et(n)&&("working"!==t||Q.current!==n.turn);i()&&D.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&en(e,t,n,r)}).catch(()=>{})},[et,en]),ei=(0,i.useCallback)(async(e,t,n)=>{let r=nf(e,t,n);if(r||!t)return r?.alias??null;let i=O.current;if(i&&i.sessionId===e&&i.provider===t)return i.alias;try{let{data:n}=await ne(e),r=n?.state==="resolved"&&n.provider===t?n.credentialId:void 0,i=nf(e,t,r)?.alias??null;return i&&(O.current={sessionId:e,provider:t,alias:i},B.current?.(i)),i}catch{return null}},[]),es=(0,i.useCallback)((e,t,n,r,i)=>{let s=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=rW(e[n]),s=0;for(let t=r;t<=n;t++)rW(e[t])===i&&(s+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:s}}}(J.current,G.current);ei(t.sessionId,n,r).then(a=>{console.info(`[cue] tag=${e} alias=${a} provider=${n} credentialId=${r} source=${i} session=${t.sessionId} turn=${t.turn}`),er(a,e,t,s)})},[er,ei]),[ea,eo]=(0,i.useState)(0),el=(0,i.useRef)([]),ed=(0,i.useCallback)(e=>{if(Z.current+=1,null!==rE(e.outcome)){let t=e.sessionId;el.current.push({completion:e,trigger:t?{sessionId:t,turn:Z.current}:null}),eo(e=>e+1)}o?.(e)},[o]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of el.current.splice(0)){let n=rE(e.outcome),r="neutral"===n?null:n;t?es(r,t,e.provider,e.credentialId,"completion"):D.current(null,r).catch(()=>{})}},[ea,es]);let ec=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:eu,error:ep,messages:eh,entryIds:em,streamState:eg,agentRunning:ex,bashRunning:ev,pendingBash:eb,modelNames:ey,modelList:ew,modelError:ek,modelScopeWarnings:ej,modelThinkingLevels:eS,modelThinkingLevelMaps:eC,modelRoles:eI,toolPreset:eN,thinkingLevel:eM,effectiveThinkingLevel:e$,retryInfo:eL,contextUsage:eA,forkingEntryId:eP,isCompacting:eB,compactError:eO,compactResult:eH,displayModel:eU,modelSwitching:eV,sessionStats:eK,slashCommands:eJ,slashCommandsLoading:eG,queuedMessages:eY,subagents:eZ,todoPhases:eX,notices:eQ,extensionDialog:e0,extensionResponse:e1,extensionCustomUi:e2,extensionStatuses:e8,extensionWidgets:e4,respondToExtensionUi:e5,sendExtensionCustomInput:e6,isAutoModelSelection:e3,agentPhase:e7,isNew:e9,autoFollowPaused:te,resumeAutoFollow:tt,goalStatus:tn,sessionIdRef:tr,messagesEndRef:ti,scrollContainerRef:ts,handleSend:ta,handleAbort:to,handleFork:tl,handleNavigate:td,handleModelChange:tc,handleRoleModelChange:tu,handleMainPresetChange:tp,newSessionAccount:th,handleCompact:tm,handleSteer:tf,handleFollowUp:tg,handlePromptWithStreamingBehavior:tx,handleAbortCompaction:tv,handleRecallQueue:tb,handleBuiltinSlashCommand:ty,handleToolPresetChange:tw,handleThinkingLevelChange:tk,loadSlashCommands:tj,ensureNewSession:tS,refreshLiveTranscript:tC}=function(e){let{session:t,newSessionCwd:r,initialData:s,onAgentEnd:a,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,f=s&&s.sessionId===t?.id?s:null,[g,x]=(0,i.useState)(f),[v,b]=(0,i.useState)(!m&&!f),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(f?.leafId??null),[S,C]=(0,i.useState)(f?.context.messages??[]),[I,T]=(0,i.useState)(f?.context.entryIds??[]),[N,M]=(0,i.useReducer)(sS,{isStreaming:!1,streamingMessage:null}),[R,E]=(0,i.useState)(!1),[$,L]=(0,i.useState)(!1),[A,P]=(0,i.useState)(null),[z,W]=(0,i.useState)({}),[F,D]=(0,i.useState)([]),[_,B]=(0,i.useState)(null),[O,H]=(0,i.useState)([]),[U,q]=(0,i.useState)({}),[V,K]=(0,i.useState)({}),[J,G]=(0,i.useState)([]),[Y,Z]=(0,i.useState)(null),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)("default"),[ei,es]=(0,i.useState)(()=>{let e=f?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[ea,eo]=(0,i.useState)(),[el,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(f?.contextUsage??null),[ep,eh]=(0,i.useState)(null),[em,eg]=(0,i.useState)(null),[ex,ev]=(0,i.useState)(null),[eb,ey]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(!1),[ej,eS]=(0,i.useState)(!1),[eC,eI]=(0,i.useState)(null),[eT,eN]=(0,i.useState)(null),[eM,eR]=(0,i.useState)(null),[eE,e$]=(0,i.useState)([]),[eL,eA]=(0,i.useState)(!1),[eP,e_]=(0,i.useReducer)(sA,{visible:[],pending:[]}),[eB,eO]=(0,i.useState)(null),[eH,eU]=(0,i.useState)(null),[eq,eV]=(0,i.useState)(null),eK=(0,i.useRef)(null),[eJ,eG]=(0,i.useState)(null),[eY,eZ]=(0,i.useState)([]),[eX,eQ]=(0,i.useState)([]),[e0,e1]=(0,i.useState)({steering:[],followUp:[]}),[e2,e8]=(0,i.useState)([]),[e4,e5]=(0,i.useState)(null),e6=(0,i.useRef)(null),e3=(0,i.useRef)(null),e7=(0,i.useRef)(null),e9=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(0),tn=(0,i.useRef)(!1),tr=(0,i.useRef)(t?.id??null),ti=(0,i.useRef)(f?.leafId??null),ts=(0,i.useRef)(S),ta=(0,i.useRef)(I);ts.current=S,ta.current=I;let to=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tl=(0,i.useRef)(!1),td=(0,i.useRef)(!1),tc=(0,i.useRef)(!1),tu=(0,i.useRef)(-1),tp=(0,i.useRef)("unknown"),th=(0,i.useRef)(null),tm=(0,i.useRef)(null),tf=(0,i.useRef)(0),tg=(0,i.useRef)(!1),tx=(0,i.useRef)(0),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useRef)(!1),tk=(0,i.useRef)(!0),[tj,tS]=(0,i.useState)(!1),[tC,tI]=(0,i.useState)(null),tT=(0,i.useRef)(void 0),tN=(0,i.useRef)(0),tM=(0,i.useRef)(0),tR=(0,i.useRef)(()=>{}),tE=(0,i.useRef)(null),t$=(0,i.useRef)(null),tL=(0,i.useRef)(null),tA=(0,i.useRef)(!1),tP=(0,i.useRef)(null),tz=(0,i.useRef)(null),tW=(0,i.useRef)(null),tF=(0,i.useRef)(!1);tF.current=e.transitioning??!1;let tD=(0,i.useRef)(Date.now()),t_=(0,i.useRef)(0),tB=(0,i.useRef)(0),tO=(0,i.useRef)(null),tH=(0,i.useRef)(!1),tU=(0,i.useRef)(Promise.resolve()),tq=e.setToolPreset??er,tV=ex??g?.context.model??eb??null,tK=m?Y??ee:tV,tJ=(0,i.useMemo)(()=>{if(eB)return{...eB,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,s=0,a=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(s+=1),"assistant"!==t.role)continue;i+=1;let o=t.usage;a+=t.content.filter(e=>"toolCall"===e.type).length,o&&(e.input+=o.input??0,e.output+=o.output??0,e.cacheRead+=o.cacheRead??0,e.cacheWrite+=o.cacheWrite??0,n+=o.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tr.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:i,toolCalls:a,toolResults:s,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ec?{contextUsage:ec}:{}}},[S,eB,ec,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),tG=(0,i.useRef)(0),tY=(0,i.useCallback)((e,t)=>{e&&tr.current===e&&Array.isArray(t)&&(tG.current+=1,e5(n=>n?.sid===e&&sI(n.phases,t)?n:{sid:e,phases:t}))},[]),tZ=(0,i.useCallback)((e,t,n)=>{tr.current===e&&tG.current===n&&Array.isArray(t)&&e5(n=>n?.sid===e&&sI(n.phases,t)?n:{sid:e,phases:t})},[]),tX=(0,i.useCallback)(e=>{let t="function"==typeof e?e(ts.current):e;ts.current=t,C(t)},[]),tQ=(0,i.useCallback)(e=>{ta.current=e,T(e)},[]),t0=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&b(!0);let s=r??null;if(!s){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),tX([]),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);s=await r.json()}if(tr.current!==e)return null;x(s),j(s.leafId),ti.current=s.leafId??null;let a=eD(s.context.messages,s.context.entryIds??[],to.current.sessionId===e?to.current.outputs:[]);if(tX(a.messages),tQ(a.entryIds),eu(s.contextUsage??null),ev(e=>tH.current?e:null),w(null),es(s.context.configuredThinkingLevel??s.context.thinkingLevel??"off"),eo(s.context.thinkingLevel),i=!0,t&&b(!1),!n)return null;try{let t=tG.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tr.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&eu(i.contextUsage??null),void 0!==i.systemPrompt&&eh(i.systemPrompt??null),void 0!==i.thinkingLevel&&(es(i.configuredThinkingLevel??i.thinkingLevel),eo(i.thinkingLevel)),void 0!==i.extensionStatuses&&eZ(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&eQ(i.extensionWidgets??[]),void 0!==i.queuedMessages&&e1(sC(i.queuedMessages)),void 0!==i.subagents&&e8(e=>sT(e,i.subagents??[])),tZ(e,i.todoPhases,t)):r.running||e1({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&b(!1)}},[tZ,tQ,tX]),t1=(0,i.useCallback)(e=>{let t=tU.current.then(async()=>{tr.current===e&&await t0(e)});return tU.current=t.catch(()=>{}),t},[t0]),t2=(0,i.useCallback)(async(e,t)=>{try{let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&n.set("leafId",t);let r=`/api/sessions/${encodeURIComponent(e)}/context?${n}`,i=await fetch(r);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();ti.current=t;let a=eD(s.context.messages,s.context.entryIds??[],to.current.sessionId===e?to.current.outputs:[]);tX(a.messages),tQ(a.entryIds),eu(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[tQ,tX]),t8=(0,i.useCallback)(async e=>{try{let t=await sp(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));tq(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[tq]),t4=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tr.current;m&&r&&n&&!tA.current&&(tA.current=!0,l?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[m,r,l]),t5=(0,i.useCallback)(async()=>{if(tr.current||!m||!r)return tr.current;if(tL.current)return tL.current;let e=(async()=>{let e=tP.current,t=tW.current,n=tz.current;e&&ey(e);let i=(0,i_.xG)(en),s=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",toolNames:i,...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{},...e&&null!==n?{oauthPosition:n}:{}})});if(!s.ok)throw Error(`HTTP ${s.status}`);let a=await s.json(),o=a.sessionId;return tr.current=o,a.model&&tP.current===e&&(ey(a.model),e||et(a.model)),a.thinkingLevel&&tW.current===t&&(es(a.configuredThinkingLevel??a.thinkingLevel),eo(a.thinkingLevel)),o})();tL.current=e;try{return await e}finally{tL.current=null}},[m,r,en]),t6=(0,i.useCallback)(async()=>{let e=tr.current??await t5();if(!e)return e$([]),[];eA(!0);try{let t=await sp(e,{type:"get_commands"}),n=t?.commands??[];return e$(n),n}catch(e){return console.error("Failed to load slash commands:",e),e$([]),[]}finally{eA(!1)}},[t5]),t3=(0,i.useCallback)(()=>{tt.current+=1,tn.current=!1,te.current&&(clearTimeout(te.current),te.current=null)},[]),t7=(0,i.useCallback)(()=>{e6.current?.close(),e6.current=null,e3.current=null,e7.current=null},[]),t9=(0,i.useCallback)(()=>{e9.current?.close(),e9.current=null},[]),ne=(0,i.useCallback)(e=>{t9();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);e9.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tv.current?.(n):"agent_start"===n.type&&tb.current?.(e)}catch{}}},[t9]),nt=(0,i.useCallback)(e=>{t7();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);e6.current=t,e3.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(s),e7.current?.source===t&&(e7.current.pending=!1),n({status:e,source:t}))},s=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tv.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),e6.current===t&&(tl.current||tn.current))){e6.current=null,e3.current=null,e7.current=null;let t=tt.current;setTimeout(()=>{t===tt.current&&!e6.current&&(tl.current||tn.current)&&nt(e)},1e3)}}});return e7.current={source:t,promise:n,pending:!0},n},[t7]),nn=(0,i.useCallback)(async e=>{let t=e6.current;if(t&&e3.current===e){if(t.readyState===EventSource.OPEN)return;let e=e7.current;if(e?.source===t&&e.pending&&(await e.promise,e6.current===t&&t.readyState===EventSource.OPEN))return}let n=await nt(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw e6.current===n.source&&(e6.current=null),e3.current===e&&(e3.current=null),e7.current?.source===n.source&&(e7.current=null),n.source.close(),new sE(n.status)},[nt]),nr=(0,i.useCallback)(async(e,t)=>{let n=eK.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tr.current,i=e=>{eK.current=e,eV(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await sp(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),eU(t=>t?.id===e.id?null:t)},[]),ni=(0,i.useCallback)(async(e,t)=>{let n=tr.current;if(n)try{await sp(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),ns=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e_({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"}})},[]),na=(0,i.useCallback)(e=>{let t={role:"custom",customType:ez,content:ef(e).trim(),display:!0,timestamp:Date.now()},n=to.current,r=tr.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=ta.current.slice(0,ts.current.length),s=null;for(let e=i.length-1;e>=0;e--)if(!eF(i[e])){s=i[e];break}n.seq+=1,n.outputs.push({entryId:`${eW}${n.seq}`,baseEntryId:s,message:t}),tX(e=>[...e,t])},[tX]),no=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){eU(e=>e?.id===t.id?null:e),eK.current?.id===t.id&&(eK.current=null,eV(null));return}switch(sd(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":eU(t);break;case"notify":ns({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":eZ(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":eQ(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":eG(e=>t.closed?e?.id===t.id?null:e:t)}},[ns,o,e.chatInputRef]),nl=(0,i.useCallback)(()=>{let e=tl.current;return tl.current=!1,E(!1),eR(null),ed(null),M({type:"end"}),e},[]),nd=(0,i.useCallback)(()=>{tp.current="unknown",th.current=null;let e=sM(ts.current,ta.current);tm.current=e?{entryId:e.entryId,key:sW(e.message)}:null,tf.current+=1},[]),nc=(0,i.useCallback)(()=>{let e=tp.current,t=th.current;if("unknown"===e){let n=sM(ts.current,ta.current),r=n?.message,i=tm.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:sW(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=sN(r),t??={provider:r.provider,...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tr.current,...t?{provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nu=(0,i.useCallback)(e=>{let t=nc();if("unknown"!==t.outcome||!e)return void a?.(t);let n=tf.current;e.catch(()=>void 0).then(()=>{let e=tr.current===t.sessionId&&tf.current===n;a?.(e?nc():t)})},[a,nc]),np=(0,i.useCallback)((e,t)=>tu.current!==e&&(tu.current=e,nu(t),!0),[nu]),nh=(0,i.useCallback)(e=>{t3(),tn.current=!0;let t=tt.current,n=async()=>{if(t===tt.current&&tr.current===e&&tn.current)try{let r=tG.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(t!==tt.current||tr.current!==e||!tn.current)return;let a=s.state;if(e8(e=>sT(e,a?.subagents??[])),tZ(e,a?.todoPhases,r),s.running&&a&&(a.isStreaming||a.isPromptRunning||a.isHandoffRunning)){tn.current=!1,te.current=null,td.current=!!a?.isStreaming,tc.current=!!a?.isPromptRunning,tl.current=!0,E(!0),eR(a?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(s.running&&a?.isCompacting){eS(!0),te.current=setTimeout(()=>void n(),600);return}if(s.running&&(a?.subagents?.length??0)>0){te.current=setTimeout(()=>void n(),1e3);return}tn.current=!1,te.current=null,t7()}catch{if(t!==tt.current||tr.current!==e||!tn.current)return;te.current=setTimeout(()=>void n(),600)}};te.current=setTimeout(()=>void n(),3e4)},[tZ,t3,t7]),nm=(0,i.useCallback)(async(e=tr.current,t=t_.current)=>{if(t_.current===t)try{e&&await t0(e)}finally{if(t_.current!==t)return;let n=tc.current,r=td.current;tc.current=!1,td.current=!1,tO.current=null;let i=nl();n?np(t):r&&i&&nu(),e&&nh(e)}},[t0,nu,np,nh,nl]),nf=(0,i.useCallback)(async(e,t)=>{await s$(800);let n=Date.now();for(;tl.current&&Date.now()-n<2e4;){if(void 0!==t&&t_.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nm(e,t)}}catch{}await s$(600)}},[nm]),ng=(0,i.useCallback)(async e=>{let t=tx.current+1;for(tx.current=t;tg.current&&tx.current===t&&tr.current===e;){await s$(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await t0(e),tx.current!==t||tr.current!==e)return;tg.current=!1,L(!1),P(null);return}catch{}}},[t0]),nx=(0,i.useCallback)(async e=>{if(!tl.current)return;let t=t_.current;try{let n=tG.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(t_.current!==t)return;let s=i.state;if(eS(s?.isCompacting??!1),e1(sC(s?.queuedMessages)),s?.contextUsage!==void 0&&eu(s.contextUsage??null),e8(e=>sT(e,s?.subagents??[])),tZ(e,s?.todoPhases,n),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting||s.isHandoffRunning)||!tl.current)return;s&&(void 0!==s.systemPrompt&&eh(s.systemPrompt??null),void 0!==s.extensionStatuses&&eZ(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&eQ(s.extensionWidgets??[])),await nm(e,t)}catch{}},[tZ,nm]),nv=(0,i.useCallback)(async e=>{let t=await t0(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tr.current===e&&!tl.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(td.current=!!n.isStreaming,tc.current=!!n.isPromptRunning,tl.current=!0,E(!0),eR(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),M({type:"start"}),nt(e),!n.isStreaming&&n.isPromptRunning&&nf(e),!0)},[nt,t0,nf]),nb=(0,i.useCallback)(async(e,t=t_.current)=>{let n=tB.current+1;tB.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==tB.current||tr.current!==e||t_.current!==t)return;i.state?.contextUsage!==void 0&&eu(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!R&&!ej)return;let e=()=>{let e=tr.current;e&&nb(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[R,ej,nb]),(0,i.useEffect)(()=>{if(!R)return;let e=()=>{let e=tr.current;e&&nx(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)}},[R,nx]),(0,i.useEffect)(()=>{if(R)return;let e=()=>{let e=tr.current;e&&!tl.current&&nv(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tr.current,n=e.detail?.sessionId;t&&n===t&&!tl.current&&nv(t).then(e=>{e||tr.current!==t||tl.current||t0(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(sx,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(sx,n)}},[R,nv,t0]),tb.current=e=>{if(tr.current!==e||tl.current||e6.current||ty.current)return;let t=nv(e).then(async t=>{t||tr.current!==e||tl.current||await t0(e)}).catch(()=>{}).finally(()=>{ty.current===t&&(ty.current=null)});ty.current=t},(0,i.useEffect)(()=>{tl.current=R},[R]),tv.current=(0,i.useCallback)(e=>{switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let s=e.context.messages,a=new Map;for(let e of s){let t=sW(e);a.set(t,(a.get(t)??0)+1)}let o=Math.min(r.length,i.length);for(let e of r.slice(0,o)){let t=sW(e),n=a.get(t)??0;n>0&&a.set(t,n-1)}let l=r.slice(o).filter(e=>{let t=sW(e),n=a.get(t)??0;return 0===n||(a.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...s,...l],entryIds:[...e.context.entryIds]}}(e,tr.current,ti.current,ts.current,ta.current);if(!t)break;ti.current=t.entryId;let n=eD(t.messages,t.entryIds,to.current.sessionId===tr.current?to.current.outputs:[]);tX(n.messages),tQ(n.entryIds);break}case"agent_start":{let e=!tl.current;t3(),e&&nd(),td.current=!0,tl.current=!0,E(!0),eR({kind:"waiting_model"}),M({type:"start"});break}case"agent_end":if(!tl.current)break;if(eR(null),ed(null),M({type:"end"}),tr.current){t0(tr.current);let e=tG.current;fetch(`/api/agent/${encodeURIComponent(tr.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&eu(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eh(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&eZ(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&eQ(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&e8(e=>sT(e,t.state?.subagents??[])),tr.current&&tZ(tr.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tI(t.state.goal??null),e1(sC(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tI(e.status??null);break;case"agent_settled":{let e=td.current;if(td.current=!1,!e||tc.current)break;let t=tr.current,n=nl();eS(!1);let r=t?t0(t):void 0;t&&nh(t),n&&nu(r);break}case"prompt_done":{let e=t_.current,t=tc.current;tc.current=!1,tO.current=null;let n=tu.current!==e;if(!t&&!n)break;let r=tr.current;np(e,r?t0(r):void 0),!td.current&&(nl(),r&&nh(r))}break;case"prompt_error":tp.current="failed",ns({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tp.current="failed",ns({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tl.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&M({type:"update",message:r6(t)}),eR(null);break}case"message_end":{if(!tl.current)break;let t=e.message;if(t?.role==="assistant"&&(th.current={provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tp.current=sN(t)),t&&"user"===t.role){let e=r6(t),n=sz(e),r=tO.current;tO.current=null,tX(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&sz(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else t&&tX(e=>[...e,r6(t)]);let n=tr.current;n&&nb(n),M({type:"reset"}),eR({kind:"waiting_model"});break}case"todo_changed":tY(tr.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args;eR(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:n,args:r}),{kind:"running_tools",tools:i}});break}case"tool_execution_end":{let t=e.toolCallId;eR(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"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";e8(n=>{let r=n.find(e=>e.id===t.id);return sT(n,[{id:t.id,index:t.index??r?.index??0,agent:t.agent??r?.agent??t.id,agentSource:t.agentSource??r?.agentSource??"bundled",description:t.description??r?.description,status:e,task:r?.task,assignment:r?.assignment,sessionFile:t.sessionFile??r?.sessionFile,parentToolCallId:t.parentToolCallId??r?.parentToolCallId,lastUpdate:Date.now(),progress:r?.progress?{...r.progress,status:e}:void 0}])});break}let n={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};e8(e=>sT(e,[n]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let n=t.progress,r={id:n.id,index:t.index??n.index,agent:t.agent??n.agent,agentSource:t.agentSource??"bundled",description:n.description,status:n.status,task:t.task??n.task,assignment:t.assignment??n.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:n};e8(e=>sT(e,[r]));break}case"queue_update":e1({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ed({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ed(null);break;case"auto_compaction_start":case"compaction_start":eS(!0),eI(null),eN(null);break;case"auto_compaction_end":case"compaction_end":if(eS(!1),e.errorMessage)eI(e.errorMessage),eN(null);else if(!e.aborted){eN(sF(e.result,e.reason??"auto"));let t=tr.current;t&&(t0(t),nb(t))}break;case"extension_ui_request":no(e)}},[ns,tY,tZ,t3,no,t0,nu,np,nb,nd,nh,nl,tQ,tX]);let ny=(0,i.useCallback)(async(n,i,s)=>{let a=n.trim();if(!a&&!i?.length&&!s?.length||tl.current||tg.current||tH.current)return;let o=nD(n,s??[]),l=!i?.length&&!s?.length&&a.startsWith("/");if(!i?.length&&!s?.length&&a.startsWith("!")){let e=a.startsWith("!!"),t=(e?a.slice(2):a.slice(1)).trim();if(!t)return;await tT.current?.(t,e);return}nd();let d=t_.current+1;t3(),tc.current=!0;let c=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:c?.length?[...o.trim()?[{type:"text",text:o}]:[],...c]:o,timestamp:Date.now()};tX(e=>[...e,u]),tO.current=sz(u),t_.current=d,tl.current=!0,E(!0),eR(l?{kind:"running_command"}:{kind:"waiting_model"}),M({type:"start"}),tR.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,f=!1;try{if(m&&r){let e=tr.current??await tL.current,t=e??await t5();t&&(h=t,Y&&(ey(Y),e&&await sp(t,{type:"set_model",provider:Y.provider,modelId:Y.modelId})),await nn(t),f=!0,await sp(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),t4(1,n))}else t&&(h=t.id,await nn(t.id),f=!0,await sp(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}));l&&h&&nf(h,d)}catch(o){console.error("Failed to send message:",o);let r=o instanceof su&&"update_draining"===o.code&&!1===o.accepted;if(!(!f||o instanceof su&&"prompt_rejected"===o.code&&!1===o.accepted||r)&&h)return void nf(h,d);tc.current=!1,tl.current=!1,t7();let a=tO.current;a&&tX(e=>{let t=e[e.length-1];return t?.role==="user"&&sz(t)===a?e.slice(0,-1):e}),ns({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(n,sD(i),s,t?.id??h??void 0),tO.current=null,E(!1),eR(null),M({type:"end"})}},[m,r,Y,t,t5,nn,t4,nf,ns,t3,t7,e.chatInputRef,nd,tX]);tT.current=(0,i.useCallback)(async(n,r)=>{if(tl.current||tg.current)return;let i=`${r?"!!":"!"}${n}`;tg.current=!0,tR.current(!0),P({command:n,excludeFromContext:r}),L(!0);try{let e=tr.current??t?.id??await t5();if(!e)throw Error("Unable to create a session for the shell command");await sp(e,{type:"bash",command:n,excludeFromContext:r}),await t0(e),t4(1,i)}catch(t){console.error("Failed to execute shell command:",t),ns({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tg.current=!1,P(null),L(!1)}},[ns,t5,t0,e.chatInputRef,t4,t]);let nw=(0,i.useCallback)(async()=>{let e=tr.current;if(e){if(tg.current){try{await sp(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sp(e,{type:"abort"}),tp.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nk=(0,i.useCallback)(async e=>{if(tg.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tr.current;if(!t)return{forked:!1,error:"No active session to fork"};eg(e??null);try{let{cancelled:n,newSessionId:r}=await sp(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return d?.(r),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eg(null)}},[d]),nj=(0,i.useCallback)(async e=>{if(tg.current)return;let t=tr.current;t&&(sp(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await t2(t,e))},[t2]),nS=(0,i.useCallback)(async e=>{if(tg.current)return;j(e);let t=tr.current;t&&(await t2(t,e),e&&sp(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[t2]),nC=(0,i.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t};tP.current=n,tz.current=null,Q(null),Z(n),ey(n);let r=tr.current??await tL.current;if(!r)return;try{await sp(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tr.current;if(n&&!tH.current){tH.current=!0,ev({provider:e,modelId:t}),ek(!0);try{await sp(n,{type:"set_model",provider:e,modelId:t}),tH.current=!1,await t0(n)}catch(e){console.error("Failed to set model:",e),tH.current=!1,ev(ex),ns({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await t0(n)}finally{tH.current=!1,ek(!1)}}},[ns,ex,m,t0,Z]),nI=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},n=e.oauthPosition,r={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==n?{oauthPosition:n}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(tH.current)return!1;tH.current=!0,ek(!0);let e=tP.current,s=tz.current,a=tW.current;try{tP.current=t,tz.current=n??null,tW.current="auto";let e=tr.current??await tL.current;return e&&await sp(e,r),Z(t),Q(n??null),ey(t),es("auto"),eo(void 0),e&&await t0(e),!0}catch(n){console.error("Failed to apply Main preset:",n),tP.current=e,tz.current=s,tW.current=a,ns({type:"error",message:i(n)});let t=tr.current;return t&&await t0(t),!1}finally{tH.current=!1,ek(!1)}}let s=tr.current;if(!s||tH.current)return!1;tH.current=!0,ev(t),ek(!0);try{return await sp(s,r),await t0(s),!0}catch(e){return console.error("Failed to apply Main preset:",e),ev(ex),ns({type:"error",message:i(e)}),await t0(s),!1}finally{tH.current=!1,ek(!1)}},[ns,ex,ea,m,t0,Z,ei]),nT=(0,i.useCallback)(async e=>{let t=J.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;tW.current=t??null,es(t??"auto"),eo(void 0),tP.current=e,tz.current=null,Q(null),Z(e),ey(e)}let r=tr.current??(m?await tL.current:null);if(r)try{await sp(r,{type:"set_role_model",role:e}),m||ev({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,J,Z]),nN=(0,i.useCallback)(async()=>{let e=tr.current;if(e&&!ej){eS(!0),eI(null),eN(null);try{let t=await sp(e,{type:"compact"});eN(sF(t,"manual")),await t0(e,!0)}catch(e){eI(e instanceof Error?e.message:String(e)),eN(null)}finally{eS(!1)}}},[ej,t0]),nM=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",s=await fetch(i,e?{signal:e}:void 0);if(!s.ok)throw Error(`HTTP ${s.status}`);let a=await s.json();W(a.models),B(a.modelError??null),H(a.modelScopeWarnings??[]),q(a.thinkingLevels??{}),K(a.thinkingLevelMaps??{}),G(a.roles??[]);let o=a.modelList??[];if(D(o),m&&!tr.current){let e=(a.defaultModel?o.find(e=>e.id===a.defaultModel?.modelId&&e.provider===a.defaultModel?.provider):void 0)??o[0];et(e?{provider:e.provider,modelId:e.id}:null);let t=e&&a.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===tW.current&&es(t??"auto")}},[m,r,t?.cwd]),nR=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),s=tr.current??await t5(),a=e=>(e.handled&&(e.error?ns({type:"error",message:e.error}):"openSessionStats"!==e.action&&ns({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!s||ej)return a({handled:!0,error:"No active session to compact"});eS(!0),eI(null),eN(null);let e=await sp(s,{type:"compact",...i?{customInstructions:i}:{}});return eN(sF(e,"manual")),await t0(s,!0)&&t4(),a({handled:!0,message:"Compacted context"})}case"reload":if(!s)return a({handled:!0,error:"No active session to reload"});return await sp(s,{type:"reload"}),await Promise.all([t0(s,!1,!0),t8(s),t6(),nM()]),a({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return a({handled:!0,error:"No active session to name"});if(!i)return a({handled:!0,error:"Usage: /name <name>"});return await sp(s,{type:"set_session_name",name:i}),await t0(s)&&t4(),a({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!s)return a({handled:!0,error:"No active session"});let e=await sp(s,{type:"get_session_stats"});return e&&eO(e),h?.(),a({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return a({handled:!0,error:"No active session"});let e=await sp(s,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return a({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),a({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!s)return a({handled:!0,error:"No active session to fork"});let e=await nk();if(!e.forked)return a({handled:!0,error:e.error??"Fork failed"});return a({handled:!0,message:"Forked a new session"})}case"goal":{if(!s)return a({handled:!0,error:"No active session"});let e=await sp(s,{type:"goal",args:i});if(tI(e?.status??null),e?.error)return a({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(na(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&ns({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return a({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!s)return a({handled:!0,error:"No active session"});if(tl.current||tg.current)return a({handled:!0,error:"Cannot hand off while the session is busy"});tl.current=!0,E(!0),eR({kind:"running_command"});try{await nn(s);let e=await sp(s,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return a({handled:!0,error:"Handoff cancelled"});return await t0(s,!0)&&t4(),a({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tl.current=!1,E(!1),eR(null),tr.current===s&&nh(s)}default:{if(!s)return a({handled:!0,error:"No active session"});let t=await sp(s,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&na(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return a({handled:!0,message:"Command completed"})}}}catch(e){return a({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eS(!1)}},[ns,na,nn,t5,nk,ej,nM,t0,t6,t8,t4,h,nh]),nE=(0,i.useCallback)(async(t,n,r)=>{let i=tr.current;if(!i){ns({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,sD(n),r);return}let s=nD(t,r??[]),a=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sp(i,{type:"steer",message:s,...a?.length?{images:a}:{}})}catch(s){console.error("Failed to steer:",s),ns({type:"error",message:s instanceof Error?s.message:String(s)}),e.chatInputRef?.current?.restoreSubmission?.(t,sD(n),r,i)}},[ns,e.chatInputRef]),n$=(0,i.useCallback)(async(t,n,r,i)=>{let s=tr.current;if(!s){ns({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,sD(r),i);return}let a=nD(t,i??[]),o=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sp(s,{type:"prompt",message:a,streamingBehavior:n,...o?.length?{images:o}:{}})}catch(n){console.error("Failed to queue prompt:",n),ns({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,sD(r),i,s)}},[ns,e.chatInputRef]),nL=(0,i.useCallback)(async(t,n,r)=>{let i=tr.current;if(!i){ns({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,sD(n),r);return}let s=nD(t,r??[]),a=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sp(i,{type:"follow_up",message:s,...a?.length?{images:a}:{}})}catch(s){console.error("Failed to follow up:",s),ns({type:"error",message:s instanceof Error?s.message:String(s)}),e.chatInputRef?.current?.restoreSubmission?.(t,sD(n),r,i)}},[ns,e.chatInputRef]),nA=(0,i.useCallback)(async()=>{let e=tr.current;if(e)try{await sp(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nP=(0,i.useCallback)(async()=>{let t=tr.current;if(t)try{var n;let r=await sp(t,{type:"clear_queue"});e1({steering:[],followUp:[]});let i={text:(n=[...r?.steering??[],...r?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:n.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(i.text,i.images.length?i.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),ns({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,ns]),nz=(0,i.useCallback)(async e=>{es(e),m&&!tr.current&&(tW.current=e),eo(void 0);let t=tr.current??await tL.current;if(t)try{await sp(t,{type:"set_thinking_level",level:e}),await t0(t)}catch(e){console.error("Failed to set thinking level:",e),ns({type:"error",message:"Failed to set thinking level"}),await t0(t)}},[m,t0,ns]),nW=(0,i.useCallback)(async e=>{let t=(0,i_.xG)(e);tq(e);let n=tr.current??await tL.current;if(n)try{await sp(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[tq]),nF=(0,i.useCallback)(e=>{tk.current=e,tS(t=>!e===t?t:!e)},[]);tR.current=nF;let n_=(0,i.useCallback)((e="smooth")=>{tM.current=Date.now()+700,tE.current?.scrollIntoView({behavior:e})},[]),nB=(0,i.useCallback)(()=>{tN.current=0,nF(!0),n_("smooth")},[n_,nF]),nO=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!sR.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tN.current=Date.now()+1200)},[]),nH=(0,i.useCallback)(()=>{if(!tl.current&&!tg.current)return;let e=t$.current;if(!e)return;let t=Date.now()<=tN.current;!t&&Date.now()<tM.current||(e.scrollHeight-e.scrollTop-e.clientHeight<=72?nF(!0):t&&nF(!1))},[nF]);return(0,i.useEffect)(()=>(tr.current=t?.id??null,to.current.sessionId!==tr.current&&(to.current={sessionId:tr.current,outputs:[],seq:0}),t&&t0(t.id,!f,!0,f).then(e=>{if(tr.current!==t.id)return;ne(t.id),e?.running&&(t8(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(td.current=!!e.state.isStreaming,tc.current=!!e.state.isPromptRunning,tl.current=!0,E(!0),eR(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),M({type:"start"}),nt(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nf(t.id)),e.state?.isBashRunning&&(tg.current=!0,L(!0),ng(t.id)),(e.state?.subagents?.length??0)>0&&nt(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&eS(n.isCompacting),void 0!==n.contextUsage&&eu(n.contextUsage??null),void 0!==n.systemPrompt&&eh(n.systemPrompt??null),void 0!==n.thinkingLevel&&(es(n.configuredThinkingLevel??n.thinkingLevel),eo(n.thinkingLevel)),void 0!==n.extensionStatuses&&eZ(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&eQ(n.extensionWidgets??[]),void 0!==n.queuedMessages&&e1(sC(n.queuedMessages)),void 0!==n.subagents&&e8(e=>sT(e,n.subagents??[])),void 0!==n.goal&&tI(n.goal??null))}),()=>{tx.current+=1,t3(),t7(),t9()}),[t?.id]),(0,i.useEffect)(()=>{p?.(ep)},[ep,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,nS)},[g?.tree,k,nS,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",nO),()=>{window.removeEventListener("keydown",nO)}),[nO]),(0,i.useEffect)(()=>{let e=t$.current;if(e)return e.addEventListener("pointerdown",nO,{passive:!0}),e.addEventListener("wheel",nO,{passive:!0}),e.addEventListener("touchstart",nO,{passive:!0}),e.addEventListener("scroll",nH,{passive:!0}),()=>{e.removeEventListener("pointerdown",nO),e.removeEventListener("wheel",nO),e.removeEventListener("touchstart",nO),e.removeEventListener("scroll",nH)}},[S.length,v,nH,nO]),(0,i.useEffect)(()=>{if(tF.current||!R&&!$||!tk.current)return;let e=t$.current;if(!e)return;let t=requestAnimationFrame(()=>{tM.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[R,$,S.length,N.streamingMessage,eM,A,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tw.current){tw.current=!0,n_("instant");return}if(!tF.current&&tk.current){let e=Date.now()-tD.current<1500;n_(tl.current||tg.current||e?"instant":"smooth")}}},[S.length,R,$,n_,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return nM(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[nM,c]),(0,i.useEffect)(()=>{if(!eT)return;let e=setTimeout(()=>eN(null),6e3);return()=>clearTimeout(e)},[eT]),(0,i.useEffect)(()=>{if(0===eP.visible.length)return;let e=eP.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e_({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eP.visible[0])return;let t=setTimeout(()=>{e_({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eP.visible]),(0,i.useEffect)(()=>{eO(null)},[S.length,ec?.tokens,ec?.percent,ec?.contextWindow]),{data:g,loading:v,error:y,activeLeafId:k,messages:S,entryIds:I,streamState:N,agentRunning:R,modelNames:z,modelList:F,modelError:_,modelScopeWarnings:O,modelThinkingLevels:U,modelThinkingLevelMaps:V,modelRoles:J,newSessionModel:Y,toolPreset:en,thinkingLevel:ei,effectiveThinkingLevel:ea,retryInfo:el,contextUsage:ec,systemPrompt:ep,forkingEntryId:em,isCompacting:ej,compactError:eC,compactResult:eT,currentModel:tV,displayModel:tK,modelSwitching:ew,sessionStats:tJ,slashCommands:eE,slashCommandsLoading:eL,queuedMessages:e0,subagents:e2,todoPhases:e4&&e4.sid===tr.current?e4.phases:null,notices:eP.visible,extensionDialog:eH,extensionResponse:eq,extensionCustomUi:eJ,extensionStatuses:eY,extensionWidgets:eX,respondToExtensionUi:nr,sendExtensionCustomInput:ni,isAutoModelSelection:m&&null===Y,agentPhase:eM,isNew:m,autoFollowPaused:tj,resumeAutoFollow:nB,goalStatus:tC,sessionIdRef:tr,eventSourceRef:e6,messagesEndRef:tE,scrollContainerRef:t$,handleSend:ny,handleAbort:nw,handleFork:nk,handleNavigate:nj,handleModelChange:nC,handleRoleModelChange:nT,handleMainPresetChange:nI,newSessionAccount:X,handleCompact:nN,handleSteer:nE,handleFollowUp:nL,handlePromptWithStreamingBehavior:n$,handleAbortCompaction:nA,handleRecallQueue:nP,handleBuiltinSlashCommand:nR,handleToolPresetChange:nW,handleThinkingLevelChange:nz,loadTools:t8,loadSlashCommands:t6,ensureNewSession:t5,refreshLiveTranscript:t1,setActiveLeafId:j,setData:x,setMessages:C,dispatch:M,setAgentRunning:E,setForkingEntryId:eg,bashRunning:$,pendingBash:A,handleAgentEventRef:tv}}({session:e,newSessionCwd:t,initialData:s,transitioning:a,onAgentEnd:ed,onAttentionNeeded:l,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),tI=ng(e?.id,eU?.provider,void 0),tT=tI?.alias;(0,i.useEffect)(()=>{tT&&B.current?.(tT)},[tT]);let tN=(0,i.useMemo)(()=>{if("auto"!==eM||!eU)return null;let e=e9?th:tV.find(e=>e.alias===tI?.alias)?.oauthPosition;return tV.find(t=>t.provider===eU.provider&&t.model===eU.modelId&&(void 0===t.oauthPosition||t.oauthPosition===e))?.alias??null},[eU,e9,th,tI,eM]),tM=ex||ev,tR=e?.id;J.current=eh,G.current=em,Y.current=tr;let tE=(0,i.useRef)(!0);tE.current=!te;let t$=(0,i.useRef)(!1);(0,i.useEffect)(()=>{ex&&!t$.current&&(Z.current+=1),t$.current=ex},[ex]),(0,i.useEffect)(()=>()=>{Z.current+=1},[]),(0,i.useEffect)(()=>{q(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(sB(e))??"[]");if(!Array.isArray(t))return[];return t.filter(e=>e&&"string"==typeof e.anchorEntryId).map(t=>({..."string"==typeof t.sticker?{...t,sticker:t.sticker.replace(/^(\/stickers\/.+)\.png$/,"$1.webp")}:t,sessionId:e}))}catch{return[]}}(tR),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===tR)])},[tR]),(0,i.useEffect)(()=>{let e=tr.current;e&&V.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&q(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let s=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let s=0;for(let a=i;a<r;a++)if(rW(t[a])===e.identity&&(s+=1)===e.occurrence)return{kind:"entry",entryId:n[a]};return null}(i.intent,eh,em);if(null===s){r.push(i);continue}n=!0,"drop"!==s.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===s.entryId)||r.push({id:i.id,anchorEntryId:s.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(sO(e,r),r):t})},[eh,em,tr]);let tL=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tr.current,t=tL.current;if(tL.current=e?{sessionId:e,entryIds:em}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let s=e.length;s<i;s++){let e=n[s];"assistant"===e.role&&"web6"===e.provider&&"ChatGPT 6PRO"===e.model&&r.push(t[s])}return r}(t.entryIds,em,eh),r=ee();if(0===n.length||!r)return;let i=nf(e,"web6",void 0)?.alias??null;for(let e of n)V.current.some(t=>t.anchorEntryId===e)||er(i,"done",r,{kind:"entry",entryId:e})},[em,eh,tr,ee,er]);let tA=ex&&e7?.kind==="running_tools"&&e7.tools.length>0&&e7.tools.every(e=>"wait"===e.name),tP=eu||a,{hideThinkingBlock:tz}=(L=t??e?.cwd??null,P=tB(),(0,i.useEffect)(()=>{t_(L).catch(()=>{})},[L]),P),tW=(0,i.useMemo)(()=>({hideThinking:tz}),[tz]);(0,i.useEffect)(()=>{if(!e0||_.current===e0.id)return;_.current=e0.id;let e=ee();if(e){var t;Q.current=e.turn,es("select"===(t=e0.method)||"ask"===t?"choice":"approval",e,eU?.provider,void 0,"dialog:session-model")}},[e0,eU?.provider,ee,es]),(0,i.useEffect)(()=>(v=tM?to:null,()=>void(v=null)),[tM,to]),(0,i.useEffect)(()=>{S?.(tM)},[S,tM]),(0,i.useEffect)(()=>()=>S?.(!1),[S]),(0,i.useEffect)(()=>{C?.(tA)},[tA,C]),(0,i.useEffect)(()=>()=>C?.(!1),[C]),(0,i.useEffect)(()=>{I?.(null!==e0)},[I,e0]),(0,i.useEffect)(()=>()=>I?.(!1),[I]);let[tF,tD]=(0,i.useState)(50),tO=(0,i.useRef)(null),tH=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tO.current,t=ts.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(tH.current=t.scrollHeight-t.scrollTop,tD(e=>(function(e,t=50){return e+t})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[tF,eh.length,ts]),(0,i.useEffect)(()=>{if(null==tH.current)return;let e=ts.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-tH.current),tH.current=null}},[tF,ts]);let tU=eK?[eK.sessionId,eK.sessionFile??"",eK.sessionName??"",eK.userMessages,eK.assistantMessages,eK.toolCalls,eK.toolResults,eK.totalMessages,eK.tokens.input,eK.tokens.output,eK.tokens.cacheRead,eK.tokens.cacheWrite,eK.tokens.total,eK.cost??0,eK.totalActiveMs??0].join("|"):null,tq=(0,i.useRef)(eK);tq.current=eK,(0,i.useEffect)(()=>{f?.(tq.current)},[tU,f]),(0,i.useEffect)(()=>()=>{f?.(null)},[f]);let tK=eA?`${eA.percent??"null"}|${eA.contextWindow}|${eA.tokens??"null"}`:null,tJ=(0,i.useRef)(eA);tJ.current=eA,(0,i.useEffect)(()=>{x?.(tJ.current)},[tK,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(eZ)},[b,eZ]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{isDragOver:tG,handleDragEnter:tY,handleDragOver:tZ,handleDragLeave:tX,handleDrop:tQ}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:a,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(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{tM||p?.current?.addAttachments(e)},[tM,p])),t0=(0,i.useMemo)(()=>{let e=new Map;for(let t of eh)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[eh]),t1=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=eh.length-1;n>=0;n-=1){let r=function(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n=(n_(t)?.message??t).trim();return n.length>0?n:null}(eh[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[eh]),t2=(0,i.useMemo)(()=>(function(e,t,n=null){return n||function(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if("assistant"!==r.role)continue;let i=r.content;if(Array.isArray(i))for(let e=i.length-1;e>=0;e-=1){let n=i[e];if("toolCall"!==n.type||!function(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}(n.toolName))continue;let r=eq(n,t.get(n.toolCallId));if("unknown"!==r.kind)return r.phases}}return null}(e,t)})(eh,t0,eX),[eh,t0,eX]),t8=(0,i.useMemo)(()=>rJ(eg.streamingMessage).join("|"),[eg.streamingMessage]),t4=(0,i.useMemo)(()=>JSON.stringify(rK(eg.streamingMessage)),[eg.streamingMessage]),t5=(0,i.useMemo)(()=>JSON.stringify(rY(eg.streamingMessage)),[eg.streamingMessage]),t6=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let s=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),a=[],o=new Map,l=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){l=n;continue}let i=rJ(r),d=rY(r,s);if(0===i.length&&0===d.length||l<0)continue;let c=rK(r),u=o.get(l);u||(u={index:l,entryId:t[l],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(l,u),a.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...c],u.peerSends=[...u.peerSends,...d]}if(n.length>0||i.length>0){let s=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){s=t;break}if(s>=0){let e=o.get(s);e||(e={index:s,entryId:t[s],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(s,e),a.push(e));let l=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!l.has(e))];let d=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!d.has(`${e.toolCallId} ${e.name??""}`))];let c=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...i.filter(e=>!c.has(e.toolCallId))]}}return a.sort((e,t)=>e.index-t.index)})(eh,em,t8.length>0?t8.split("|"):[],JSON.parse(t4),JSON.parse(t5)),[eh,em,t8,t4,t5]),t3=e?.id??tr.current??void 0,t7=(z=ii(A=(0,i.useMemo)(()=>({sessionId:t3,sessionProvider:eU?.provider,turns:t6,messages:eh,subagents:eZ}),[t3,eU?.provider,t6,eh,eZ])),W=il(A),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=t.get(n.turnIndex);e?e.push(n):t.set(n.turnIndex,[n])}return t})(function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.speakerId===n.speakerId&&e.turnIndex===n.turnIndex&&e.text===n.text){t[t.length-1]=n;continue}t.push(n)}return t}([...z,...W])),[z,W])),t9=e9&&0===eh.length&&!eg.isStreaming&&!tM,nt=e?.cwd??t??void 0,nn=eU?eS[`${eU.provider}:${eU.modelId}`]??null:null,nr=eU?eC[`${eU.provider}:${eU.modelId}`]??null:null,ni=(0,i.useRef)(null),ns=(0,i.useRef)(null),na=(0,i.useCallback)(()=>{ni.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(j?.(na),()=>j?.(null)),[na,j]),(0,i.useLayoutEffect)(()=>{let e=ns.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=()=>{let n=Math.ceil(e.getBoundingClientRect().height);n>0&&t.style.setProperty("--omp-dock-h",`${n}px`)};n();let r=new ResizeObserver(n);return r.observe(e),()=>r.disconnect()},[eu]);let no=(0,r.jsx)("div",{ref:ni,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(ss,{ref:p,sessionId:e?.id??tr.current??void 0,onEnsureSession:e9&&t?tS:void 0,onLiveTranscriptPersisted:tC,onSend:ta,onAbort:to,onSteer:ex?tf:void 0,onFollowUp:ex?tg:void 0,onPromptWithStreamingBehavior:ex?tx:void 0,isStreaming:tM,model:eU,isAutoModelSelection:e3,modelNames:ey,modelList:ew,modelError:ek,modelScopeWarnings:ej,onModelChange:tc,onMainPresetChange:e||e9?tp:void 0,mainPresetActiveAlias:tN,modelRoles:eI,onRoleModelChange:tu,modelSwitching:eV,onCompact:e||e9?tm:void 0,onAbortCompaction:tv,isCompacting:eB,compactError:eO,compactResult:eH,toolPreset:eN,onToolPresetChange:e||e9?tw:void 0,thinkingLevel:eM,effectiveThinkingLevel:e$,onThinkingLevelChange:e||e9?tk:void 0,availableThinkingLevels:nn,thinkingLevelMap:nr,retryInfo:eL,queuedMessages:eY,inputHistory:t1,onRecallQueue:tb,slashCommands:eJ,slashCommandsLoading:eG,onLoadSlashCommands:tj,onBuiltinCommand:ty,soundEnabled:T,onSoundToggle:N,onAudioUnlock:$,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),nl=eg.streamingMessage,nd=(0,i.useMemo)(()=>nl?eR(nl,{isStreaming:!0}):[],[nl]),nc=(0,i.useMemo)(()=>nd.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[nd]),nu=(0,i.useMemo)(()=>nd.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[nd]),np=nl?.role==="assistant"?nl:null,nh=ex&&(e7?.kind==="running_tools"||(np?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),nm=np?.provider??eU?.provider,nx=np?.credentialId,nv=np?.provider?`stream:${np.provider}/${np.model}`:`session-model:${eU?.provider}/${eU?.modelId}`;(0,i.useEffect)(()=>{if(!nh)return;let e=ee();e&&X.current!==e.turn&&Q.current!==e.turn&&(X.current=e.turn,es("working",e,nm,nx,nv))},[nh,nm,nx,nv,ee,es]);let[nb,ny]=(0,i.useState)(null),nw=(0,i.useCallback)(e=>{ny(e)},[]),nk=(0,i.useMemo)(()=>eb?{role:"bashExecution",command:eb.command,output:"",excludeFromContext:eb.excludeFromContext}:null,[eb]),nj=(0,i.useMemo)(()=>{let e=[ex&&!nl&&e7?function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?t("chat.runningTool"):1===n.length?t("chat.runningNamedTool",{name:n[0]}):n.length<=3?t("chat.runningTools",{names:n.join(", ")}):t("chat.runningToolsMore",{names:n.slice(0,2).join(", "),count:n.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(e7,F):null,ev&&!eb?F("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[ex,nl,e7,ev,eb,F]);(0,i.useEffect)(()=>{if(!nb)return void y?.(null);let e=[],t=[],n=0;if(nl&&nu.length>0){let r=nb.messages.length+e.length;for(let i of(e.push(nl),nu))t.push({idx:r,blocks:i}),n+=eE(i)}if(nk&&(t.push({idx:nb.messages.length+e.length}),e.push(nk)),0===t.length)return void y?.(nj?{...nb,status:nj}:nb);let r=-1;for(let e=nb.messages.length-1;e>=0;e--)if(e_(nb.messages[e])){r=e;break}let i=nb.groups.slice(),s=i.length>0?i[i.length-1]:void 0;s&&s.anchorIdx===r?i[i.length-1]={...s,entries:[...s.entries,...t],messageCount:s.messageCount+t.length,toolCallCount:s.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),y?.({...nb,groups:i,messages:[...nb.messages,...e],status:nj})},[nb,nu,nl,nk,nj,y]),(0,i.useEffect)(()=>()=>y?.(null),[y]);let nS=e4.filter(e=>"belowEditor"!==e.placement),nC=e4.filter(e=>"belowEditor"===e.placement);return ep?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ep}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":tP,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:tY,onDragOver:tZ,onDragLeave:tX,onDrop:tQ,children:[tP?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:F("chat.loadingSession")})}):null,tG&&!tM&&(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,r.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:F("chat.attachFile")})}),e2&&(0,r.jsx)(sY,{request:e2,onInput:e6}),t9&&!k?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto px-4 py-8",children:(0,r.jsxs)("div",{className:"w-full max-w-[820px]",children:[(0,r.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(H,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.5.9"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.3.5"]})]})]})]}),(0,r.jsx)(sK,{notices:eQ,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[k&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:k}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!k,style:{display:k?"none":"flex"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(sK,{notices:eQ,floating:!0,align:"right"})})}),(0,r.jsx)("div",{ref:ts,className:"chat-session-scroll min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(sV,{widgets:nS}),(0,r.jsx)(rO,{utterances:t7,children:(0,r.jsx)(sH,{messages:eh,entryIds:em,toolResultsMap:t0,modelNames:ey,messageCwd:nt,onOpenFile:w,sessionBusy:tM,isNew:e9,isStreaming:eg.isStreaming,displayOptions:tW,handleFork:tl,forkingEntryId:eP,handleNavigate:td,handleEditContent:ec,sessionId:e?.id??tr.current??void 0,visibleCount:tF,sentinelRef:tO,t:F,cues:U,cueFollowRef:tE,onProcessLogChange:nw})}),eg.isStreaming&&eg.streamingMessage&&nc.length>0&&(0,r.jsx)(n4,{message:eT(eg.streamingMessage,nc),sessionId:e?.id??tr.current??void 0,isStreaming:!0,modelNames:ey,cwd:nt,onOpenFile:w}),(0,r.jsx)("div",{ref:ti})]})})}),tM&&te&&(0,r.jsxs)("button",{type:"button",onClick:tt,"aria-label":F("chat.jumpToBottom"),title:F("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},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",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),F("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:ns,className:"relative chat-composer-dock",children:[e0&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(sG,{request:e0,onRespond:e5,delivery:e1})})}),(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsxs)("div",{style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(sq,{goal:tn,t:F}),(0,r.jsx)(sV,{widgets:nC}),t2&&(0,r.jsx)(so,{phases:t2})]})}),no,(0,r.jsx)(sa,{statuses:e8})]})]})}function sq({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:iz(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:iz(e.tokensUsed)});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:n?.7:1},children:[(0,r.jsx)("span",{style:{color:n?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:n?t("chat.goalPaused"):e.status}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function sV({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,r.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function sK({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let s="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function sJ({focusKey:e,label:t,labelledBy:n,maxBlockSize:s="min(56dvh, 620px)",onCancel:a,delivery:o,children:l}){let{t:d}=(0,E.s)(),c=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!c.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=c.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let n=document.activeElement;(null===n||n===document.body||e?.contains(n))&&t.focus()}},[e]),(0,r.jsxs)("div",{ref:c,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:a?e=>{"Escape"===e.key&&(e.stopPropagation(),a())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:s},children:[o?(0,r.jsx)("p",{className:"chat-response-delivery",role:"failed"===o.status?"alert":"status","data-state":o.status,children:"sending"===o.status?d("chat.responseSending"):`${d("chat.responseFailed")}${o.error?` (${o.error})`:""}`}):null,l]})}function sG({request:e,onRespond:t,delivery:n}){let{t:s}=(0,E.s)(),[a,o]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[l,d]=(0,i.useState)({}),[c,u]=(0,i.useState)({}),[p,h]=(0,i.useState)("");(0,i.useEffect)(()=>{if(o("editor"===e.method?e.prefill??"":""),h(""),u({}),"ask"!==e.method)return void d({});let t={};for(let n of e.questions)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];d(t)},[e]);let m=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:a})};if("ask"===e.method){let i=e.questions.every(e=>(l[e.id]?.length??0)>0||(c[e.id]?.trim().length??0)>0),a=()=>{i&&t(e,{value:JSON.stringify({kind:"submit",results:e.questions.map(e=>{let t=c[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(l[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})})})};return(0,r.jsx)(sJ,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:n,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")})]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let i=l[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let a=i.includes(n),o=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":a,onClick:()=>{var e,r;return e=t.id,r=t.multi??!1,void d(t=>{let i=t[e]??[],s=r?i.includes(n)?i.filter(e=>e!==n):[...i,n]:[n];return{...t,[e]:s}})},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${a?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:a?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${a?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:a?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:a&&(t.multi?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:a?600:500},children:e.label}),e.description&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),a&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),o&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:c[t.id]??"",onChange:e=>u(n=>({...n,[t.id]:e.target.value})),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&a()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!i||n?.status==="sending",onClick:a,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:i&&n?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:i&&n?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:i&&n?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:n?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(sJ,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:n,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(tR,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:p,onChange:e=>h(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:p.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(sJ,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:n,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:a,placeholder:e.placeholder,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&m()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===e.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:a,onChange:e=>o(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&m()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:m,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:m,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.submit")}):null]})]})})}function sY({request:e,onInput:t}){let{t:n}=(0,E.s)(),s=(0,i.useRef)(null),a=(0,i.useRef)(!1),o=eb(e.lines);return(0,i.useEffect)(()=>{s.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||s.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:s,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=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=ek[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":" ":ew[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:n=>{a.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{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:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\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:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,n)=>{var s;return(0,r.jsxs)(i.Fragment,{children:[(s=`line-${t}`,ey(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${s}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}var sZ=n(50640),sX=n(73620);let sQ=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function s0(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)}let s1=["tags","categories","keywords","tag","category"];function s2({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,s=s1.find(t=>Array.isArray(e[t])),a=s?e[s].map(s0).filter(Boolean):[],o=n.filter(([e])=>e!==s&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),a.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:a.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),o.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:o.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=s0(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}(t)})]},e))})]})}let s8={source:"Source",preview:"Preview",diff:"Diff"},s4={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},s5={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)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function s6(){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 s3(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function s7(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=s3(n.startContainer),i=s3(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),a=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(a))return null;if(s<a){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]")&&(a=Number((i=e).dataset.lineNumber))}}}return s>a?null:{startLine:s,endLine:a}}function s9({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,s)=>{let a=e.children??[],o=a[0]?.properties?.className,l=Array.isArray(o)&&o.includes("react-syntax-highlighter-line-number"),d=l?a[0]:null,c=l?a.slice(1):a;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":s+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,sZ.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${s}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,r)=>(0,sZ.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${s}-${r}`}))})]},`source-line-${s}`)})}function ae(e,t,n,r={}){let i=eY(e),s=new URLSearchParams({type:t});for(let[e,t]of(n&&s.set("sessionId",n),Object.entries(r)))void 0!==t&&s.set(e,String(t));return`/api/files/${i}?${s.toString()}`}function at({filePath:e,sourceSessionId:t}){let{t:n}=(0,E.s)();return(0,r.jsx)("a",{href:ae(e,"download",t),download:eZ(e),title:n("i18n.downloadFile"),"aria-label":n("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 an(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ar({patch:e}){let t,{t:n}=(0,E.s)(),i=(t=nb(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[];if(!i.some(e=>"unchanged"!==e.type))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:n("i18n.noChanges")});let s=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),a=new Set;for(let e of s)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)a.add(t);let o=[],l=0;for(;l<i.length;)if(a.has(l)){let e=[];for(;l<i.length&&a.has(l);)e.push(i[l]),l++;o.push({hidden:!1,lines:e})}else{let e=0;for(;l<i.length&&!a.has(l);)e++,l++;o.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...s4},children:o.map((e,t)=>{if(e.hidden)return(0,r.jsxs)("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:["... ",e.count," unchanged lines ..."]},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",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="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:s5,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:s,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function ai({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,E.s)(),[a,o]=(0,i.useState)(!1),[l,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=eZ(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),f(null),o(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(ae(e,"watch",n));return g.current=t,t.addEventListener("connected",()=>o(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}d(e=>e+1)}),t.addEventListener("error",()=>o(!1)),t.onerror=()=>o(!1),()=>{t.close(),g.current=null}},[e,n]);let v=ae(e,"read",n,l?{v:l}:void 0),b=null!=c?an(c):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:e,children:eX(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||"image"}),p&&(0,r.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),b&&(0,r.jsx)("span",{children:b}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"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)(at,{filePath:e,sourceSessionId:n})]}),(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:m?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:m}):(0,r.jsx)("img",{src:v,alt:e,onLoad:e=>{let t=e.currentTarget;h({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>f("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function as({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,E.s)(),[a,o]=(0,i.useState)(!1),[l,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=eZ(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),f(null),o(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(ae(e,"watch",n));return g.current=t,t.addEventListener("connected",()=>o(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}h(null),f(null),d(e=>e+1)}),t.addEventListener("error",()=>o(!1)),t.onerror=()=>o(!1),()=>{t.close(),g.current=null}},[e,n]);let v=ae(e,"read",n,l?{v:l}: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:e,children:eX(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||"audio"}),null!=p&&(0,r.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}(p)}),null!=c&&(0,r.jsx)("span",{children:an(c)}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"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)(at,{filePath:e,sourceSessionId:n})]}),(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:[m&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:m}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:v,onLoadedMetadata:e=>h(e.currentTarget.duration),onError:()=>f("Failed to load audio"),style:{width:"100%"}},v)]})})]})}function aa({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,E.s)(),[a,o]=(0,i.useState)(!1),[l,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),m=(0,i.useRef)(null),f=eC(e),g="pdf"===f,x=g?ae(e,"read",n,l?{v:l}:void 0):ae(e,"preview",n,l?{v:l}:void 0);return(0,i.useEffect)(()=>{d(0),u(null),h(null),o(!1),m.current&&(m.current.close(),m.current=null),fetch(ae(e,"meta",n)).then(e=>e.json()).then(e=>{e.error&&h(e.error),"number"==typeof e.size&&(u(e.size),!g&&e.size>0xa00000&&h("DOCX too large for preview (>10MB)"))}).catch(e=>h(String(e)));let t=new EventSource(ae(e,"watch",n));return m.current=t,t.addEventListener("connected",()=>o(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(u(t.size),!g&&t.size>0xa00000))return void h("DOCX too large for preview (>10MB)")}catch{}h(null),d(e=>e+1)}),t.addEventListener("error",()=>o(!1)),t.onerror=()=>o(!1),()=>{t.close(),m.current=null}},[e,g,n]),(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:e,children:eX(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===f?"docx preview":"pdf"}),null!=c&&(0,r.jsx)("span",{children:an(c)}),(0,r.jsx)(at,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)",flexShrink:0},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)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,r.jsx)("iframe",{src:x,sandbox:g?void 0:"allow-same-origin",title:s("i18n.previewFile",{file:eZ(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function ao({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:o,initialDisplayMode:l}){let d;return eI(e)?(0,r.jsx)(ai,{filePath:e,cwd:t,sourceSessionId:n}):null!==(eS[eC(e)]??null)?(0,r.jsx)(as,{filePath:e,cwd:t,sourceSessionId:n}):null!==("pdf"===(d=eC(e))||"docx"===d?d:null)?(0,r.jsx)(aa,{filePath:e,cwd:t,sourceSessionId:n}):(0,r.jsx)(al,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:o,initialDisplayMode:l})}function al({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:s,onMentionLines:a,onAtMention:o,gitRefreshKey:l,initialDisplayMode:d}){let c,u,{isDark:p}=tC(),{t:h}=(0,E.s)(),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[y,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(null),[S,C]=(0,i.useState)("source"),[I,T]=(0,i.useState)(!1),[N,M]=(0,i.useState)(!1),R=(0,i.useRef)(null),$=(0,i.useRef)(0),L=(0,i.useRef)(null),[A,P]=(0,i.useState)(null),z=(0,i.useCallback)(e=>fetch(ae(e,"read",n)).then(e=>e.json()).then(e=>e.error?(j(e.error),null):(j(null),f(e),e)).catch(e=>(j(String(e)),null)),[n]),W=(0,i.useCallback)(async e=>{let n=++$.current;if(b(!0),!t){x(null),b(!1);return}try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(n!==$.current)return;x(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch{n===$.current&&x(null)}finally{n===$.current&&b(!1)}},[t]);(0,i.useEffect)(()=>{w(!0),j(null),f(null),x(null),C("source"),T(!1),M(!1),R.current&&(R.current.close(),R.current=null),z(e).finally(()=>w(!1));let t=new EventSource(ae(e,"watch",n));return R.current=t,t.addEventListener("connected",()=>{M(!0)}),t.addEventListener("change",()=>{z(e),W(e)}),t.addEventListener("error",()=>{M(!1)}),t.onerror=()=>{M(!1)},()=>{t.close(),R.current=null}},[e,z,W,n]),(0,i.useEffect)(()=>{W(e)},[W,e,l]),(0,i.useEffect)(()=>{(m?.language==="markdown"||m?.language==="html")&&"diff"!==d&&C("preview")},[m?.language,d]);let F=g?.supported===!0&&"string"==typeof g.patch,D=F&&"deleted"===g.status;(0,i.useEffect)(()=>{F||"diff"!==S||C("source")},[S,F]),(0,i.useEffect)(()=>{D&&R.current&&(R.current.close(),R.current=null,M(!1))},[D]);let _=(0,i.useRef)(!1);(0,i.useEffect)(()=>{_.current=!1},[e]),(0,i.useEffect)(()=>{"diff"===d&&F&&!_.current&&(_.current=!0,C("diff"))},[d,F]);let B=(0,i.useMemo)(()=>m?.language==="markdown"?e3(m.content):"",[m]),O=(0,i.useMemo)(()=>m?.language==="markdown"?function(e){let t=function(e){let t=sQ.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,sX.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(m.content):null,[m]);(0,i.useEffect)(()=>{let e=()=>{let e=L.current;P(a&&"source"===S&&e?s7(e,window.getSelection()):null)};if(e(),a&&"source"===S)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[m?.content,S,a]);let H=(0,i.useCallback)(n=>{a&&n&&a(eX(e,t),n.startLine,n.endLine)},[t,e,a]);if((0,i.useEffect)(()=>{if(!a||"source"!==S)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=L.current,r=n?s7(n,window.getSelection()):null;r&&(e.preventDefault(),H(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[S,H,a]),y||"diff"===d&&v&&!m)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:h("i18n.loading")});if(k&&!D)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:k});if(!m&&!D)return null;let U=m?.language??"text",q=m?.content??"",V="html"===U,K="markdown"===U,J=(u=(c=eG(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===u?"/":2===u&&/^[a-zA-Z]:\//.test(c)?c.slice(0,3):c.slice(0,u),G=q.split("\n"),Y=D?"diff":S,Z=D?["diff"]:["source",...V||K?["preview"]:[],...F?["diff"]:[]],X=D?h("files.deleted"):`${U} \xb7 ${G.length} lines \xb7 ${an(m.size)}`;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},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:e,children:eX(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:X,children:X}),!D&&(0,r.jsx)("span",{title:N?h("i18n.liveSync"):h("i18n.notWatching"),"aria-label":N?h("i18n.liveSync"):h("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:N?"#4ade80":"var(--border)",boxShadow:N?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[Z.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":h("i18n.fileViewMode"),children:Z.map(e=>{let t=Y===e;return(0,r.jsx)("button",{type:"button",onClick:()=>C(e),title:"diff"===e?h("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:s8[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(o||a)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{A&&a?H(A):o?.(eX(e,t),!1)},title:A&&a?`${h("i18n.mentionSelectedLines")} (L${A.startLine}${A.startLine!==A.endLine?`-L${A.endLine}`:""})`:h("files.insertPath"),"aria-label":h("files.mention"),disabled:!o&&!a,className:"file-viewer-icon-button",children:(0,r.jsx)(s6,{})}),"source"===Y&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:()=>T(e=>!e),title:I?h("i18n.disableWrap"):h("i18n.enableWrap"),"aria-label":I?h("i18n.disableWrap"):h("i18n.enableWrap"),"aria-pressed":I,className:"file-viewer-icon-button",style:{background:I?"var(--bg-selected)":"transparent",color:I?"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"})]})})})]}),!D&&(0,r.jsx)(at,{filePath:e,sourceSessionId:n})]})]}),(0,r.jsx)("div",{ref:L,className:"file-viewer-content",style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===Y&&F?(0,r.jsx)(ar,{patch:g.patch}):V&&"preview"===Y?(0,r.jsx)("iframe",{srcDoc:q,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:h("i18n.htmlPreview")}):K&&"preview"===Y?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[O?.data&&(0,r.jsx)(s2,{data:O.data}),(0,r.jsx)(eJ.oz,{remarkPlugins:tn,rehypePlugins:ti,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===i?(0,r.jsx)(tT,{code:s.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(tM,{code:s.replace(/\n$/,""),lang:i}):(0,r.jsx)("code",{className:e,...n,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:n,...i}){delete i.node;let a=s?eU(e,J,t??J):null;return a&&s?(0,r.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),s(a))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})},img({src:e,alt:i,...s}){delete s.node;let a="string"==typeof e?eU(e,J,t??J):null,o=a?ae(a,"read",n):e;return(0,r.jsx)("img",{src:o,alt:i??"",loading:"lazy",...s})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})},children:B})]}):(0,r.jsx)(eV.A,{className:I?"file-source-view is-wrapped":"file-source-view",language:"text"===U?"plaintext":U,style:p?eK.xJ:eK.vs,showLineNumbers:!0,lineNumberStyle:{...s5},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...s4,width:I?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:I?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(s9,{...e,wrapLines:I}),wrapLongLines:I,children:q})})]})}function ad({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:s}){let{t:a,locale:o}=(0,E.s)(),[l,d]=(0,i.useState)(null);return(0,r.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===o?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let i=e.id===t;return(0,r.jsxs)("div",{className:`file-tab${i?" is-active":""}`,role:"presentation",onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),s(e.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"tab","aria-selected":i,onClick:()=>n(e.id),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,height:"100%",padding:"0 0 0 12px",border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:nT(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},children:e.label})]}),(0,r.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),s(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:l===e.id?"var(--bg-hover)":"transparent",border:"none",color:l===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:a("i18n.close"),"aria-label":`${a("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)})})}let ac=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],au=new Set(ac);function ap(e){return void 0!==e&&au.has(e)}function ah(e){if(!e)return[...ac];let t=new Set(e);return ac.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function am(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),n=t>=0?e.slice(t+1):void 0;return ap(n)?n:"inherit"}function af(e,t){let n=e.lastIndexOf(":"),r=ap(n>=0?e.slice(n+1):void 0)?e.slice(0,n):e;return"inherit"===t?r:`${r}:${t}`}var ag=n(98795),ax=n.n(ag);function av(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function ab({value:e,options:t,onChange:n,disabled:s=!1,placeholder:a="Select…",searchPlaceholder:o="Search options…",noResultsLabel:l="No matching options",ariaLabel:d,className:c,style:u}){let p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(null),f=(0,i.useRef)([]),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(0),k=(0,i.useId)(),j=t.find(t=>t.value===e),S=(0,i.useMemo)(()=>{let e=av(v.trim());return e?t.filter(t=>av(`${t.label} ${t.value} ${t.searchText??""}`).includes(e)):t},[t,v]);(0,i.useEffect)(()=>{if(!g)return;let e=e=>{p.current?.contains(e.target)||x(!1)};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[g]),(0,i.useEffect)(()=>{g?requestAnimationFrame(()=>m.current?.focus()):b("")},[g]),(0,i.useEffect)(()=>{if(!g)return;let t=S.findIndex(t=>t.value===e&&!t.disabled);w(t>=0?t:Math.max(0,S.findIndex(e=>!e.disabled)))},[S,g,e]),(0,i.useEffect)(()=>{(y>=S.length||S[y]?.disabled)&&w(Math.max(0,S.findIndex(e=>!e.disabled)))},[y,S]),(0,i.useEffect)(()=>{g&&f.current[y]?.scrollIntoView({block:"nearest"})},[y,g]);let{side:C,maxHeight:I}=iD(p,g,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),T=e=>{e.disabled||(n(e.value),x(!1))},N=e=>{if(!S.length)return;let t=y;for(let n=0;n<S.length;n+=1)if(t=(t+e+S.length)%S.length,!S[t].disabled)return void w(t)};return(0,r.jsxs)("div",{ref:p,className:`${ax().root}${c?` ${c}`:""}`,style:u,children:[(0,r.jsxs)("button",{ref:h,type:"button",className:ax().trigger,disabled:s,"aria-label":d,"aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?k:void 0,onClick:()=>x(e=>!e),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),x(!0))},children:[(0,r.jsx)("span",{className:j?ax().value:ax().placeholder,children:j?.label??(e||a)}),(0,r.jsx)("svg",{className:ax().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),g&&(0,r.jsxs)("div",{className:ax().popover,style:"above"===C?{bottom:"calc(100% + 5px)",maxHeight:I}:{top:"calc(100% + 5px)",maxHeight:I},"data-dismissible-layer":"searchable-select",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),x(!1),h.current?.focus())},children:[(0,r.jsxs)("div",{className:ax().searchWrap,children:[(0,r.jsxs)("svg",{className:ax().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,r.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,r.jsx)("input",{ref:m,className:ax().search,value:v,placeholder:o,"aria-label":o,role:"combobox","aria-expanded":"true","aria-controls":k,"aria-activedescendant":S[y]?`${k}-${y}`:void 0,autoComplete:"off",spellCheck:!1,onChange:e=>{b(e.target.value),w(0)},onKeyDown:e=>{if("ArrowDown"===e.key)e.preventDefault(),N(1);else if("ArrowUp"===e.key)e.preventDefault(),N(-1);else if("Enter"===e.key){e.preventDefault();let t=S[y];t&&T(t)}else"Tab"===e.key&&x(!1)}})]}),(0,r.jsx)("div",{id:k,className:ax().options,role:"listbox","aria-label":d,style:{maxHeight:Math.max(0,I-46)},children:S.length?S.map((t,n)=>(0,r.jsxs)("button",{ref:e=>{f.current[n]=e},id:`${k}-${n}`,type:"button",role:"option","aria-selected":t.value===e,className:ax().option,"data-active":n===y,"data-selected":t.value===e,disabled:t.disabled,onMouseEnter:()=>w(n),onClick:()=>T(t),children:[(0,r.jsxs)("span",{className:ax().optionCopy,children:[(0,r.jsx)("span",{className:ax().optionLabel,children:t.label}),t.description&&(0,r.jsx)("span",{className:ax().optionDescription,children:t.description})]}),t.value===e&&(0,r.jsx)("svg",{className:ax().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},t.value)):(0,r.jsx)("div",{className:ax().empty,children:l})})]})]})}let ay=["global","project"];function aw(e){return`${e.provider}/${e.id}`}function ak({cwd:e,onRolesChanged:t}){let{t:n}=(0,E.s)(),[s,a]=(0,i.useState)([]),[o,l]=(0,i.useState)([]),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,m]=(0,i.useState)(!0),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),b=(0,i.useCallback)(async t=>{if(!e){a([]),l([]),c({}),m(!1);return}m(!0),g(null);try{let n=`?cwd=${encodeURIComponent(e)}`,[r,i]=await Promise.all([fetch(`/api/model-roles${n}`,t?{signal:t}:void 0),fetch(`/api/models${n}`,t?{signal:t}:void 0)]);if(!r.ok)throw Error(`HTTP ${r.status}`);let s=await r.json();if(s.error)throw Error(s.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json();a(s.roles??[]),l(o.modelList??[]),c(o.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[e]);(0,i.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]);let y=(0,i.useCallback)(async(n,r)=>{if(e){v(n),g(null);try{let i=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:n,selector:r,scope:u})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);a(s.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>s.filter(e=>!e.hidden),[s]);return e?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:n("roles.title")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n("roles.description")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:n("roles.scope")}),(0,r.jsx)("div",{style:{display:"flex",border:"1px solid var(--border)",borderRadius:6,overflow:"hidden"},children:ay.map(e=>(0,r.jsx)("button",{onClick:()=>p(e),style:{padding:"4px 10px",border:"none",background:u===e?"var(--bg-selected)":"transparent",color:u===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:u===e?600:400},children:"global"===e?n("roles.scopeGlobal"):n("roles.scopeProject")},e))}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:f}),h?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("i18n.loading")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:w.map(e=>{let t=e.resolved?`${e.resolved.provider}/${e.resolved.modelId}`:af(e.selector??"","inherit"),i=am(e.selector),s=ah(d[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("span",{style:{flexShrink:0,minWidth:62,padding:"2px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:n(`roles.source.${e.source}`)})]}),(0,r.jsx)(ab,{value:t,disabled:x===e.role,ariaLabel:e.name,style:{flex:1,minWidth:160},onChange:t=>{if(!t)return void y(e.role,null);let n=o.find(e=>aw(e)===t),r=n?d[`${n.provider}:${n.id}`]:void 0,i=am(e.selector),s=ah(r).includes(i)?i:"inherit";y(e.role,af(t,s))},options:[{value:"",label:n("roles.unset")},...o.map(e=>({value:aw(e),label:`${e.name} — ${e.provider}`,searchText:aw(e)})),...t&&!o.some(e=>aw(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,r.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:n("roles.thinking")}),(0,r.jsx)("div",{role:"group","aria-label":`${e.name} ${n("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:s.map(s=>{let a=i===s;return(0,r.jsx)("button",{type:"button","aria-pressed":a,disabled:x===e.role,title:"inherit"===s?n("roles.thinkingInherit"):s,onClick:()=>{a||y(e.role,af(t,s))},style:{padding:"3px 7px",border:`1px solid ${a?"var(--accent)":"var(--border)"}`,borderRadius:4,background:a?"var(--bg-selected)":"transparent",color:a?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:a?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:s},s)})})]})]},e.role)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("roles.needsProject")})}function aj(e){window.open(e,"_blank","noopener,noreferrer")}var aS=n(67381),aC=n(64433),aI=n(70350),aT=n(88195),aN=n(9312),aM=n(87275),aR=n(22008),aE=n(95476),a$=n(35029),aL=n(14489),aA=n(78728),aP=n(19872),az=n(7751),aW=n(92526),aF=n(48238),aD=n(57794),a_=n(41098),aB=n(84604),aO=n(15315),aH=n(74278),aU=n(55457),aq=n(71437),aV=n(29167),aK=n(97283),aJ=n(34166),aG=n(33889),aY=n(85486),aZ=n(74068),aX=n(83546),aQ=n(83709);let a0={anthropic:{Icon:aS.A,hasColor:!1},openai:{Icon:aC.A,hasColor:!1},"openai-codex":{Icon:aC.A,hasColor:!1},google:{Icon:aI.A,hasColor:!0},"google-vertex":{Icon:aI.A,hasColor:!0},"ant-ling":{Icon:aG.A,hasColor:!0},deepseek:{Icon:aT.A,hasColor:!0},groq:{Icon:aN.A,hasColor:!1},mistral:{Icon:aM.A,hasColor:!0},moonshotai:{Icon:aR.A,hasColor:!1},"moonshotai-cn":{Icon:aR.A,hasColor:!1},moonshot:{Icon:aR.A,hasColor:!1},minimax:{Icon:aE.A,hasColor:!0},"minimax-cn":{Icon:aE.A,hasColor:!0},fireworks:{Icon:a$.A,hasColor:!0},huggingface:{Icon:aL.A,hasColor:!0},cerebras:{Icon:aA.A,hasColor:!0},openrouter:{Icon:aP.A,hasColor:!1},xai:{Icon:az.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:aW.A,hasColor:!0},"cloudflare-workers-ai":{Icon:aW.A,hasColor:!0},"vercel-ai-gateway":{Icon:aF.A,hasColor:!1},"github-copilot":{Icon:aD.A,hasColor:!1},"amazon-bedrock":{Icon:a_.A,hasColor:!0},"azure-openai-responses":{Icon:aB.A,hasColor:!0},"kimi-coding":{Icon:aO.A,hasColor:!0},nvidia:{Icon:aY.A,hasColor:!0},opencode:{Icon:aZ.A,hasColor:!1},"opencode-go":{Icon:aZ.A,hasColor:!1},qwen:{Icon:aH.A,hasColor:!0},xiaomi:{Icon:aX.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:aX.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:aX.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:aX.A,hasColor:!1},zai:{Icon:aQ.A,hasColor:!1},"zai-coding-cn":{Icon:aQ.A,hasColor:!1},zhipu:{Icon:aU.A,hasColor:!0},cohere:{Icon:aq.A,hasColor:!0},perplexity:{Icon:aV.A,hasColor:!0},together:{Icon:aK.A,hasColor:!0},grok:{Icon:aJ.A,hasColor:!1}},a1=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function a2({label:e,children:t}){return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let a8={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 a4({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...a8,fontFamily:i?"var(--font-mono)":"inherit"}})}function a5({value:e,onChange:t,placeholder:n,mono:s,onKeyDown:a,autoComplete:o="off",spellCheck:l=!1,style:d}){let[c,u]=(0,i.useState)(!1),{t:p}=(0,E.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:c?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:a,placeholder:n,style:{...a8,paddingRight:34,fontFamily:s?"var(--font-mono)":"inherit"},autoComplete:o,spellCheck:l}),(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":p(c?"i18n.hideDetails":"i18n.showDetails"),title:p(c?"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:c?(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 a6({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:a8})}function a3({value:e,onChange:t,options:n,required:i}){let{t:s}=(0,E.s)();return(0,r.jsx)(ab,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${s("i18n.default")} / none —`}],...n.map(e=>({value:e,label:e}))]})}function a7({label:e,checked:t,onChange:n}){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:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function a9({children:e}){return(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function oe({name:e,provider:t,onChange:n,onRename:s,onDelete:a,onAddModels:o}){let{t:l}=(0,E.s)(),[d,c]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)([]),x=(0,i.useRef)(0),v=(0,i.useRef)(null);(0,i.useEffect)(()=>c(e),[e]);let b=(e,r)=>n({...t,[e]:r});(0,i.useEffect)(()=>{t.api||n({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{x.current+=1,p({phase:"idle"}),m(""),g([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let n=++x.current;p({phase:"loading"}),g([]);try{let r=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),i=await r.json();if(n!==x.current)return;if(!r.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${r.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==x.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),k="success"===u.phase?u.models:[],j=h.trim().toLocaleLowerCase(),S=k.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),I=C.filter(e=>!w.has(e.id)).map(e=>e.id),T=f.filter(e=>!w.has(e)).length,N=I.length>0&&I.every(e=>f.includes(e)),M=!N&&I.some(e=>f.includes(e));return(0,i.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(a9,{children:l("i18n.provider")}),(0,r.jsx)("button",{onClick:a,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:l("i18n.delete")})]}),(0,r.jsxs)(a2,{label:l("i18n.providerName"),children:[(0,r.jsx)(a4,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,r.jsx)("button",{onClick:()=>s(d.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:4,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:l("i18n.rename")})]}),(0,r.jsx)(a2,{label:"Base URL",children:(0,r.jsx)(a4,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(a2,{label:"API Key",children:[(0,r.jsx)(a5,{value:t.apiKey??"",onChange:e=>b("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(a2,{label:"API",children:(0,r.jsx)(a3,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:a1,required:!0})}),(0,r.jsxs)(a2,{label:"Headers",children:[(0,r.jsx)(os,{headers:t.headers,onChange:e=>b("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,r.jsx)("button",{onClick:y,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?l("models.discoveryFetching"):l("models.discoveryFetch")}),"error"===u.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:u.message}),"success"===u.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:h,onChange:e=>m(e.target.value),placeholder:l("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":l("models.discoveryFilter"),style:{...a8,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:I.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:v,type:"checkbox",checked:N,disabled:0===I.length,onChange:()=>{let e=new Set(I);g(t=>N?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...I])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),l("models.discoverySelectShown")]}),0===C.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:l("models.discoveryNoMatches")}):C.map((e,t)=>{let n=w.has(e.id),i=f.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 g(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:l("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?l("models.discoveryShowing",{shown:C.length,total:S.length}):l("models.discoveryFetched",{count:u.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(f),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(o(t),g([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:T?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",color:T?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?l("models.discoveryAddSelectedCount",{count:T}):l("models.discoveryAddSelected")})]})]})]})]})}let ot=["off","minimal","low","medium","high","xhigh","max"],on={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function or({value:e,onChange:t}){let n=e??{},i=(e,r)=>{let i={...n};"omit"===r?delete i[e]:i[e]=r,t(Object.keys(i).length?i:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:ot.map(e=>{let t=n[e],s=e in n?null===t?"null":"string":"omit",a="string"==typeof t?t:"",o=on[e],l={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)"},d={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",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:o,flexShrink:0,opacity:"null"===s?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===s?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===s?"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:()=>i(e,"omit"),style:{...l,..."omit"===s?d:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...l,borderLeft:"1px solid var(--border)",..."null"===s?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===s?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,a||e),style:{...l,..."string"===s?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:a,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==s&&i(e,a||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===s?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===s?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let oi={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function os({headers:e,onChange:t}){let[n,s]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),a=(0,i.useRef)(n.length),o=e=>{s(e),t(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))},l=(e,t)=>{o(n.map(n=>n.id===e?{...n,...t}:n))},d={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:[n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>l(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...a8,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>l(e.id,{value:t.target.value}),placeholder:"value",style:{...a8,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void o(n.filter(e=>e.id!==t))},style:d,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>s(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:"+ Add header"})]})}function oa({providerName:e,provider:t,model:n,onChange:s,onDelete:a}){let[o,l]=(0,i.useState)({phase:"idle"}),{t:d}=(0,E.s)(),[c,u]=(0,i.useState)({phase:"idle"}),p=(0,i.useRef)(0),h=(0,i.useRef)(null),m=(e,t)=>s({...n,[e]:t}),f=(()=>{if("idle"===o.phase)return null;if("testing"===o.phase)return d("i18n.testingModel");let e=[void 0!==o.latencyMs?`${o.latencyMs}ms`:null,void 0!==o.status?`HTTP ${o.status}`:null].filter(Boolean);return"success"===o.phase?[d("i18n.connected"),...e,o.responseText||null].filter(Boolean).join(" \xb7 "):[d("i18n.failed"),...e,o.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{l({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,i.useEffect)(()=>{p.current+=1,u({phase:"idle"}),h.current=null},[e,t.baseUrl,n.id]);let g=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==o.phase){l({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n})}),i=await r.json();if(!r.ok||!i.ok)return void l({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});l({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){l({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,o.phase]),x=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===c.phase)return;let i=++p.current;u({phase:"loading"});try{let a=new URLSearchParams({q:r,provider:e,limit:"50"});t.baseUrl?.trim()&&a.set("baseUrl",t.baseUrl.trim());let o=await fetch(`/api/models-config/catalog?${a}`),l=await o.json();if(i!==p.current)return;if(!o.ok||l.error||!l.recommendation)return void u({phase:"error",message:l.error??`HTTP ${o.status}`});let d=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=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s=!0,r+=1);s&&(n.cost=i)}return{model:n,appliedCount:r}}(n,l.recommendation.preset);d.appliedCount>0&&(h.current=n,s(d.model)),u({phase:"success",recommendation:l.recommendation,appliedCount:d.appliedCount})}catch(e){if(i!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,n,s,t.baseUrl,e]),v=(()=>{if("success"!==c.phase)return null;let{recommendation:t,appliedCount:n}=c,r=n>0?d("models.catalogFilled",{count:n}):d("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?d("models.catalogNoExactMatch"):d("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?d("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?d("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):d("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),b="error"===c.phase?c.message:v,y="error"===c.phase?"#ef4444":"success"===c.phase&&"unreliable"===c.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(a9,{children:d("i18n.model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,r.jsx)("span",{title:f,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===o.phase?"#fecaca":"success"===o.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===o.phase?"#fee2e2":"success"===o.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:f}),(0,r.jsxs)("button",{onClick:g,disabled:!n.id.trim()||"testing"===o.phase,title:d("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===o.phase?"#16a34a":"none",border:`1px solid ${"success"===o.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===o.phase?"#fff":n.id.trim()&&"testing"!==o.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"testing"!==o.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===o.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"===o.phase?d("i18n.checking"):"success"===o.phase?d("common.ok"):d("i18n.test")]}),(0,r.jsx)("button",{onClick:a,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:d("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(a2,{label:"ID *",children:(0,r.jsx)(a4,{value:n.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(a2,{label:"Name",children:(0,r.jsx)(a4,{value:n.name??"",onChange:e=>m("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void x(),disabled:!n.id.trim()||"loading"===c.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==c.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==c.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===c.phase?d("models.catalogFilling"):d("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:d("models.catalogSource")})]}),(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,r.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,r.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,s(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:d("models.catalogUndo")})]})]}),(0,r.jsx)(a2,{label:"API override",children:(0,r.jsx)(a3,{value:n.api??"",onChange:e=>m("api",e||void 0),options:a1})}),(0,r.jsxs)(a2,{label:"Headers",children:[(0,r.jsx)(os,{headers:n.headers,onChange:e=>m("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to this model's requests; overrides the provider headers for this model."})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(a7,{label:"Reasoning / thinking",checked:n.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,r.jsx)(a7,{label:"Image input",checked:n.input?.includes("image")??!1,onChange:e=>m("input",e?["text","image"]:void 0)})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(a7,{label:"DeepSeek thinking compat",checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...oi}};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}}(n,e))}),(0,r.jsx)(a7,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>s({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(a9,{children:"Thinking level map"}),n.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>m("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",cursor:"pointer"},children:"clear all"})]}),(0,r.jsx)(or,{value:n.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(a2,{label:"Context window (tokens)",children:(0,r.jsx)(a6,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(a2,{label:"Max output tokens",children:(0,r.jsx)(a6,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>m("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(a9,{children:"Cost (per million tokens)"}),(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,r.jsx)(a2,{label:e,children:(0,r.jsx)(a6,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void s({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}function oo({provider:e,onRefresh:t}){let[n,s]=(0,i.useState)({phase:"idle"}),{t:a}=(0,E.s)(),[o,l]=(0,i.useState)(""),d=(0,i.useRef)(null),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===n.phase||"prompt"===n.phase)&&setTimeout(()=>c.current?.focus(),50)},[n.phase]),(0,i.useEffect)(()=>{s({phase:"idle"}),l(""),d.current?.close(),d.current=null},[e.id]),(0,i.useEffect)(()=>()=>{d.current?.close()},[]);let u=(0,i.useCallback)(()=>{d.current?.close(),s({phase:"connecting"}),l("");let n=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);d.current=n,n.onmessage=e=>{let r=JSON.parse(e.data);"auth"===r.type?(s({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),aj(r.url)):"device_code"===r.type?(s({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),aj(r.verificationUri)):"prompt_request"===r.type?s({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?s({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?s({phase:"progress",message:r.message}):"success"===r.type?(n.close(),s({phase:"success"}),t()):"error"===r.type?(n.close(),s({phase:"error",message:r.message})):"cancelled"===r.type&&(n.close(),s({phase:"idle"}))},n.onerror=()=>{n.close(),s(e=>"success"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,t]),p=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),s({phase:"idle"}),t()},[e.id,t]),h=(0,i.useCallback)(async(t,n)=>{if(n.trim()){s({phase:"progress",message:"Verifying…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));s({phase:"error",message:e.error??`Server error ${r.status}`});return}l("")}catch(e){s({phase:"error",message:e instanceof Error?e.message:"Network error"})}}},[e.id]),m=(0,i.useCallback)(async(t,n)=>{s({phase:"progress",message:"Continuing…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));s({phase:"error",message:e.error??`Server error ${r.status}`})}}catch(e){s({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id]),f="connecting"===n.phase||"progress"===n.phase||"auth"===n.phase||"device_code"===n.phase||"prompt"===n.phase||"select"===n.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(a9,{children:a("i18n.subscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:a(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${e.name} account.`}),"connecting"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:a("i18n.openingBrowser")}),"select"===n.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:n.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:n.options.map(e=>(0,r.jsx)("button",{onClick:()=>m(n.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"===n.phase||"prompt"===n.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:"auth"===n.phase?"Complete sign-in in the browser, then copy the redirect URL from the address bar and paste it below.":n.message}),"auth"===n.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:c,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&h(n.token,o)},placeholder:"auth"===n.phase?"http://localhost:1455/auth/callback?code=…":n.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,r.jsx)("button",{onClick:()=>h(n.token,o),disabled:!o.trim(),style:{padding:"6px 12px",background:o.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:o.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:o.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:a("i18n.submit")})]})]}),"device_code"===n.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:"Open the verification page and enter this code:"}),(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:n.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:n.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:n.verificationUri}),n.expiresInSeconds?` Expires in ${Math.ceil(n.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:n.message}),"success"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:a("i18n.connectedSuccessfully")}),"error"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:n.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:f?(0,r.jsx)("button",{onClick:()=>{d.current?.close(),s({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:a("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{onClick:u,style:{padding:"5px 14px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:5,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:12,fontWeight:600},children:a(e.loggedIn?"i18n.relogin":"i18n.login")}),e.loggedIn&&(0,r.jsx)("button",{onClick:p,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:a("i18n.disconnect")})]})})]})}function ol({provider:e,onRefresh:t}){let[n,s]=(0,i.useState)(""),[a,o]=(0,i.useState)(!1),[l,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:m}=(0,E.s)();(0,i.useEffect)(()=>{s(""),u(null),h(!1)},[e.id]);let f=(0,i.useCallback)(async()=>{if(n.trim()){o(!0),u(null),h(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n.trim()})}),i=await r.json();!r.ok||i.error?u(i.error??`HTTP ${r.status}`):(s(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{o(!1)}}},[n,e.id,t]),g=(0,i.useCallback)(async()=>{d(!0),u(null);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),r=await n.json();!n.ok||r.error?u(r.error??`HTTP ${n.status}`):t()}catch(e){u(String(e))}finally{d(!1)}},[e.id,t]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(a9,{children:"API Key"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:m(e.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${e.displayName} API key to enable ${e.modelCount} model${1!==e.modelCount?"s":""}.`}),(0,r.jsx)(a2,{label:"API Key",children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(a5,{value:n,onChange:s,onKeyDown:e=>{"Enter"===e.key&&n.trim()&&f()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:f,disabled:a||!n.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":n.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:p?"#fff":n.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:a||!n.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(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"})}),m(p?"i18n.saved":a?"i18n.saving":"i18n.save")]})]})}),c&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:c}),e.configured&&(0,r.jsx)("button",{onClick:g,disabled:l,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:l?"not-allowed":"pointer",fontSize:12},children:m(l?"i18n.removing":"i18n.disconnect")})]})}function od({id:e,size:t}){let n=a0[e];if(!n){let n=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,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*t)),fontWeight:700,lineHeight:1},children:n})}return n.hasColor?(0,r.jsx)(n.Icon,{size:t}):(0,r.jsx)(n.Icon,{size:t,style:{color:"var(--text-muted)"}})}function oc({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:s,onAddCustom:a,onClose:o}){let[l,d]=(0,i.useState)(""),{t:c}=(0,E.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=l.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),m=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),f=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),g=h.length+m.length+ +!!f,x={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&&o()},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:u,value:l,onChange:e=>d(e.target.value),onKeyDown:e=>{"Escape"===e.key&&o()},placeholder:c("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===g?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:c("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.custom")}),f&&(0,r.jsxs)("button",{onClick:()=>{a(),o()},style:x,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:c("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"})]})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.subscriptions")}),h.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(e.id),o()},style:x,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)(od,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),o()},style:x,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.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(od,{id:e.id,size:28})]},e.id))]})})]})})}function ou({cwd:e,onClose:t,embedded:n=!1,onModelsChanged:s}){let a=W(),{t:o}=(0,E.s)(),[l,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)(!1),[v,b]=(0,i.useState)({type:"roles"}),[y,w]=(0,i.useState)([]),[k,j]=(0,i.useState)([]),[S,C]=(0,i.useState)(!1),I=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>w(e.providers)).catch(()=>{})},[]),T=(0,i.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>j(e.providers)).catch(()=>{})},[]),N=(0,i.useCallback)(()=>{I(),T()},[I,T]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{d(e.providers?e:{...e,providers:{}})}).catch(()=>d({providers:{}})).finally(()=>u(!1)),N()},[N]);let M=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;l.providers?.[e];)e=`new-provider-${t++}`;d(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),b({type:"provider",name:e})},[l.providers]),R=(0,i.useCallback)((e,t)=>{d(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),$=(0,i.useCallback)((e,t)=>{d(n=>{let r=Object.entries(n.providers??{}),i=r.findIndex(([t])=>t===e);return -1===i?n:(r[i]=[t,r[i][1]],{...n,providers:Object.fromEntries(r)})}),b(n=>n?"provider"===n.type&&n.name===e?{type:"provider",name:t}:"model"===n.type&&n.providerName===e?{...n,providerName:t}:n:n)},[]),L=(0,i.useCallback)(e=>{d(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),d(e=>{let t=Object.keys(e.providers??{});return b(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),A=(0,i.useCallback)(e=>{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 b({type:"model",providerName:e,index:n}),t})},[]),P=(0,i.useCallback)((e,t)=>{d(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],s=new Set(i.map(e=>e.id));for(let e of t)s.has(e.id)||(s.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),z=(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}}}})},[]),F=(0,i.useCallback)((e,t)=>{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}}}}),b({type:"provider",name:e})},[]),D=(0,i.useCallback)(async()=>{h(!0),f(null),x(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}),t=await e.json();!e.ok||t.error?f(t.error??`HTTP ${e.status}`):(x(!0),s?.(),setTimeout(()=>x(!1),2e3))}catch(e){f(String(e))}finally{h(!1)}},[l,s]),_=Object.entries(l.providers??{}),B=y.filter(e=>e.loggedIn),O=k.filter(e=>e.configured),H=(()=>{if(!v)return null;if("roles"===v.type)return(0,r.jsx)(ak,{cwd:e??null,onRolesChanged:s});if("oauth"===v.type){let e=y.find(e=>e.id===v.providerId);return e?(0,r.jsx)(oo,{provider:e,onRefresh:N},e.id):null}if("apikey"===v.type){let e=k.find(e=>e.id===v.providerId);return e?(0,r.jsx)(ol,{provider:e,onRefresh:N},e.id):null}if("provider"===v.type){let e=l.providers?.[v.name];return e?(0,r.jsx)(oe,{name:v.name,provider:e,onChange:e=>R(v.name,e),onRename:e=>$(v.name,e),onDelete:()=>L(v.name),onAddModels:e=>P(v.name,e)},v.name):null}let t=l.providers?.[v.providerName],n=t?.models?.[v.index];return n?(0,r.jsx)(oa,{providerName:v.providerName,provider:t,model:n,onChange:e=>z(v.providerName,v.index,e),onDelete:()=>F(v.providerName,v.index)},`${v.providerName}-${v.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},children:(0,r.jsxs)("div",{style:{width:n?"100%":a?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":a?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.models")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,r.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:a?"100%":210,maxHeight:a?"40vh":void 0,borderRight:a?"none":"1px solid var(--border)",borderBottom:a?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,r.jsxs)("div",{onClick:()=>b({type:"roles"}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:v?.type==="roles"?"var(--bg-selected)":"none"},onMouseEnter:e=>{v?.type!=="roles"&&(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{v?.type!=="roles"&&(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:o("roles.title")})]}),(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),B.map(e=>{let t=v?.type==="oauth"&&v.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>b({type:"oauth",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(od,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),O.map(e=>{let t=v?.type==="apikey"&&v.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>b({type:"apikey",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(od,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(B.length>0||O.length>0)&&_.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")}):_.map(([e,t])=>{let n=v?.type==="provider"&&v.name===e,i=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("div",{onClick:()=>b({type:"provider",name:e}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},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)("span",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,n)=>{let i=v?.type==="model"&&v.providerName===e&&v.index===n;return(0,r.jsxs)("div",{onClick:()=>b({type:"model",providerName:e,index:n}),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||o("i18n.newModel")}),t.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)("div",{onClick:t=>{t.stopPropagation(),A(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",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)("span",{style:{fontSize:11},children:["+ ",o("i18n.model")]})})]},e)})]}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,r.jsxs)("button",{onClick:()=>C(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:"100%",padding:"6px 0",background:"none",border:"1px dashed var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:["+ ",o("i18n.addProvider")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:c?null:H??(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectProviderModel")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[m&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:m}),(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:o("i18n.cancel")}),(0,r.jsxs)("button",{onClick:D,disabled:p||g,style:{position:"relative",padding:"6px 16px",minWidth:92,background:g?"#16a34a":p?"var(--bg-panel)":"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:6,color:g?"#fff":p?"var(--text-muted)":"var(--seed-color-fg-neutral-inverted)",cursor:p||g?"default":"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,transition:"background-color 0.2s ease, color 0.2s ease",animation:g?"saved-pop 0.45s ease":void 0},children:[g&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:g?o("i18n.saved"):p?o("i18n.saving"):o("i18n.save")})]})]})]})}),S&&(0,r.jsx)(oc,{oauthProviders:y,apiKeyProviders:k,onSelectOAuth:e=>b({type:"oauth",providerId:e}),onSelectApiKey:e=>b({type:"apikey",providerId:e}),onAddCustom:M,onClose:()=>C(!1)})]})}function op(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function oh(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function om(e){let t=oh(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function of(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function og(e){return e?e.slice(0,8):"unknown"}function ox({enabled:e,loading:t,onToggle:n}){let{t:i}=(0,E.s)();return(0,r.jsx)("button",{onClick:n,disabled:t,title:i(e?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function ov({skill:e,cwd:t,onToggle:n,toggling:i,saveError:s,updateStatus:a,checkingUpdate:o,updating:l,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:p}=(0,E.s)(),h=oh(e),m=!e.disableModelInvocation;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===h?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===h?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:h}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===h&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return op(e)}(e.filePath)}),(0,r.jsx)(ox,{enabled:m,loading:i,onToggle:()=>n(e)})]}),(0,r.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!m&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),s&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:s})]})]}),e.install?.skillsShUrl&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,r.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:og(a?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)("button",{onClick:c,disabled:o||l,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:o||l?"not-allowed":"pointer",opacity:o||l?.5:1,fontSize:11},children:p("i18n.check")}),a?.state==="update-available"&&(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:og(a.latestVersion)}),(o||a&&"update-available"!==a.state)&&(0,r.jsx)("span",{style:{fontSize:12,color:o?"var(--accent)":a?.state==="up-to-date"?"#16a34a":a?.state==="error"?"#ef4444":"var(--text-dim)"},children:o?p("i18n.checking"):a?.state==="up-to-date"?p("i18n.upToDate"):a?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):a?.message||p("i18n.checkFailed")}),a?.state==="update-available"&&(0,r.jsx)("button",{onClick:u,disabled:l||o,style:{padding:"4px 10px",border:"none",borderRadius:5,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:l||o?"not-allowed":"pointer",opacity:l||o?.5:1,fontSize:11,fontWeight:600},children:p(l?"i18n.updating":"i18n.update")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,r.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function ob({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:s}){let{t:a}=(0,E.s)(),[o,l]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(new Set),[w,k]=(0,i.useState)("global"),j=(0,i.useRef)(null);(0,i.useEffect)(()=>{j.current?.focus()},[]);let S=(0,i.useCallback)(async e=>{if(e.trim()){p(!0),m(null),c([]);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 m(n.error);c(n.results??[]),0===(n.results??[]).length&&m("No skills found")}catch(e){m(String(e))}finally{p(!1)}}},[]),C=(0,i.useCallback)(async t=>{g(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);y(e=>new Set(e).add(`${w}:${t}`)),s()}catch(e){v(String(e))}finally{g(null)}},[s,w,e]),I="global"===w?"~/.claude/skills/":`${op(e)}/.claude/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:a("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:j,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(o)},placeholder:a("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)("button",{onClick:()=>S(o),disabled:u||!o.trim(),style:{padding:"7px 16px",fontSize:13,borderRadius:6,border:"none",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:u||!o.trim()?"not-allowed":"pointer",opacity:u||!o.trim()?.5:1,flexShrink:0},children:u?a("i18n.searching"):a("i18n.search")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.jsx)("button",{onClick:()=>{("global"===e||n)&&k(e)},disabled:"project"===e&&!n,title:"project"!==e||n?void 0:a("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||n?"pointer":"not-allowed",background:w===e?"var(--bg-selected)":"none",color:w===e?"var(--text)":"var(--text-dim)",fontWeight:w===e?600:400,opacity:"project"!==e||n?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",I]})]}),h&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),d.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let n=t[w].has(e.package)||b.has(`${w}:${e.package}`),i=f===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)("button",{onClick:()=>!n&&!i&&C(e.package),disabled:n||i||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:n||i||null!==f?"not-allowed":"pointer",background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":i?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:n?`✓ ${a("i18n.installed")}`:i?a("i18n.installing"):a("i18n.install")})]},e.package)})}):!h&&!u&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function oy({cwd:e,onClose:t,embedded:n=!1}){let s=W(),{t:a}=(0,E.s)(),[o,l]=(0,i.useState)([]),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(new Set),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)({}),[j,S]=(0,i.useState)(new Set),[C,I]=(0,i.useState)(!1),[T,N]=(0,i.useState)(null),[M,R]=(0,i.useState)(null),[$,L]=(0,i.useState)(!0),[A,P]=(0,i.useState)({}),z=(0,i.useCallback)(async()=>{c(!0),p(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.skills??[];if(l(r),L(n.projectResourcesLoaded??!0),r.length>0&&!h){let e=r.find(e=>!e.disableModelInvocation)??r[0];m(e.filePath),e.disableModelInvocation&&P(t=>({...t,[om(e)]:!0}))}return r}catch(e){return p(String(e)),[]}finally{c(!1)}},[e,h]);(0,i.useEffect)(()=>{k({}),R(null),z()},[e]);let F=(0,i.useCallback)(async t=>{let n=(t?[t]:o.filter(e=>!!e.install)).map(of).filter(e=>!!e);if(0!==n.length){R(null),S(e=>new Set([...e,...n])),t||I(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);k(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){R(e instanceof Error?e.message:String(e))}finally{S(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||I(!1)}}},[e,o]),D=(0,i.useCallback)(async t=>{if(!t.install)return;let n=of(t);N(n),R(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await z();let s=i.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){R(e instanceof Error?e.message:String(e))}finally{N(null)}},[e,z]),_=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),v(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 v(r.error??`HTTP ${n.status}`);l(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n)),t&&P(t=>({...t,[om(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),B=o.find(e=>e.filePath===h)??null;return(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},children:(0,r.jsxs)("div",{style:{width:n?"100%":s?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":s?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("common.skills")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:op(e)})]}),(0,r.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!$&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:a("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:s?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:s?"100%":210,maxHeight:s?"40vh":void 0,borderRight:s?"none":"1px solid var(--border)",borderBottom:s?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:d?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("i18n.loading")}):u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===o.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:a("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===oh(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===oh(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===oh(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===oh(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===oh(e)}]){let r=o.filter(n);r.length>0&&e.push({label:t,skills:r})}let t=e=>{let t,n,i=!b&&h===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)("div",{onClick:()=>{m(e.filePath),y(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:s?"var(--border)":"var(--accent)",boxShadow:s?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:i?600:400,color:s?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(n=(t=of(e))?w[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:a("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:n})=>{let i=n.filter(e=>!e.disableModelInvocation),s=n.filter(e=>e.disableModelInvocation),o=A[e]??!1;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),i.map(t),s.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{onClick:()=>P(t=>({...t,[e]:!o})),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("span",{style:{fontSize:8},children:o?"▾":"▸"}),a("i18n.dormant")," (",s.length,")"]}),o&&s.map(t)]})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none",color:b?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{b||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b||(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",strokeLinecap:"round",strokeLinejoin:"round",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"})]}),a("i18n.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(ob,{cwd:e,projectResourcesLoaded:$,installedPackages:{global:new Set(o.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(o.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{z()}}):d?null:B?(0,r.jsx)(ov,{skill:B,cwd:e,onToggle:_,toggling:f.has(B.filePath),saveError:x,updateStatus:of(B)?w[of(B)]:void 0,checkingUpdate:!!of(B)&&j.has(of(B)),updating:T===of(B),updateError:M,onCheckUpdate:()=>void F(B),onUpdate:()=>void D(B)},B.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:a("i18n.selectSkill")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[o.some(e=>!!e.install)&&(0,r.jsx)("button",{onClick:()=>void F(),disabled:C||null!==T,style:{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:C||null!==T?"not-allowed":"pointer",opacity:C||null!==T?.5:1,fontSize:12},children:C?a("i18n.checking"):a("i18n.checkUpdates")}),Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?a("i18n.update"):a("i18n.updates")]})]}),(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:a("i18n.close")})]})]})})}function ow(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function ok(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function oj(e){return`${e.scope}\0${e.source}`}function oS(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")}function oC(e,t){let n=[];return e.version&&n.push(t("i18n.installedVersion",{version:e.version})),e.configuredVersion&&n.push(t("i18n.configuredVersion",{version:e.configuredVersion})),n.length?n.join(" \xb7 "):t("i18n.unknown")}function oI(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function oT({pkg:e}){let{t}=(0,E.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:n.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 oN({scope:e}){return(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===e?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===e?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:e})}function oM(e,t){return{padding:"6px 12px",background:t?"rgba(239,68,68,0.08)":"none",border:"1px solid var(--border)",borderRadius:6,color:t?"#ef4444":"var(--text-muted)",cursor:e?"not-allowed":"pointer",fontSize:12,opacity:e?.5:1}}function oR({enabled:e,loading:t,onToggle:n,label:i}){return(0,r.jsx)("button",{type:"button",onClick:n,disabled:t,title:i,"aria-label":i,"aria-pressed":e,style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none",opacity:t?.65:1},children:(0,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function oE({value:e,projectResourcesLoaded:t,onChange:n}){let{t:i}=(0,E.s)();return(0,r.jsx)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:7,overflow:"hidden",height:30},children:["global","project"].map(s=>{let a=e===s,o="project"===s&&!t;return(0,r.jsx)("button",{onClick:()=>{o||n(s)},disabled:o,title:o?i("trust.projectScopeUnavailable"):void 0,style:{width:76,border:"none",borderRight:"global"===s?"1px solid var(--border)":"none",background:a?"var(--bg-selected)":"none",color:a?"var(--text)":"var(--text-muted)",cursor:o?"not-allowed":"pointer",opacity:o?.45:1,fontSize:12},children:s},s)})})}function o$({cwd:e,source:t,scope:n,projectResourcesLoaded:s,busy:a,actionError:o,onSourceChange:l,onScopeChange:d,onInstall:c}){let{t:u}=(0,E.s)(),p=(0,i.useRef)(null);return(0,i.useEffect)(()=>{p.current?.focus()},[]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:u("i18n.addPlugin")}),(0,r.jsxs)("a",{href:"https://github.com/can1357/oh-my-pi#plugins",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},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"})]}),"oh-my-pi plugins"]})]}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"project"===n?`${ow(e)}/.omp/plugins`:"~/.omp/plugins"})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,r.jsx)("input",{id:"plugin-source",ref:p,value:t,onChange:e=>l(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=ok(t);n!==t&&(e.preventDefault(),l(n))},onBlur:e=>l(ok(e.currentTarget.value)),placeholder:"@scope/package or github:user/repo",style:{width:"100%",height:36,padding:"0 11px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,outline:"none"},onKeyDown:e=>{"Enter"===e.key&&t.trim()&&!a&&c()}})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)(oE,{value:n,projectResourcesLoaded:s,onChange:d}),(0,r.jsx)("button",{type:"button",onClick:c,disabled:a||!t.trim(),style:{...oM(a||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:u(a?"i18n.installing":"i18n.install")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>l(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:o})]})}function oL({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:s,sessionId:a,onAction:o,onReloadSession:l}){let{t:d}=(0,E.s)(),c=oj(e),u=n?.endsWith(c)??!1,p="reload"===n,h=!e.disabled;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,r.jsx)(oR,{enabled:h,loading:u||p,onToggle:()=>o(e.disabled?"enable":"disable",e),label:d(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,r.jsx)(oN,{scope:e.scope}),e.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:d("i18n.disabled")}):e.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:d("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>o("update",e),disabled:u||p,style:oM(u||p),children:d(n===`update:${c}`?"i18n.updating":"i18n.update")}),(0,r.jsx)("button",{onClick:l,disabled:!a||p||u,style:oM(!a||p||u),title:d(a?"i18n.reloadSession":"i18n.openSessionToReload"),children:d(p?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)("button",{onClick:()=>o("remove",e),disabled:u||p,style:oM(u||p,!0),children:d(n===`remove:${c}`?"i18n.removing":"i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.status")}),(0,r.jsx)("div",{style:{color:oI(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:oC(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??d("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:oS(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?ow(e.installedPath):d("i18n.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:ow(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:d("i18n.resolvedResources")}),(0,r.jsx)(oT,{pkg:e})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:s}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function oA({cwd:e,sessionId:t,onClose:n,onReloaded:s,embedded:a=!1}){let o=W(),{t:l}=(0,E.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(""),[w,k]=(0,i.useState)("global"),[j,S]=(0,i.useState)(null),[C,I]=(0,i.useState)(null),[T,N]=(0,i.useState)(null),M=(0,i.useMemo)(()=>d?.packages??[],[d?.packages]),R=M.find(e=>oj(e)===f)??null,$=d?.projectResourcesLoaded??!0,L=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:M.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[M]),A=(0,i.useCallback)(async()=>{p(!0),m(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);c(n),v(e=>0===n.packages.length||e),g(e=>e&&n.packages.some(t=>oj(t)===e)?e:n.packages[0]?oj(n.packages[0]):null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,i.useEffect)(()=>{A()},[A]);let P=(0,i.useCallback)(async(t,n)=>{let r=oj(n);S(`${t}:${r}`),I(null),N(null);try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);c(i),"remove"===t?(g(i.packages[0]?oj(i.packages[0]):null),0===i.packages.length&&v(!0),N("Package removed.")):N({install:"Package installed.",update:"Package updated.",disable:"Package disabled.",enable:"Package enabled."}[t])}catch(e){I(e instanceof Error?e.message:String(e))}finally{S(null)}},[e]),z=(0,i.useCallback)(async()=>{let t=ok(b).trim();if(!t)return;y(t);let n=`${w}\0${t}`;S(`install:${n}`),I(null),N(null);try{var r;let i,s,a=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:w,cwd:e})}),o=await a.json();if(!a.ok||o.error)throw Error(o.error??`HTTP ${a.status}`);c(o);let l=(r=o.packages,s=(i=t.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)));g(l?oj(l):n),v(!1),y(""),N("Package installed.")}catch(e){I(e instanceof Error?e.message:String(e))}finally{S(null)}},[e,w,b]),F=(0,i.useCallback)(async()=>{if(t){S("reload"),I(null),N(null);try{await sp(t,{type:"reload"}),s?.(),await A(),N("Session reloaded.")}catch(e){I(e instanceof Error?e.message:String(e))}finally{S(null)}}},[A,s,t]),D=j?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:{position:a?"relative":"fixed",inset:a?void 0:0,width:"100%",height:"100%",zIndex:a?void 0:1e3,background:a?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{a||e.target!==e.currentTarget||n()},children:(0,r.jsxs)("div",{style:{width:a?"100%":o?"calc(100vw - 16px)":860,maxWidth:a?"none":"calc(100vw - 16px)",height:a?"100%":o?"calc(100dvh - 16px)":"76vh",maxHeight:a?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:a?"none":"1px solid var(--border)",borderRadius:8*!a,display:"flex",flexDirection:"column",boxShadow:a?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common.plugins")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ow(e)})]}),(0,r.jsx)("button",{onClick:n,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!$&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:l("trust.pluginsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:o?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:o?"100%":245,maxHeight:o?"40vh":void 0,borderRight:o?"none":"1px solid var(--border)",borderBottom:o?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):h?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===M.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):L.map(e=>(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:e.scope}),e.packages.map(e=>{let t=oj(e),n=!x&&f===t;return(0,r.jsxs)("div",{onClick:()=>{g(t),v(!1),I(null),N(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:oI(e.status)}}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:oS(e,l)}),(e.version||e.configuredVersion)&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:oC(e,l)})]})]},t)})]},e.scope))}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("button",{type:"button",onClick:()=>{v(!0),I(null),N(null)},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,border:"none",width:"100%",cursor:"pointer",background:x?"var(--bg-selected)":"none",color:x?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{x||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{x||(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",strokeLinecap:"round",strokeLinejoin:"round",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"})]}),l("i18n.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,r.jsx)(o$,{cwd:e,source:b,scope:w,projectResourcesLoaded:$,busy:D,actionError:C,onSourceChange:y,onScopeChange:k,onInstall:z}):u?null:R?(0,r.jsx)(oL,{pkg:R,cwd:e,busyKey:j,actionError:C,actionMessage:T,sessionId:t,onAction:P,onReloadSession:F},oj(R)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("i18n.selectPackage")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:d?.diagnostics.length?(0,r.jsxs)("span",{title:d.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:d.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[d.diagnostics.length," diagnostic",1===d.diagnostics.length?"":"s"]}):(0,r.jsx)("span",{children:d?`${d.totals.extensions} ext \xb7 ${d.totals.skills} skills \xb7 ${d.totals.prompts} prompts \xb7 ${d.totals.themes} themes`:""})}),(0,r.jsx)("button",{onClick:()=>void A(),disabled:u||null!==j,style:oM(u||null!==j),children:l("i18n.refresh")}),(0,r.jsx)("button",{onClick:n,style:oM(!1),children:l("i18n.close")})]})]})})}var oP=n(13004),oz=n.n(oP);function oW(){let[e,t]=(0,i.useState)(null),[n,s]=(0,i.useState)(null),[a,o]=(0,i.useState)(null),[l,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[m,f]=(0,i.useState)(""),g=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);t(n),s(null)}catch(e){s(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async(e,n={})=>{u(!0),o(null),d(null);try{let r=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,...n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);return t(i),i}catch(e){return o(e instanceof Error?e.message:String(e)),null}finally{u(!1)}},[]),v=(0,i.useCallback)(async()=>{if(p!==m)return void o("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),f(""),d(`Password saved and password access turned on. The browser will ask for the username "${e.username}" and this password on the next request.`))},[m,p,x]),b=(0,i.useCallback)(async()=>{if(!e)return;let t=await x(e.enabled?"disable":"enable");t&&d(t.enabled?`Password access is on. The browser will ask for the username "${t.username}" and your password on the next request.`:"Password access is off. The stored password is kept and can be switched back on here.")},[x,e]),y=(0,i.useCallback)(async()=>{await x("clear")&&d("The stored password was removed and password access is off.")},[x]);if(!e)return(0,r.jsx)("div",{className:oz().empty,children:n??"Loading password access…"});let w=e.managedByEnvironment,k=!c&&!w&&p.length>=8&&p===m;return(0,r.jsxs)("div",{className:oz().scrollContent,children:[(0,r.jsxs)("header",{className:oz().contentHeader,children:[(0,r.jsx)("h2",{className:oz().contentTitle,children:"Access"}),(0,r.jsxs)("p",{className:oz().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,r.jsx)("code",{children:e.username}),". It is stored as a scrypt hash in ",(0,r.jsx)("code",{children:e.file})," — CUELO never keeps the password itself, which is why forgetting it means recovering rather than reading it back."]}),w&&(0,r.jsxs)("div",{className:oz().readOnlyNotice,children:["Read-only \xb7 ",(0,r.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),l&&(0,r.jsx)("div",{className:oz().reloadNotice,children:(0,r.jsx)("span",{children:l})})]}),(0,r.jsxs)("div",{className:oz().settingsBody,children:[(0,r.jsxs)("section",{className:oz().group,children:[(0,r.jsx)("h3",{className:oz().groupTitle,children:"Password access"}),(0,r.jsxs)("div",{className:oz().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:oz().settingLabel,children:"Require a password"}),(0,r.jsx)("div",{className:oz().settingDescription,children:e.managedByEnvironment?"Every request needs the password from CUELO_PASSWORD.":e.unreadable?"The credential file exists but could not be read, so every request is being refused.":e.configured?e.enabled?"Every request needs the username and password.":"A password is stored but the lock is off.":"No password is set. Anyone who can reach this server can use it."}),!e.configured&&!w&&(0,r.jsx)("div",{className:oz().settingDescription,children:"Set a password below before turning this on."}),a&&(0,r.jsx)("div",{className:oz().error,children:a})]}),(0,r.jsx)("div",{className:oz().settingControl,children:(0,r.jsx)("button",{type:"button",className:oz().switch,"data-on":e.enabled,"aria-pressed":e.enabled,"aria-label":"Require a password",disabled:c||w||!e.enabled&&!e.stored,onClick:()=>void b()})})]})]}),(0,r.jsxs)("section",{className:oz().group,children:[(0,r.jsx)("h3",{className:oz().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,r.jsxs)("div",{className:oz().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:oz().settingLabel,children:"New password"}),(0,r.jsxs)("div",{className:oz().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,r.jsx)("div",{className:oz().settingControl,children:(0,r.jsx)("input",{className:oz().textInput,type:"password",autoComplete:"new-password",value:p,disabled:c||w,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)("div",{className:oz().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:oz().settingLabel,children:"Confirm password"}),(0,r.jsx)("div",{className:oz().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,r.jsx)("div",{className:oz().settingControl,children:(0,r.jsx)("input",{className:oz().textInput,type:"password",autoComplete:"new-password",value:m,disabled:c||w,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key&&k&&v()}})})]}),(0,r.jsxs)("div",{className:oz().editorActions,children:[(0,r.jsx)("div",{children:(0,r.jsx)("div",{className:oz().saveState,children:e.stored&&e.updatedAt?`Last changed ${new Date(e.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[e.stored&&!w&&(0,r.jsx)("button",{type:"button",className:oz().dangerButton,disabled:c,onClick:()=>void y(),children:"Remove password"}),(0,r.jsx)("button",{type:"button",className:oz().primaryButton,disabled:!k,onClick:()=>void v(),children:c?"Saving…":"Save password"})]})]})]}),(0,r.jsxs)("section",{className:oz().group,children:[(0,r.jsx)("h3",{className:oz().groupTitle,children:"If you forget it"}),(0,r.jsxs)("div",{className:oz().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:oz().settingLabel,children:"Recovery"}),(0,r.jsxs)("div",{className:oz().settingDescription,children:["Run ",(0,r.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,r.jsx)("code",{children:"/recover"})," in the browser: CUELO prints a one-time code on its own console, and entering that code sets a new password. Both paths require access to the machine running the server — nothing can hand the password back."]})]}),(0,r.jsx)("div",{className:oz().settingControl,children:(0,r.jsx)("a",{className:oz().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,r.jsxs)("div",{className:oz().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:oz().settingLabel,children:"Basic Auth is not encryption"}),(0,r.jsx)("div",{className:oz().settingDescription,children:"The password crosses the network in a reversible encoding. Over plain HTTP on an untrusted network it can be read in transit, so put CUELO behind HTTPS or a trusted VPN before exposing it beyond loopback."})]}),(0,r.jsx)("div",{className:oz().settingControl})]})]})]})]})}let oF=JSON.parse('{"tabs":{"appearance":"외관","model":"모델","interaction":"상호작용","context":"컨텍스트","memory":"메모리","files":"파일","shell":"Shell","tools":"도구","tasks":"작업","providers":"제공자"},"groups":{"Theme":"테마","Status Line":"상태 표시줄","Display":"표시","Images":"이미지","Thinking":"사고","Sampling":"샘플링","Prompt":"프롬프트","Retry & Fallback":"재시도 및 폴백","Advisor":"어드바이저","Prewalk":"Prewalk","Vision":"비전","Input":"입력","Approvals":"승인","Notifications":"알림","Speech":"음성","Collab":"협업","Magic Keywords":"매직 키워드","Startup & Updates":"시작 및 업데이트","Power (macOS)":"전원 (macOS)","Agent":"에이전트","Git":"Git","General":"일반","Compaction":"압축","Rules (TTSR)":"규칙 (TTSR)","Experimental":"실험적 기능","Auto-Learn":"자동 학습","Mnemopi":"Mnemopi","Hindsight":"Hindsight","Editing":"편집","Reading":"읽기","Read Summaries":"읽기 요약","LSP":"LSP","Bash":"Bash","Eval & Runtimes":"평가 및 런타임","Available Tools":"사용 가능한 도구","Todos":"할 일","Grep & Browser":"Grep 및 브라우저","Computer":"컴퓨터","GitHub":"GitHub","Output Limits":"출력 제한","Execution":"실행","Discovery & MCP":"탐색 및 MCP","Developer":"개발자","Modes":"모드","Subagents":"서브에이전트","Isolation":"격리","Commands & Skills":"명령 및 스킬","Services":"서비스","Fireworks":"Fireworks","Tiny Model":"Tiny Model","Protocol":"프로토콜","Timeouts":"타임아웃","Privacy":"개인정보"},"shell":{"Loading omp settings…":"omp 설정을 불러오는 중…","Settings unavailable":"설정을 사용할 수 없음","Matching canonical /settings entries across every category.":"모든 카테고리에서 표준 /settings 항목을 일치시킨다.","Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.":"표준 omp /settings 값이다. 변경 사항은 공유 에이전트 설정에 즉시 저장된다.","Saved. Reload the active session to apply runtime settings.":"저장됨. 런타임 설정을 적용하려면 활성 세션을 다시 불러온다.","Reloading…":"다시 불러오는 중…","Reload session":"세션 다시 불러오기","No settings match this search.":"이 검색과 일치하는 설정이 없다.","Search /settings":"/settings 검색","Configuration":"구성","OMP settings":"OMP 설정","Close settings":"설정 닫기","Global configuration":"전역 구성","Settings":"설정","Search":"검색","Models":"모델","Themes":"테마","Skills":"스킬","Plugins":"플러그인","MCP":"MCP","Loading themes…":"테마를 불러오는 중…","Themes unavailable":"테마를 사용할 수 없음","Active on web":"웹에서 활성","Preview ":"미리보기 ","The web interface uses the same dark and light theme mappings as omp. Changes are persisted to ":"웹 인터페이스는 omp와 동일한 다크 및 라이트 테마 매핑을 사용한다. 변경 사항은 다음에 저장된다: "," and applied here immediately.":" 그리고 여기에 즉시 적용된다."," mapping":" 매핑","requires a project":"프로젝트가 필요하다"},"fields":{"theme.dark":{"label":"다크 테마","description":"터미널 배경이 어두울 때 사용하는 테마이다"},"theme.light":{"label":"라이트 테마","description":"터미널 배경이 밝을 때 사용하는 테마이다"},"symbolPreset":{"label":"심볼 프리셋","description":"아이콘과 기호에 사용하는 글리프 세트이다 (Unicode, Nerd Font, ASCII)"},"colorBlindMode":{"label":"색맹 모드","description":"diff 추가 표시에 초록색 대신 파란색을 사용한다"},"statusLine.preset":{"label":"상태 표시줄 프리셋","description":"미리 구성된 상태 표시줄 설정이다"},"statusLine.separator":{"label":"상태 표시줄 구분자","description":"세그먼트 사이 구분자의 스타일이다"},"statusLine.sessionAccent":{"label":"세션 강조색","description":"에디터 테두리와 상태 표시줄 여백에 세션 이름 색상을 사용한다"},"statusLine.transparent":{"label":"투명 상태 표시줄","description":"상태 표시줄에 테마의 `statusLineBg` 대신 터미널 기본 배경을 사용한다. Powerline 끝 캡은 주변 터미널로 이어지려면 대비되는 채움색이 필요하므로 제거된다."},"statusLine.compactThinkingLevel":{"label":"간결한 thinking 레벨","description":"thinking 레벨을 별도의 ` \xb7 <level>` 접미사 대신 모델 이름에 아이콘 하나로 표시한다."},"statusLine.showHookStatus":{"label":"hook 상태 표시","description":"상태 표시줄 아래에 hook 상태 메시지를 표시한다"},"terminal.showImages":{"label":"인라인 이미지 표시","description":"터미널에 이미지를 인라인으로 렌더링한다"},"images.autoResize":{"label":"이미지 자동 크기 조정","description":"모델 호환성을 높이기 위해 큰 이미지를 최대 2000x2000으로 축소한다"},"images.blockImages":{"label":"이미지 차단","description":"이미지가 LLM 제공자에게 전송되지 않도록 한다"},"terminal.showProgress":{"label":"네이티브 터미널 진행 표시","description":"에이전트나 컨텍스트 유지 작업이 실행되는 동안 OSC 9;4 부정형 진행 표시를 내보낸다"},"tui.textSizing":{"label":"큰 제목 (Kitty)","description":"Kitty의 OSC 66 text-sizing 프로토콜을 사용해 Markdown H1 제목을 2배 크기로 렌더링한다. Kitty 터미널에서만 적용되며 그 외에서는 무시된다. 기본값은 꺼짐이다."},"tui.renderMermaid":{"label":"Mermaid 다이어그램 렌더링","description":"Mermaid 코드 블록을 ASCII 다이어그램으로 렌더링한다"},"tui.codexResetFireworks":{"label":"Codex 리셋 불꽃놀이","description":"예정에 없던 Codex 주간 사용량 리셋과 새로 적립된 저장 리셋을 화면 상단 1/3의 불꽃놀이 오버레이로 축하하며, Escape를 누를 때까지 유지된다"},"tui.titleState":{"label":"터미널 제목 실행 상태","description":"터미널 제목의 구분자에 에이전트 실행 상태를 표시한다 — 작업 중에는 애니메이션 스피너(Windows에서는 고정된 \':\'), 사용자 차례일 때는 \'>\', 에이전트가 사용자를 기다릴 때는 \'!\'이다"},"tui.hyperlinks":{"label":"터미널 하이퍼링크","description":"터미널 자체의 클릭 열기를 위해 경로와 URL을 OSC 8 하이퍼링크로 감싼다 (auto: 지원 여부 감지, off: 사용 안 함, always: 무조건 사용)"},"tui.tight":{"label":"조밀한 레이아웃","description":"터미널 출력 좌우의 1문자 가로 여백을 제거한다"},"tui.scrollbackRebuild":{"label":"스크롤백 다시 쓰기","description":"블록의 최종 형태가 실시간 미리보기를 대체할 때 터미널 스크롤백을 지우고 다시 출력한다. 꺼짐(기본값)일 때는 오래된 미리보기 사본이 기록에 남고 최종 내용이 그 아래에 추가된다."},"display.shimmer":{"label":"셔머","description":"작업/로딩 메시지의 애니메이션 스타일이다"},"display.smoothStreaming":{"label":"부드러운 스트리밍","description":"청크가 도착하는 동안 어시스턴트 텍스트와 스트리밍되는 도구 입력을 부드럽게 표시한다"},"display.hideToolActivity":{"label":"도구 활동 숨김","description":"모델이 시작한 도구 호출과 결과를 대화 기록에서 숨긴다"},"display.showTokenUsage":{"label":"토큰 사용량 표시","description":"어시스턴트 메시지에 턴별 토큰 사용량을 표시한다"},"display.cacheMissMarker":{"label":"캐시 미스 표시","description":"요청이 프롬프트 캐시를 놓친(miss) 어시스턴트 턴 위에 구분선을 표시한다"},"display.collapseCompacted":{"label":"압축 히스토리 접기","description":"라이브 트랜스크립트에서 compaction 이전 히스토리를 요약 구분선 뒤로 접는다. 비활성화하면 각 compaction 지점에 구분선을 둔 채 전체 트랜스크립트를 인라인으로 유지한다"},"showHardwareCursor":{"label":"하드웨어 커서 표시","description":"IME 지원을 위해 터미널 커서를 표시한다"},"tui.imeSafeCursor":{"label":"IME 안전 프롬프트 레이아웃","description":"macOS IME preedit가 프롬프트 하단 테두리를 밀어내지 못하도록 테두리를 별도 행으로 옮긴다"},"task.showResolvedModelBadge":{"label":"확정 모델 배지 표시","description":"task 위젯 상태줄에 각 subagent가 실제로 사용한 모델 ID를 표시한다"},"advisor.enabled":{"label":"Advisor 활성화","description":"\'advisor\' 역할에 배정된 두 번째 모델을 함께 두어 각 턴을 수동적으로 검토하고 메모를 주입한다."},"prewalk.enabled":{"label":"Prewalk 활성화","description":"활성 모델로 시작한 뒤, plan nudge의 todo 목록이 생성된 이후 첫 edit/write 시점에 빠르고 저렴한 모델(기본값은 \'smol\' 역할)로 전환한다 — 강한 모델이 계획하고 todo를 확정하며 구현을 시작한 후 인계한다. 세션별로 --prewalk / --no-prewalk로 재정의할 수 있다."},"advisor.syncBacklog":{"label":"Advisor 동기화 백로그","description":"advisor가 이 턴 수만큼 뒤처지면 메인 에이전트를 최대 30초 동안 멈춘다. Off로 두면 따라잡기 지연을 비활성화한다."},"advisor.immuneTurns":{"label":"Advisor 면역 턴","description":"advisor의 concern 또는 blocker가 한 번 인터럽트한 뒤에는, 이 primary 턴 수 동안 이후 concern/blocker를 인터럽트 없이 전달한다."},"modelRoleStorage":{"label":"모델 역할 저장소","description":"모델 선택기의 역할 배정이 저장되는 위치이다"},"images.describeForTextModels":{"label":"텍스트 모델용 이미지 설명","description":"vision을 지원하지 않는 모델에 이미지가 첨부되면, 이미지를 버리지 않고 local:// 아래에 저장한 뒤 vision 지원 모델이 만든 설명을 주입한다"},"defaultThinkingLevel":{"label":"Thinking 레벨","description":"thinking을 지원하는 모델의 추론 깊이이다"},"hideThinkingBlock":{"label":"Thinking 블록 숨김","description":"어시스턴트 응답에서 thinking 블록을 숨긴다"},"proseOnlyThinking":{"label":"산문 전용 Thinking","description":"thinking 요약에서 코드 블록을 제외하고 생략 부호로 대체한다"},"omitThinking":{"label":"Thinking 요약 생략","description":"응답에서 thinking 요약을 완전히 생략하도록 업스트림 provider에 지시한다(지원되는 경우)"},"externalThinking":{"label":"외부 Thinking","description":"사용자에게 표시되지 않는 비공개 스크래치패드이다. 지원되는 GPT, Claude, Gemini의 reasoning을 비활성화한다"},"model.loopGuard.enabled":{"label":"Loop Guard","description":"모델 reasoning과 산문에 대한 자동 스트림 루프 감지를 활성화한다"},"model.loopGuard.checkAssistantContent":{"label":"Loop Guard 산문 검사","description":"thinking 로그 외에 어시스턴트 산문 메시지에도 loop guard를 적용한다"},"model.loopGuard.toolCallReminder":{"label":"Loop Guard 도구 호출 알림","description":"Gemini reasoning 스트림이 도구를 호출하지 않고 계획 헤더를 연속으로 다수 출력하면 중단하고 도구 호출을 요구하는 알림을 주입한다(Loop Guard 필요)"},"model.toolCallLoopGuard.enabled":{"label":"도구 호출 Loop Guard","description":"여러 턴에 걸친 동일한 연속 도구 호출을 감지하고 교정용 steer를 주입한다"},"inlineToolDescriptors":{"label":"인라인 도구 디스크립터","description":"시스템 프롬프트에 전체 도구 디스크립터를 렌더링하고 provider 도구 스키마에서 최상위/중첩 description을 제거해 디스크립터 텍스트를 한 번만 전송한다. Auto는 Gemini 모델에서 이를 활성화하고 그 외에는 비활성화한다"},"includeModelInPrompt":{"label":"프롬프트에 모델 포함","description":"에이전트가 자신이 어떤 모델인지 알 수 있도록 시스템 프롬프트에 활성 모델 식별자를 노출한다"},"includeWorkspaceTree":{"label":"워크스페이스 트리 포함","description":"시스템 프롬프트에 워크스페이스 디렉터리 트리를 렌더링한다. 경고: 파일이 수정되면 세션 간 프롬프트 캐싱이 깨질 수 있다."},"personality":{"label":"성격","description":"시스템 프롬프트의 personality 블록에 렌더링되는 의사소통 스타일이다"},"temperature":{"label":"Temperature","description":"샘플링 temperature이다(0 = 결정적, 1 = 창의적, -1 = provider 기본값)"},"topP":{"label":"Top P","description":"Nucleus 샘플링 컷오프이다(0-1, -1 = provider 기본값)"},"topK":{"label":"Top K","description":"상위 K개 토큰에서 샘플링한다(-1 = provider 기본값)"},"minP":{"label":"Min P","description":"최소 확률 임계값 (0-1, -1 = provider 기본값)"},"presencePenalty":{"label":"Presence Penalty","description":"이미 등장한 토큰을 도입하는 데 대한 페널티 (-1 = provider 기본값)"},"repetitionPenalty":{"label":"Repetition Penalty","description":"반복된 토큰에 대한 페널티 (-1 = provider 기본값)"},"textVerbosity":{"label":"텍스트 상세도","description":"OpenAI Responses 및 Codex 응답의 상세도 (low, medium, high)"},"tier.openai":{"label":"서비스 티어 — OpenAI","description":"OpenAI / OpenAI-Codex 요청 및 OpenRouter를 경유하는 OpenAI 계열 모델의 처리 티어 (none = 생략). `service_tier`로 전송한다."},"tier.anthropic":{"label":"서비스 티어 — Anthropic","description":"Claude 요청의 처리 티어. `priority`는 지원되는 직접 Anthropic 모델에서 fast 모드(`speed: \\"fast\\"`)를 활성화하며, Bedrock/Vertex Claude 및 OpenRouter 경유에서는 무시된다."},"tier.google":{"label":"서비스 티어 — Google","description":"Gemini(Google AI Studio + Vertex) 요청 및 OpenRouter를 경유하는 Google 계열 모델의 처리 티어 (none = 생략). 최상위 `serviceTier` 필드로 전송한다."},"tier.subagent":{"label":"서비스 티어 — 서브에이전트","description":"생성된 task/eval 서브에이전트의 서비스 티어. Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다(/fast를 추적한다). 값을 지정하면 서브에이전트 모델이 속한 계열에 그 값을 적용한다."},"tier.advisor":{"label":"서비스 티어 — Advisor","description":"advisor 모델의 서비스 티어. None = 표준 처리, Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다. 값을 지정하면 advisor 모델의 계열에 그 값을 적용한다."},"retry.maxRetries":{"label":"재시도 횟수","description":"API 오류 시 최대 재시도 횟수"},"retry.modelFallback":{"label":"재시도 모델 폴백","description":"재시도 복구 시 설정된 폴백 모델로 전환하도록 허용한다"},"retry.usageAwareFallback":{"label":"사용량 인식 폴백","description":"신뢰할 수 있는 coding-plan 할당량 보고를 활용해, 하드 사용량 한도에 도달하기 전에 동일 provider 계정을 먼저 사용하고 그다음 설정된 폴백 모델을 사용한다. 일반 설정 API 키는 제외한다."},"retry.usageReservePct":{"label":"예비 마진","description":"남은 비율이 이 값 미만이면 coding-plan 모델이 한도에 근접한 것으로 간주한다. 사용량을 알 수 없거나 매핑되지 않은 경우 주 모델을 유지한다."},"retry.usageReservePolicy":{"label":"예비 정책","description":"동일 provider의 모든 coding-plan 계정이 예비 마진 안에 들어왔을 때의 동작이다."},"retry.fallbackChains":{"label":"재시도 폴백 체인","description":"모델 역할, 모델 선택자(\\"provider/model-id\\"), 또는 provider 와일드카드(\\"provider/*\\")를 순서가 있는 폴백 선택자에 매핑하는 JSON 객체이다. 예: {\\"default\\":[\\"openai/gpt-4o-mini\\"],\\"google-antigravity/*\\":[\\"google/*\\",\\"google-vertex/*\\"]}. 모델 지향 키는 역할과 무관하게 해당 모델/provider가 활성일 때마다 적용되며, \\"provider/*\\" 항목은 실패한 모델의 id를 유지한 채 provider만 교체한다. id 접두사 와일드카드(\\"openrouter/google/*\\")는 실패한 모델의 순수 id에 접두사를 다시 붙이고(google-antigravity/gemini-x -> openrouter/google/gemini-x), 키로 사용될 때는 해당 접두사 아래의 그 provider id에만 매칭된다."},"retry.fallbackRevertPolicy":{"label":"폴백 복귀 정책","description":"폴백 이후 주 모델로 되돌아가는 시점이다"},"providers.anthropic.serverSideFallback":{"label":"Anthropic 서버 사이드 폴백 (Fable 5)","description":"Claude Fable 5 / Mythos 5 요청이 Anthropic의 안전 분류기에 의해 차단되면 서버 사이드에서 Claude Opus 4.8로 재시도한다(Anthropic `server-side-fallback-2026-06-01` 베타). 옵트인 방식이며, 끄면 모든 요청에 대해 폴백 이전 동작이 유지된다."},"providers.autoThinkingModel":{"label":"Auto Thinking 모델","description":"`auto` thinking 레벨의 난이도 분류기이다. 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 사용할 수 있다"},"providers.autoThinkingMaxEffort":{"label":"Auto Thinking 상한","description":"`auto` 분류기가 도달할 수 있는 최고 effort이다. `xhigh`는 분류기를 최상위보다 한 단계 아래로 유지해 명시적인 `ultrathink`만 `max`에 도달하게 하며, `max`는 분류기가 예외적이라고 판단한 턴이 이를 노출하는 모델에서 최상위 티어로 과금되도록 허용한다."},"autoResume":{"label":"자동 재개","description":"현재 디렉터리의 가장 최근 세션을 자동으로 재개한다"},"power.sleepPrevention":{"label":"절전 방지","description":"활성 세션 동안 macOS 절전을 방지한다. 각 레벨은 누적되며, 하위 레벨의 플래그를 모두 포함한다."},"git.enabled":{"label":"Git 통합 활성화","description":"TUI에 git 브랜치, 상태, PR 정보를 표시하고 저장소 메타데이터를 감시한다."},"steeringMode":{"label":"Steering 모드","description":"에이전트가 작업하는 동안 대기 중인 메시지를 처리하는 방식이다"},"followUpMode":{"label":"후속 메시지 모드","description":"턴이 완료된 후 후속 메시지를 처리하는 방식이다"},"interruptMode":{"label":"인터럽트 모드","description":"steering 메시지가 도구 실행을 중단하는 시점이다"},"loop.mode":{"label":"Loop 모드","description":"/loop 반복 사이에 프롬프트를 다시 제출하기 전에 일어나는 동작이다"},"doubleEscapeAction":{"label":"이중 Escape 동작","description":"편집기가 비어 있는 상태에서 Escape를 두 번 누를 때의 동작이다"},"treeFilterMode":{"label":"세션 트리 필터","description":"세션 트리를 열 때의 기본 필터 모드이다"},"autocompleteMaxVisible":{"label":"자동완성 항목 수","description":"자동완성 드롭다운에 표시되는 최대 항목 수이다 (3-20)"},"emojiAutocomplete":{"label":"이모지 자동완성","description":"`:name:` 숏코드로 이모지를 제안하고 `:D` 또는 `:-)` 같은 텍스트 이모티콘을 확장한다"},"paste.largeMenuThreshold":{"label":"대용량 붙여넣기 메뉴","description":"붙여넣기가 이 줄 수에 도달하면 코드 블록으로 감싸기, XML 태그로 감싸기, 파일로 저장하기 메뉴를 제공한다. 0은 메뉴를 비활성화한다(대용량 붙여넣기는 여전히 [Paste] 마커로 축약된다)."},"startup.quiet":{"label":"조용한 시작","description":"환영 화면과 시작 상태 메시지를 건너뛴다"},"startup.showSplash":{"label":"시작 스플래시 표시","description":"설정을 다시 실행하지 않고 일반 대화형 시작 시 전체 애니메이션 설정 스플래시를 표시한다. 조용한 시작은 여전히 이를 억제한다."},"startup.setupWizard":{"label":"설정 위저드","description":"새로 추가된 온보딩 단계를 설정 버전마다 한 번 표시한다"},"startup.checkUpdate":{"label":"업데이트 확인","description":"시작 시 omp 업데이트를 확인한다"},"marketplace.autoUpdate":{"label":"마켓플레이스 자동 업데이트","description":"시작 시 플러그인 업데이트를 확인한다"},"startup.changelogMode":{"label":"시작 변경 내역","description":"업데이트 노트를 요약으로 시작할지, 전체 상세로 시작할지, 숨긴 상태로 둘지 선택한다"},"magicKeywords.enabled":{"label":"매직 키워드","description":"단독으로 쓰인 ultrathink, orchestrate, workflowz 키워드에 대한 숨겨진 공지를 활성화한다"},"magicKeywords.ultrathink":{"label":"Ultrathink 키워드","description":"단독으로 쓰인 ultrathink가 최대 자동 사고를 요청하고 숨겨진 공지를 덧붙이도록 한다"},"magicKeywords.orchestrate":{"label":"Orchestrate 키워드","description":"단독으로 쓰인 orchestrate가 숨겨진 멀티 에이전트 오케스트레이션 공지를 덧붙이도록 한다"},"magicKeywords.workflow":{"label":"Workflow 키워드","description":"단독으로 쓰인 workflowz가 숨겨진 eval 워크플로 공지를 덧붙이도록 한다"},"completion.notify":{"label":"완료 알림","description":"에이전트가 턴을 마쳤을 때 알린다"},"error.notify":{"label":"오류 알림","description":"에이전트가 오류로 중단되었을 때 알린다"},"ask.timeout":{"label":"Ask 타임아웃","description":"이 초가 지나면 권장 ask 옵션을 자동 선택한다 (0은 비활성화)"},"ask.notify":{"label":"Ask 알림","description":"ask 도구가 입력을 기다릴 때 알린다"},"recap.enabled":{"label":"유휴 요약","description":"터미널이 유휴 상태가 된 후 현재 상황에 대한 간단한 LLM 요약을 생성한다"},"recap.idleSeconds":{"label":"유휴 요약 지연","description":"요약을 표시하기 전 유휴 상태로 대기하는 초이다"},"collab.relayUrl":{"label":"Relay URL","description":"/collab에서 사용하는 relay이다 (wss://host[:port])"},"collab.webUrl":{"label":"웹 UI URL","description":"/collab 링크에 사용되는 브라우저 UI이다. 비어 있으면 collab.relayUrl에서 파생되며, 명시적인 http://는 localhost에서만 사용된다"},"collab.displayName":{"label":"표시 이름","description":"다른 collab 참가자에게 표시되는 이름이다 (기본값: OS 사용자 이름)"},"share.serverUrl":{"label":"Share 서버","description":"/share에서 사용하는 공유 뷰어/업로드 기준 주소이다 (암호화된 blob 업로드 + 뷰어, 링크는 <base>/<id>#<key> 형식이다)"},"share.store":{"label":"Share 저장소","description":"/share가 암호화된 세션 blob을 업로드하는 위치이다"},"share.redactSecrets":{"label":"공유 시 비밀정보 삭제","description":"업로드 전에 /share 스냅샷에 대해 secret obfuscator를 실행한다(secrets.* 설정을 사용한다)"},"stt.enabled":{"label":"음성 인식","description":"마이크를 통한 speech-to-text 입력을 활성화한다"},"stt.modelName":{"label":"음성 모델","description":"로컬 온디바이스 음성 모델이다. Parakeet TDT v3(sherpa-onnx)가 SoTA 기본값이며, Whisper base/small/large-v3-turbo 등급(transformers.js)은 크기를 다국어 지원과 맞바꾼다. 첫 사용 시 다운로드된다."},"stt.submitTrigger":{"label":"음성 입력 전송 트리거","description":"음성 받아쓰기가 자동으로 전송되는 시점을 선택한다: Never, Release(2단어 이상), 완전한 문장으로 Release, 또는 When I Say Submit."},"tools.approval":{"label":"도구 승인 정책","description":"도구별 승인 정책이다. \'allow\'는 자동 승인, \'prompt\'는 확인 요구, \'deny\'는 차단으로 설정한다. 재정의는 모든 승인 모드에서 적용된다."},"tools.approvalMode":{"label":"도구 승인","description":"도구 호출의 기본 승인 동작이다. \'Always ask\'는 읽기 전용 도구만 자동 승인한다. \'Write\'는 읽기 및 workspace-write 도구를 자동 승인한다. \'Yolo\'는 모든 등급을 자동 승인하지만, 사용자 정책에 따라 확인이나 차단이 발생할 수 있다."},"features.unexpectedStopDetection":{"label":"예상치 못한 중단","description":"어시스턴트가 예상치 못하게 멈추면 자동으로 복구한다. \'기계적\'(기본값)은 표시할 답변 없이 끝난 경우를 재시도하고 도구 호출이 있었던 중단은 제외한다. \'스마트\'는 기계적 감지에 더해 작은 모델로 텍스트만 남긴 중단도 판별하며, \'사용 안 함\'은 감지를 끈다."},"contextPromotion.enabled":{"label":"컨텍스트 자동 승격","description":"컨텍스트 초과 시 compaction 대신 더 큰 컨텍스트 모델로 승격한다"},"compaction.enabled":{"label":"자동 Compact","description":"컨텍스트가 너무 커지면 자동으로 compact한다"},"compaction.midTurnEnabled":{"label":"턴 중간 Compaction","description":"다음 provider 요청 전에 안전한 턴 중간 tool-loop 경계에서 임계값을 확인한다"},"compaction.strategy":{"label":"Compaction 전략","description":"제자리 context-full 유지, auto-handoff, surgical shake(무거운 콘텐츠 제거), snapcompact(히스토리를 밀집 이미지로 보관) 중에서 선택하거나 자동 유지를 비활성화(off)한다"},"compaction.thresholdPercent":{"label":"Compaction 임계값","description":"컨텍스트 유지의 퍼센트 임계값이다. Default로 설정하면 기존 reserve 기반 동작을 사용한다"},"compaction.thresholdTokens":{"label":"Compaction 토큰 한도","description":"컨텍스트 유지의 고정 토큰 한도이다. 설정하면 퍼센트 값을 재정의한다"},"compaction.handoffSaveToDisk":{"label":"Handoff 문서 저장","description":"auto-handoff 흐름에서 생성된 handoff 문서를 markdown 파일로 저장한다"},"compaction.remoteEnabled":{"label":"원격 Compaction","description":"가능한 경우 로컬 요약 대신 원격 compaction 엔드포인트를 사용한다"},"compaction.remoteStreamingV2Enabled":{"label":"원격 Compaction V2","description":"호환되는 원격 compaction 모델에 대해 Responses 스트리밍 compaction을 사용한다"},"compaction.idleEnabled":{"label":"유휴 Compaction","description":"토큰 수가 임계값을 넘으면 유휴 상태에서 컨텍스트를 compact한다"},"compaction.idleThresholdTokens":{"label":"유휴 Compaction 임계값","description":"유휴 compaction이 트리거되는 토큰 수 기준이다"},"compaction.idleTimeoutSeconds":{"label":"유휴 Compaction 지연","description":"compact하기 전 유휴 상태로 대기하는 초이다"},"compaction.supersedeReads":{"label":"오래된 읽기 대체","description":"같은 파일을 다시 읽으면 이전 읽기 결과를 정리한다(캐시 인식, 매 턴 실행)"},"compaction.dropUseless":{"label":"무의미한 결과 제거","description":"컨텍스트상 무용하다고 표시된 도구 결과(일치 없음, 시간 초과된 대기)를 소비된 후 정리한다(캐시 인식)"},"snapcompact.systemPrompt":{"label":"Snapcompact 시스템 프롬프트","description":"실험적 기능이다: 선택한 시스템 프롬프트 텍스트를 밀집 PNG 이미지로 렌더링해 첫 사용자 메시지에 첨부한다(비전 모델 전용). 토큰을 절약하지만 이미지화된 텍스트의 prompt caching을 잃는다."},"snapcompact.toolResults":{"label":"Snapcompact 도구 결과","description":"실험적 기능이다: 큰 과거 도구 결과를 텍스트 대신 밀집 PNG 이미지로 렌더링한다(비전 모델 전용). 누적된 읽기/검색 출력의 토큰을 절약한다."},"tools.format":{"label":"도구 호출 모드","description":"도구가 모델에 노출되는 방식을 제어한다. Auto는 provider-native 도구 호출을 사용하지만, 선택된 모델이 이를 지원하지 않는다고 표시된 경우 GLM owned dialect로 대체한다. Native는 provider-native 도구를 강제하고, 나머지 값은 지정된 owned dialect를 강제한다. 세션 시작 시 적용된다."},"snapcompact.shape":{"label":"Snapcompact 형태","description":"snapcompact가 텍스트를 출력하는 프레임 형태이다(compaction 보관 및 인라인 이미지화). Auto는 현재 모델에 맞게 조정된 형태를 선택한다."},"branchSummary.enabled":{"label":"브랜치 요약","description":"브랜치를 떠날 때 요약을 요청한다"},"ttsr.enabled":{"label":"TTSR","description":"출력이 규칙 패턴과 일치하면 스트리밍 도중에 에이전트를 중단한다(Time-Traveling Stream Rules)"},"ttsr.contextMode":{"label":"TTSR 컨텍스트 모드","description":"TTSR이 발동할 때 부분 출력을 어떻게 처리할지 정한다"},"ttsr.interruptMode":{"label":"TTSR 인터럽트 모드","description":"스트리밍 도중에 중단할지, 완료 후 경고를 주입할지 정한다"},"ttsr.repeatMode":{"label":"TTSR 반복 모드","description":"규칙이 반복되는 방식을 정한다: 세션당 한 번 또는 메시지 간격 이후"},"ttsr.repeatGap":{"label":"TTSR 반복 간격","description":"규칙이 다시 발동할 수 있기까지의 메시지 수이다"},"ttsr.builtinRules":{"label":"기본 제공 규칙","description":"에이전트에 기본 포함된 규칙을 로드한다(ttsr.disabledRules로 개별 해제 가능)"},"memory.backend":{"label":"메모리 백엔드","description":"끄기, 로컬 요약 파이프라인, Mnemopi SQLite, 또는 Hindsight 원격 메모리 중에서 선택한다"},"autolearn.enabled":{"label":"자동 학습 (실험적)","description":"에이전트가 멈춘 뒤 교훈을 메모리에 기록하고 격리된 관리형 skill을 생성/보강하도록 유도한다"},"autolearn.autoContinue":{"label":"중지 시 캡처 자동 실행","description":"켜면 중지 시 비공개 캡처 턴을 한 번 자동 실행한다(추가 토큰을 사용한다). 끄면 상시 자동 학습 안내만 남는다."},"mnemopi.dbPath":{"label":"Mnemopi DB 경로","description":"선택적 SQLite DB 경로이다. 기본값은 에이전트 memories 디렉터리이다."},"mnemopi.bank":{"label":"Mnemopi 뱅크","description":"선택적 공유 뱅크 기본 이름이다. per-project 모드는 이를 기반으로 프로젝트 로컬 뱅크를 파생한다."},"mnemopi.scoping":{"label":"Mnemopi 스코핑","description":"global = 공유 뱅크 하나, per-project = cwd별 격리 뱅크, per-project-tagged = 프로젝트 로컬 쓰기에 global recall 가시성을 더한 방식이다"},"mnemopi.embeddingVariant":{"label":"임베딩 variant","description":"로컬 임베딩 모델 계열이다. en = 더 강력한 영어 모델, multilingual = 교차 언어 모델이다. 이를 변경하면 다음 시작 시 기존 메모리 임베딩을 다시 생성한다."},"mnemopi.autoRecall":{"label":"Mnemopi 자동 recall","description":"각 세션의 첫 턴에 로컬 메모리를 recall한다"},"mnemopi.autoRetain":{"label":"Mnemopi 자동 retain","description":"완료된 대화 턴을 로컬 Mnemopi 메모리에 retain한다"},"mnemopi.polyphonicRecall":{"label":"Mnemopi 폴리포닉 recall","description":"reciprocal rank fusion으로 융합한 4-voice recall(vector, graph, fact, temporal)을 활성화한다"},"mnemopi.enhancedRecall":{"label":"Mnemopi 향상된 recall","description":"반복되거나 유사한 recall 쿼리를 위한 계층형 쿼리 결과 캐시를 활성화한다"},"mnemopi.proactiveLinking":{"label":"Mnemopi 선제적 링킹","description":"새 메모리를 저장하는 즉시 episodic 그래프에 수집해 관련 엔터티 및 메모리와 연결한다"},"mnemopi.noEmbeddings":{"label":"Mnemopi 임베딩 비활성화","description":"vector 임베딩 대신 결정적인 FTS 전용 recall을 강제한다"},"mnemopi.embeddingModel":{"label":"Mnemopi 임베딩 모델","description":"고급: variant를 재정의하는 명시적 임베딩 모델 id이다. 비워 두면 mnemopi.embeddingVariant를 사용한다."},"mnemopi.embeddingApiUrl":{"label":"Mnemopi 임베딩 API URL","description":"Mnemopi에 전달하는 선택적 OpenAI 호환 임베딩 엔드포인트이다"},"mnemopi.embeddingApiKey":{"label":"Mnemopi 임베딩 API 키","description":"Mnemopi에 전달하는 선택적 임베딩 API 키이다"},"mnemopi.llmMode":{"label":"Mnemopi LLM 모드","description":"LLM 미사용, 온라인 tiny 모델(/models의 TINY 역할, 없으면 @smol), 또는 원격 OpenAI 호환 엔드포인트를 사용한다"},"mnemopi.llmBaseUrl":{"label":"Mnemopi LLM Base URL","description":"Mnemopi 원격 모드를 위한 선택적 OpenAI 호환 LLM 엔드포인트이다"},"mnemopi.llmApiKey":{"label":"Mnemopi LLM API 키","description":"Mnemopi 원격 모드를 위한 선택적 LLM API 키이다"},"mnemopi.llmModel":{"label":"Mnemopi LLM 모델","description":"Mnemopi 원격 모드를 위한 선택적 LLM 모델 이름이다"},"hindsight.apiUrl":{"label":"Hindsight API URL","description":"Hindsight 서버 URL(Cloud 또는 self-hosted)이다"},"hindsight.apiToken":{"label":"Hindsight API 토큰","description":"인증이 필요한 Hindsight 서버용 Bearer 토큰이다"},"hindsight.bankId":{"label":"Hindsight Bank ID","description":"메모리 뱅크 식별자다(기본값: 프로젝트 이름)"},"hindsight.scoping":{"label":"Hindsight 범위","description":"global = 하나의 공유 뱅크, per-project = cwd별로 격리된 뱅크, per-project-tagged = 프로젝트 태그가 붙은 공유 뱅크로 recall 시 global 메모리와 프로젝트 메모리가 병합된다"},"hindsight.autoRecall":{"label":"Hindsight 자동 recall","description":"각 세션의 첫 턴에 메모리를 recall한다"},"hindsight.autoRetain":{"label":"Hindsight 자동 retain","description":"N턴마다 그리고 세션 경계에서 대화 기록을 retain한다"},"hindsight.retainMode":{"label":"Hindsight retain 모드","description":"full-session = 세션당 문서 하나를 upsert하고, last-turn = 청크 단위로 저장한다"},"hindsight.mentalModelsEnabled":{"label":"Hindsight 멘탈 모델","description":"부팅 시 정리된 reflect 요약(멘탈 모델)을 developer instructions로 읽어들인다. 뱅크에 있는 기존 모델을 로드하며 쓰기는 하지 않는다. 내장 seed 세트를 자동 생성하려면 hindsight.mentalModelAutoSeed와 함께 사용한다."},"hindsight.mentalModelAutoSeed":{"label":"Hindsight 멘탈 모델 자동 seed","description":"세션 시작 시 뱅크에 아직 없는 내장 멘탈 모델(project-conventions, project-decisions, user-preferences)을 생성한다."},"providers.memoryModel":{"label":"메모리 모델","description":"사실 추출 및 통합에 사용하는 Mnemopi LLM이다: 기본값은 online(/models의 TINY 역할, 없으면 smol/remote)이며, 로컬 on-device 모델도 사용할 수 있다"},"edit.mode":{"label":"편집 모드","description":"edit 도구 변형을 선택한다(replace, patch, hashline, apply_patch)"},"edit.fuzzyMatch":{"label":"퍼지 매치","description":"공백 차이에 대해 신뢰도가 높은 퍼지 매치를 허용한다"},"edit.fuzzyThreshold":{"label":"퍼지 매치 임계값","description":"퍼지 매치를 허용하는 유사도 임계값(0-1)이다"},"edit.streamingAbort":{"label":"프리뷰 실패 시 중단","description":"패치 프리뷰가 실패하면 스트리밍 edit 도구 호출을 중단한다"},"edit.blockAutoGenerated":{"label":"자동 생성 파일 차단","description":"자동 생성된 것으로 보이는 파일(protoc, sqlc, swagger 등)의 편집을 막는다"},"edit.enforceSeenLines":{"label":"확인된 줄 가드 적용","description":"이전 read/search가 전체를 표시하지 않은 줄을 기준으로 하는 편집을 거부한다"},"readLineNumbers":{"label":"줄 번호","description":"기본적으로 read 도구 출력에 줄 번호를 앞에 붙인다"},"read.defaultLimit":{"label":"기본 read 제한","description":"에이전트가 limit 없이 read를 호출할 때 반환하는 기본 줄 수다"},"read.renderMarkdown":{"label":"Markdown 프리뷰","description":"Markdown read 결과를 원본 소스가 아니라 서식이 적용된 터미널 Markdown 프리뷰로 렌더링한다"},"read.summarize.enabled":{"label":"read 요약","description":"명시적 selector 없이 read가 호출되면 구조적 코드 요약을 반환한다"},"read.summarize.prose":{"label":"산문 요약","description":"Markdown 및 일반 텍스트 read에 대해 구조적 요약을 반환한다"},"read.toolResultPreview":{"label":"인라인 read 프리뷰","description":"read 도구 결과를 요약 행이 아니라 대화 기록에 인라인으로 렌더링한다"},"lsp.enabled":{"label":"LSP","description":"코드 인텔리전스(정의, 참조, 진단, 이름 변경)를 위한 lsp 도구를 활성화한다"},"lsp.lazy":{"label":"LSP 지연 시작","description":"세션 시작 시점이 아니라 처음 사용할 때(lsp 도구 호출 또는 해당 파일 타입 편집) language server를 시작한다"},"lsp.shared":{"label":"공유 language server","description":"daemon broker를 통해 프로젝트당 하나의 language server를 omp 인스턴스 간에 공유한다(사용할 수 없으면 개별 서버로 대체된다)"},"lsp.formatOnWrite":{"label":"쓰기 시 포맷","description":"파일을 쓴 후 LSP로 코드 파일을 자동 포맷한다"},"lsp.diagnosticsOnWrite":{"label":"쓰기 시 진단","description":"코드 파일을 쓴 후 LSP 진단을 반환한다"},"lsp.diagnosticsOnEdit":{"label":"편집 시 진단","description":"코드 파일을 편집한 후 LSP 진단을 반환한다"},"lsp.diagnosticsDeduplicate":{"label":"진단 중복 제거","description":"파일에 대해 이미 표시된 편집 후 LSP 진단을 억제하고, 새롭거나 변경된 것만 표시한다"},"bash.enabled":{"label":"Bash","description":"셸 명령 실행을 위한 bash 도구를 활성화한다"},"bash.autoBackground.enabled":{"label":"Bash 자동 백그라운드","description":"오래 실행되는 bash 명령을 자동으로 백그라운드로 보내고 결과를 나중에 전달한다"},"bashInterceptor.enabled":{"label":"Bash 인터셉터","description":"전용 도구가 있는 셸 명령을 차단한다"},"bash.direnv":{"label":"direnv 자동 로드","description":"저장소의 direnv/devenv `.envrc`를 bash 세션에 자동으로 로드해 수동 `direnv exec` 없이 devenv 도구와 환경 변수를 사용할 수 있게 한다. direnv의 허용 목록을 따르며, `direnv allow`하지 않은 `.envrc`는 절대 실행되지 않는다"},"shellMinimizer.enabled":{"label":"셸 출력 축소","description":"장황한 셸 출력(git, npm, cargo 등)을 에이전트에 반환하기 전에 압축한다"},"shellMinimizer.sourceOutlineLevel":{"label":"셸 축소 소스 아웃라인","description":"소스 파일의 cat/read에 대한 소스 아웃라인 모드: default 또는 aggressive"},"eval.py":{"label":"Python Eval 백엔드","description":"eval 도구가 Python 셀을 IPython 커널로 보내도록 허용한다"},"eval.js":{"label":"JavaScript Eval 백엔드","description":"eval 도구가 JavaScript 셀을 인프로세스 런타임으로 보내도록 허용한다"},"eval.rb":{"label":"Ruby Eval 백엔드","description":"eval 도구가 Ruby 셀을 상시 유지되는 Ruby 커널로 보내도록 허용한다"},"eval.jl":{"label":"Julia Eval 백엔드","description":"eval 도구가 Julia 셀을 상시 유지되는 Julia 커널로 보내도록 허용한다"},"python.kernelMode":{"label":"Python 커널 모드","description":"eval 호출 간에 IPython 커널을 유지할지 매번 새로 시작할지 정한다"},"python.interpreter":{"label":"Python 인터프리터","description":"정확한 Python 실행 파일의 선택적 경로이다. 설정하면 자동 Python 런타임 탐색을 건너뛴다."},"ruby.interpreter":{"label":"Ruby 인터프리터","description":"정확한 Ruby 실행 파일의 선택적 경로이다. 설정하면 자동 Ruby 런타임 탐색을 건너뛴다."},"julia.interpreter":{"label":"Julia 인터프리터","description":"정확한 Julia 실행 파일의 선택적 경로이다. 설정하면 자동 Julia 런타임 탐색을 건너뛴다."},"tools.artifactSpillThreshold":{"label":"아티팩트 분리 임계값(KB)","description":"이 크기를 넘는 도구 출력은 아티팩트로 저장되고, 끝부분은 인라인으로 유지된다"},"tools.artifactTailBytes":{"label":"아티팩트 끝부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 양이다"},"tools.artifactHeadBytes":{"label":"아티팩트 앞부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 끝부분과 함께 인라인으로 유지되는 앞부분 내용의 양이다(중간 생략). 0이면 비활성화되어 끝부분만 유지한다."},"tools.outputMaxColumns":{"label":"출력 열 제한","description":"스트리밍 도구 출력(bash, python, js eval)과 `read`에 대한 줄당 바이트 제한이다. 이보다 긴 줄은 말줄임표로 잘리고, 다음 줄바꿈까지 남은 바이트는 버려진다. 0이면 비활성화된다."},"tools.artifactTailLines":{"label":"아티팩트 끝부분 줄 수","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 최대 줄 수이다"},"todo.enabled":{"label":"할 일 목록","description":"작업 추적을 위한 todo 도구를 활성화한다"},"todo.reminders":{"label":"할 일 알림","description":"중지하기 전에 할 일을 완료하도록 에이전트에 상기시킨다"},"todo.remindersMax":{"label":"할 일 알림 제한","description":"포기하기 전까지의 최대 할 일 알림 횟수이다"},"todo.eager":{"label":"할 일 자동 생성","description":"첫 메시지 이후 자동 할 일 목록 생성을 얼마나 강하게 유도할지 정한다"},"glob.enabled":{"label":"Glob","description":"glob 기반 파일 조회를 위한 glob 도구를 활성화한다"},"grep.enabled":{"label":"Grep","description":"정규식 내용 검색을 위한 grep 도구를 활성화한다"},"grep.contextBefore":{"label":"Grep 앞 컨텍스트","description":"각 grep 일치 항목 앞에 표시할 컨텍스트 줄 수이다"},"grep.contextAfter":{"label":"Grep 뒤 컨텍스트","description":"각 grep 일치 항목 뒤에 표시할 컨텍스트 줄 수이다"},"astGrep.enabled":{"label":"AST Grep","description":"구조적 AST 검색을 위한 ast_grep 도구를 활성화한다"},"astEdit.enabled":{"label":"AST Edit","description":"구조적 AST 재작성을 위한 ast_edit 도구를 활성화한다"},"debug.enabled":{"label":"디버그","description":"DAP 기반 디버깅을 위한 debug 도구를 활성화한다"},"launch.enabled":{"label":"Launch","description":"공유되는 장기 실행 프로젝트 프로세스를 감독하는 launch 도구를 활성화한다"},"speechgen.enabled":{"label":"음성 생성","description":"온디바이스(Kokoro) 또는 xAI Grok Voice 음성 파일 합성을 위한 tts 도구를 활성화한다"},"generate_image.enabled":{"label":"이미지 생성","description":"generate_image 도구(텍스트-이미지 생성 및 편집)를 활성화한다. tools.xdev가 켜져 있으면 xd:// 장치로 노출된다."},"inspect_image.mode":{"label":"이미지 분석","description":"이미지 이해를 비전 지원 모델에 위임하는 inspect_image 도구를 제어한다. \'auto\'는 활성 모델이 네이티브 이미지 입력을 지원하지 않을 때만 노출하고, \'on\'은 항상 노출하며, \'off\'는 노출하지 않는다."},"computer.enabled":{"label":"컴퓨터","description":"스크립트 가능한 호스트 데스크톱 제어 도구(스크린샷, 입력, 접근성)를 활성화한다"},"computer.display":{"label":"컴퓨터 디스플레이","description":"모든 디스플레이를 합성하거나 네이티브 display id를 선택한다"},"inspect_image.timeoutMs":{"label":"이미지 분석 타임아웃","description":"inspect_image 비전 모델 호출의 요청당 타임아웃이며 단위는 milliseconds이다. 응답이 멈춘 제공자는 수동 중단까지 차단되지 않고 타임아웃 오류로 빠르게 실패한다. 0으로 설정하면 타임아웃을 비활성화한다."},"checkpoint.enabled":{"label":"체크포인트/되돌리기","description":"컨텍스트 체크포인팅을 위한 checkpoint 및 rewind 도구를 활성화한다"},"fetch.enabled":{"label":"URL 읽기","description":"read 도구가 URL을 가져와 처리하도록 허용한다"},"vault.enabled":{"label":"Obsidian Vault","description":"Obsidian CLI를 통해 Obsidian vault 내용을 읽고 편집하는 vault:// 내부 URL을 활성화한다. 비활성화하면 vault:// 해석이 거부되고 시스템 프롬프트에서 vault:// 항목이 생략된다."},"github.enabled":{"label":"GitHub CLI","description":"github 도구(리포지터리, 이슈, pull request, diff, 검색, checkout, push, Actions watch 워크플로에 대한 op 기반 디스패치)를 활성화한다"},"github.cache.enabled":{"label":"GitHub 뷰 캐시","description":"렌더링된 이슈/PR 뷰 출력을 ~/.omp/cache/github-cache.db에 캐시해 반복 읽기 비용을 없앤다"},"web_search.enabled":{"label":"웹 검색","description":"실시간 웹 결과를 위한 web_search 도구를 활성화한다"},"security.enabled":{"label":"보안","description":"OMP 네이티브 보안 스캔 계획과 실행, 그리고 읽기 전용 security:// 리소스 네임스페이스를 활성화한다"},"ask.enabled":{"label":"Ask","description":"대화형 사용자 질문을 위한 ask 도구를 활성화한다"},"browser.enabled":{"label":"브라우저","description":"스크립트 기반 Chromium 자동화(puppeteer)를 위한 browser 도구를 활성화한다"},"browser.cdpUrl":{"label":"브라우저 CDP URL","description":"브라우저를 실행하는 대신 연결할 기본 HTTP CDP 디스커버리 엔드포인트이다(예: http://127.0.0.1:9222). 도구 호출에 명시된 app.cdp_url 또는 app.path가 우선한다."},"browser.relay":{"label":"브라우저 릴레이","description":"omp browser relay를 통해 사용자의 Chrome 탭을 제어한다. 확장 프로그램을 한 번 설치하면(`omp browser-relay install`) browser 도구가 필요할 때 릴레이 서버가 자동으로 시작된다. Browser CDP URL보다 우선하며, PI_BROWSER_RELAY=0 또는 PI_BROWSER_RELAY=1로 재정의한다."},"browser.relayUrl":{"label":"브라우저 릴레이 URL","description":"omp browser relay 엔드포인트이다(기본값 http://127.0.0.1:9224)."},"browser.headless":{"label":"헤드리스 브라우저","description":"브라우저를 headless 모드로 실행한다(비활성화하면 브라우저 UI를 표시한다)"},"browser.cmux":{"label":"cmux 브라우저","description":"cmux 소켓을 사용할 수 있을 때 브라우저 자동화에 cmux WKWebView 서피스를 사용한다. PI_BROWSER_CMUX=0 또는 PI_BROWSER_CMUX=1로 재정의한다."},"browser.screenshotDir":{"label":"스크린샷 디렉터리","description":"스크린샷을 저장할 디렉터리이다. 설정하지 않으면 스크린샷은 임시 파일로 저장된다. ~를 지원한다. 예: ~/Downloads, ~/Desktop, /sdcard/Download (Android)"},"tools.intentTracing":{"label":"인텐트 트레이싱","description":"각 도구 호출을 실행하기 전에 그 의도를 설명하도록 에이전트에 요청한다"},"tools.abortOnFabricatedResult":{"label":"조작된 도구 결과 시 중단","description":"in-band 도구 호출에서 모델이 턴 중간에 도구 결과를 환각하기 시작하면 즉시 중단한다. 비활성화하면 모델이 생성을 끝내도록 두고 조작된 이어쓰기를 폐기한다."},"tools.maxTimeout":{"label":"최대 도구 타임아웃","description":"에이전트가 임의의 도구에 설정할 수 있는 최대 타임아웃(초, 0 = 무제한)"},"async.enabled":{"label":"비동기 실행","description":"비동기 bash 명령과 백그라운드 작업 실행을 활성화한다"},"tools.xdev":{"label":"xd:// 도구","description":"드물게 쓰이는(탐색 가능한) 도구의 스키마를 매 요청마다 보내는 대신 read/write로 구동되는 xd:// 디바이스 URL 아래에 마운트한다. write 도구가 허용되지 않은 세션은 마운트를 건너뛰고 모든 도구를 최상위로 노출한다. 비활성화하면 활성화된 모든 도구를 최상위로 노출한다."},"tools.xdevDocs":{"label":"xd:// 프롬프트 문서","description":"시스템 프롬프트에 인라인으로 포함할 마운트된 디바이스 문서와 스키마를 선택한다. Built-ins는 핵심 도구를 인라인으로 유지하고 MCP 및 확장 도구는 on-demand로 남긴다."},"mcp.enableProjectConfig":{"label":"MCP 프로젝트 설정","description":"프로젝트 루트에서 .mcp.json/mcp.json을 로드한다"},"mcp.renderMarkdownResults":{"label":"MCP Markdown 결과","description":"JSON이 아닌 MCP 텍스트 결과를 트랜스크립트에서 Markdown으로 렌더링한다"},"mcp.notifications":{"label":"MCP 업데이트 주입","description":"MCP 리소스 업데이트를 에이전트 대화에 주입한다"},"tasks.todoClearDelay":{"label":"Todo 자동 정리 지연","description":"완료되거나 중단된 todo가 todo 위젯에서 제거되기까지의 지연 시간이다"},"dev.autoqa":{"label":"Auto QA","description":"자동 도구 이슈 보고(xd://report_issue)이다. 기본적으로 켜져 있으며, 첫 보고 시 동의를 요청하고 거부하면 명시적으로 다시 활성화할 때까지 보고를 비활성화한다"},"dev.autoqaPush.endpoint":{"label":"Auto QA 푸시 엔드포인트","description":"Auto QA JSON 보고를 수신하는 전체 URL이다(기본값 https://qa.omp.sh/v1/grievances)"},"plan.enabled":{"label":"Plan 모드","description":"실행 전 읽기 전용 탐색과 계획 수립을 위한 plan 모드를 활성화한다"},"plan.defaultOnStartup":{"label":"Plan 모드로 시작","description":"모든 새 세션 시작 시 자동으로 plan 모드로 진입한다"},"goal.enabled":{"label":"Goal 모드","description":"세션별 goal 모드와 숨겨진 goal 도구를 활성화한다"},"goal.statusInFooter":{"label":"푸터의 Goal 상태","description":"상태 표시줄에서 goal 표시기와 함께 토큰 예산을 표시한다"},"title.refreshOnReplan":{"label":"재계획 시 제목 갱신","description":"사용자가 제목을 설정한 경우가 아니면 todo init 재계획 이후 생성된 세션 제목을 갱신한다"},"task.isolation.mode":{"label":"격리 모드","description":"서브에이전트의 격리 백엔드이다. \\"auto\\"는 네이티브 PAL이 사용 가능한 최적 백엔드를 선택하게 한다(CoW를 지원하는 파일시스템, 그다음 overlayfs/ProjFS, 그다음 git worktree / 재귀 복사 폴백)."},"task.isolation.apply":{"label":"격리 변경 적용","description":"성공한 격리 작업의 변경을 부모 체크아웃에 자동으로 적용한다. 비활성화하면 patch 또는 branch 아티팩트를 유지한다"},"task.isolation.merge":{"label":"격리 병합 전략","description":"격리 작업의 변경을 통합하는 방식이다(patch apply 또는 branch merge)"},"task.isolation.commits":{"label":"격리 커밋 스타일","description":"중첩 저장소 변경의 커밋 메시지 스타일이다(generic 또는 AI 생성)"},"worktree.base":{"label":"Worktree 기본 디렉터리","description":"에이전트가 관리하는 worktree의 기본 디렉터리로, 작업 격리 사본, `github` PR 체크아웃, `omp worktree` 정리가 모두 여기에 위치한다. 설정하지 않으면 ~/.omp/wt를 사용한다. 절대 경로 또는 ~ 기준 경로여야 하며, 상대 경로는 무시된다. OMP_WORKTREE_DIR 환경 변수가 이 값을 재정의한다."},"task.eager":{"label":"작업 위임 선호도","description":"서브에이전트에 작업을 위임하도록 얼마나 강하게 유도할지를 정한다"},"task.batch":{"label":"작업 호출 배치","description":"task 도구를 배치 형태로 전환한다: 한 번의 호출이 { context, tasks[] }를 전달하며, 항목당 서브에이전트 하나가 실행되고, 항목별 agent(기본값은 세션 spawn-policy 에이전트)와 항목별 격리를 지정할 수 있으며, 공유 context는 모든 assignment 앞에 필수로 붙는다. async.enabled=true인 경우 각 spawn은 일반적인 idle/parked 수명 주기를 갖는 독립 백그라운드 에이전트로 실행되고, 그렇지 않으면 호출은 병합된 결과를 기다리며 블로킹된다. 비활성화하면 평면적인 단일 spawn 스키마로 되돌아간다."},"task.enableEffort":{"label":"작업별 effort","description":"task spawn에서 선택적 effort 파라미터를 노출해, 호출자가 각 서브에이전트의 thinking 레벨을 재정의할 수 있게 한다"},"task.maxConcurrency":{"label":"최대 동시 작업 수","description":"동시에 실행되는 서브에이전트의 최대 개수이다"},"task.enableLsp":{"label":"서브에이전트 LSP","description":"task 도구로 생성된 서브에이전트가 lsp 도구를 사용할 수 있게 한다. 서브에이전트 비용을 낮게 유지하기 위해 기본적으로 꺼져 있으며, LSP를 활용한 위임이 추가 토큰만큼 가치가 있을 때 활성화한다."},"task.maxRecursionDepth":{"label":"최대 작업 재귀 깊이","description":"서브에이전트가 자신의 서브에이전트를 생성할 수 있는 최대 깊이이다"},"task.maxRuntimeMs":{"label":"서브에이전트 최대 실행 시간","description":"서브에이전트당 절대 실행 시간 제한(ms)이다. 0이면 비활성화된다. 추론 계층 워치독을 빠져나가는 프로바이더 측 스트림 정지에 대한 심층 방어 수단이며, \'timed out\' 사유로 일반적인 서브에이전트 중단을 발생시킨다."},"task.softRequestBudget":{"label":"서브에이전트 소프트 요청 예산","description":"서브에이전트당 소프트 요청 예산(실행당 assistant 요청 수)이다. 이를 초과하면 마무리를 유도하는 steering 알림이 주입되며(task.softRequestBudgetNotice 참고), 예산의 1.5배에 도달하면 실행이 강제 중단되고 에이전트는 부분 결과를 내놓아야 한다. 0이면 이 보호 장치가 비활성화된다. 번들된 scout/sonic 에이전트는 더 낮은 내장 예산이 상한이므로, 그 상한보다 낮은 값은 이들에게도 적용된다."},"task.softRequestBudgetNotice":{"label":"소프트 요청 예산 알림","description":"서브에이전트가 소프트 요청 예산을 초과할 때 steering 알림을 한 번 주입해, 1.5배 강제 중단 전에 마무리하도록 요청한다."},"task.maxEffort":{"label":"spawn당 최대 effort","description":"task 도구의 spawn별 effort 힌트에 허용되는 최대 추론 effort이다. 값을 낮추면 호출자가 서브에이전트를 이 상한 이상으로 올릴 수 없으며, 기본값은 모델의 전체 범위를 유지한다."},"task.prewalk":{"label":"일반 작업 prewalk","description":"번들된 일반 `task` 서브에이전트에 prewalk를 적용한다: 해석된 모델로 시작해 계획을 세우고 구현을 시작한 뒤, 첫 편집/쓰기 시점에 \'smol\' 역할로 넘긴다. 에이전트별 재정의(/agents 허브에서 설정하는 task.agentPrewalk)와 사용자 에이전트의 `prewalk` frontmatter는 이 토글과 무관하게 적용된다."},"skills.enableSkillCommands":{"label":"스킬 명령","description":"스킬을 /skill:name 명령으로 등록한다"},"commands.enableClaudeUser":{"label":"Claude 사용자 명령","description":"~/.claude/commands/에서 명령을 로드한다"},"commands.enableClaudeProject":{"label":"Claude 프로젝트 명령","description":".claude/commands/에서 명령을 로드한다"},"commands.enableOpencodeUser":{"label":"OpenCode 사용자 명령","description":"~/.config/opencode/commands/에서 명령을 로드한다"},"commands.enableOpencodeProject":{"label":"OpenCode 프로젝트 명령","description":".opencode/commands/에서 명령을 로드한다"},"providers.maxInFlightRequests":{"label":"최대 동시 요청 수","description":"프로바이더 id별(예: \\"openai\\" 또는 \\"anthropic\\") 최대 동시 LLM 요청 수로, 같은 config root를 쓰는 로컬 OMP 프로세스 간에 공유된다. 명시되지 않은 프로바이더는 제한이 없다."},"secrets.enabled":{"label":"시크릿 숨김","description":"AI 프로바이더로 전송하기 전에 설정된 시크릿을 난독화하고 자격 증명 형태의 토큰을 마스킹한다"},"providers.webSearchOrder":{"label":"웹 검색 프로바이더 순서","description":"web_search 도구에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 그 뒤에 기본 순서를 유지한다"},"providers.webSearchExclude":{"label":"제외할 웹 검색 프로바이더","description":"web_search가 폴백으로도 절대 사용하지 않을 프로바이더이다"},"providers.webSearchTimeoutSeconds":{"label":"웹 검색 타임아웃","description":"web_search가 다음 폴백으로 넘어가기 전 각 프로바이더 검색 전송에 적용되는 절대 타임아웃이며 단위는 초이다(최대 300)"},"providers.webSearchGeminiModel":{"label":"Gemini web_search 모델","description":"Gemini Google Search grounding에 사용할 모델 ID이다. 기본값은 gemini-2.5-flash이다."},"providers.antigravityEndpoint":{"label":"Antigravity 엔드포인트 모드","description":"google-antigravity 프로바이더의 엔드포인트 라우팅 전략이다(chat, search, image, discovery)"},"providers.imageOrder":{"label":"이미지 프로바이더 순서","description":"이미지 생성에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 활성 세션 프로바이더와 내장 순서를 따른다"},"providers.fireworksTier":{"label":"Fireworks 티어","description":"Fireworks 요청의 서빙 경로이다. Priority는 `service_tier: \\"priority\\"`를 전송해 트래픽이 몰릴 때 더 높은 신뢰성을 더 높은 가격에 제공하고, Standard는 이를 생략한다. Fast(`-fast`) 모델은 이 설정을 무시하며, Fast는 별도의 서빙 경로이다."},"live.voice":{"label":"Live 음성","description":"Codex 기반 realtime 음성 세션에서 사용하는 음성이다"},"providers.tts":{"label":"TTS 제공자","description":"tts 도구의 백엔드이다: 로컬 온디바이스 신경망 TTS(Kokoro-82M) 또는 xAI Grok Voice 중 하나이다"},"tts.localModel":{"label":"로컬 TTS 모델","description":"로컬 TTS 백엔드가 사용하는 온디바이스 신경망 TTS 모델(Kokoro-82M)이다"},"tts.localVoice":{"label":"로컬 TTS 음성","description":"로컬 TTS 백엔드가 사용하는 Kokoro 음성이다(미국/영국, 여성/남성)"},"speech.enabled":{"label":"음성 출력","description":"어시스턴트의 출력을 스트리밍되는 대로 스피커로 소리내어 읽는다"},"speech.mode":{"label":"음성 출력 모드","description":"읽을 대상이다: all = 어시스턴트 메시지 + 사고 과정, assistant = 메시지만, yield = 턴 종료 시 마지막 메시지만이다"},"speech.enhanced":{"label":"향상된 음성 재작성","description":"합성 전에 tiny/smol 모델로 어시스턴트 출력을 자연스러운 구어체 산문으로 재작성한다(코드는 설명으로 바꾸고 링크와 markdown은 제거한다). 실패하면 기계적 정리로 대체된다"},"speech.voice":{"label":"음성 출력 목소리","description":"어시스턴트의 출력을 소리내어 읽을 때 사용하는 Kokoro 음성이다"},"providers.tinyModel":{"label":"Tiny 모델","description":"세션 제목 생성 모델이다: 기본값은 온라인(/models의 TINY 역할, 없으면 @smol)이며, 로컬 온디바이스 모델도 가능하다"},"providers.tinyModelDevice":{"label":"Tiny 모델 디바이스","description":"로컬 tiny 모델(제목 + 메모리)에 사용하는 ONNX 실행 제공자이다. 기본값은 CPU 전용 추론을 사용한다. PI_TINY_DEVICE 환경 변수가 이 값을 덮어쓴다."},"providers.tinyModelDtype":{"label":"Tiny 모델 정밀도","description":"로컬 tiny 모델의 ONNX 양자화/정밀도이다. 기본값은 각 모델에 포함된 dtype(q4)을 사용하며, 정밀도가 낮으면 더 빠르고 높으면 원본에 더 충실하다. PI_TINY_DTYPE 환경 변수가 이 값을 덮어쓴다."},"providers.unexpectedStopModel":{"label":"예기치 않은 중단 모델","description":"예기치 않은 중단 감지용 분류기이다: 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 가능하다."},"providers.kimiApiFormat":{"label":"Kimi API 형식","description":"Kimi Code 제공자의 API 형식이다(auto는 라이브 모델 메타데이터를 따른다)"},"providers.openaiWebsockets":{"label":"OpenAI WebSockets","description":"OpenAI Codex 모델의 websocket 정책이다(auto는 모델 기본값을 사용하고, on은 강제하며, off는 비활성화한다)"},"providers.streamFirstEventTimeoutSeconds":{"label":"스트림 첫 이벤트 타임아웃","description":"모델 스트림의 첫 이벤트를 기다리는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.streamIdleTimeoutSeconds":{"label":"스트림 유휴 타임아웃","description":"모델 스트림이 이벤트 사이에 무응답 상태로 있을 수 있는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.openrouterVariant":{"label":"OpenRouter 라우팅","description":"OpenRouter 모델 ID에 덧붙이는 기본 라우팅 variant 접미사이다(선택기에서 이미 variant를 지정한 경우 무시된다)"},"providers.fetch":{"label":"Fetch 제공자","description":"fetch/read URL 도구의 리더 백엔드 우선순위이다"},"codexResets.autoRedeem":{"label":"Codex 리셋 자동 사용","description":"저장된 Codex rate-limit 리셋을 자동으로 사용한다: 턴이 멈추고 다른 계정이 대체할 수 없을 때 5h 또는 weekly 창을 소진해 차단된 계정을 복구하고, 곧 만료될 크레딧을 회수한다. unset은 첫 사용 전에 확인하고, yes는 확인 없이 사용하며, no는 두 검사 모두 비활성화한다."},"provider.appendOnlyContext":{"label":"추가 전용 컨텍스트","description":"시스템 프롬프트 + 도구 명세를 캐시하고 추가 전용 메시지 로그를 유지해 provider prefix 캐시(DeepSeek, Xiaomi/SGLang, Anthropic) 적중률을 최대화한다. auto는 prefix 캐시가 알려진 제공자에 대해 활성화한다."},"exa.enabled":{"label":"Exa","description":"Exa 웹 검색 제공자를 활성화한다"},"searxng.endpoint":{"label":"SearXNG 엔드포인트","description":"웹 검색에 사용하는 자체 호스팅 SearXNG 인스턴스의 기본 URL이다"}}}'),oD=[{id:"models",label:"Models",icon:"model"},{id:"themes",label:"Themes",icon:"theme"},{id:"skills",label:"Skills",icon:"skill",requiresCwd:!0},{id:"plugins",label:"Plugins",icon:"plugin",requiresCwd:!0},{id:"mcp",label:"MCP",icon:"mcp"},{id:"access",label:"Access",icon:"access"}],o_={model:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,r.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,r.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,r.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,r.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,r.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),appearance:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,r.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,r.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 4a3 3 0 0 0-3 3v1a3 3 0 0 0-1 5v1a3 3 0 0 0 3 3h1m6-13a3 3 0 0 1 3 3v1a3 3 0 0 1 1 5v1a3 3 0 0 1-3 3h-1M9 4v16m6-16v16"})}),files:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"m14 6 4-4 4 4-4 4M3 18l8-8m-6 4 5 5-3 3-5-5 3-3Z"})}),tasks:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2m-3 7 1 1 2-2m-3 7 1 1 2-2"})}),providers:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function oB({kind:e}){return(0,r.jsx)("svg",{className:oz().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:o_[e]??o_.tools})}function oO({field:e,busy:t,onSave:n}){let[s,a]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{a("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let o="secret"===e.type?"":String(e.value??"");return(0,r.jsx)("input",{className:oz().textInput,type:"secret"===e.type?"password":"text",value:s,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>a(e.target.value),onBlur:()=>{s!==o&&("secret"!==e.type||s.length>0)&&n(s)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function oH({field:e,busy:t,onSave:n}){let s=JSON.stringify(e.value??{},null,2),[a,o]=(0,i.useState)(s),[l,d]=(0,i.useState)(null);return(0,i.useEffect)(()=>{o(s),d(null)},[s]),(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsx)("textarea",{className:oz().jsonEditor,style:{minHeight:92},value:a,disabled:t,onChange:e=>o(e.target.value),onBlur:()=>{if(a!==s)try{n(JSON.parse(a)),d(null)}catch(e){d(e instanceof Error?e.message:String(e))}}}),l&&(0,r.jsx)("div",{className:oz().error,children:l})]})}function oU({field:e,busy:t,onSave:n}){let i=Array.isArray(e.value)?e.value:[],s=(e,t)=>{let r=e+t;if(r<0||r>=i.length)return;let s=[...i];[s[e],s[r]]=[s[r],s[e]],n(s)};return(0,r.jsx)("div",{className:oz().multiSelect,children:e.options?.map(a=>{let o=i.indexOf(a.value);return(0,r.jsxs)("span",{className:oz().choice,"data-selected":o>=0,title:a.description,children:[(0,r.jsx)("button",{type:"button",className:oz().choiceToggle,disabled:t,onClick:()=>{let e;return e=a.value,n(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:a.label}),e.ordered&&o>=0&&(0,r.jsxs)("span",{className:oz().reorder,children:[(0,r.jsx)("button",{type:"button",disabled:t||0===o,onClick:()=>s(o,-1),children:"←"}),(0,r.jsx)("button",{type:"button",disabled:t||o===i.length-1,onClick:()=>s(o,1),children:"→"})]})]},a.value)})})}function oq({field:e,busy:t,onSave:n}){return"boolean"===e.type?(0,r.jsx)("button",{type:"button",className:oz().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>n(!0!==e.value)}):"select"===e.type?(0,r.jsx)(ab,{value:String(e.value??""),disabled:t,ariaLabel:e.label,options:(e.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:t=>n("number"==typeof e.value||"number"==typeof e.defaultValue?Number(t):t)}):"multiselect"===e.type?(0,r.jsx)(oU,{field:e,busy:t,onSave:n}):"providerLimits"===e.type?(0,r.jsx)(oH,{field:e,busy:t,onSave:n}):(0,r.jsx)(oO,{field:e,busy:t,onSave:n})}function oV({field:e,busy:t,error:n,onSave:i}){return(0,r.jsxs)("div",{className:oz().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:oz().settingLabel,children:e.label}),(0,r.jsx)("div",{className:oz().settingDescription,children:e.description}),n&&(0,r.jsx)("div",{className:oz().error,children:n})]}),(0,r.jsx)("div",{className:oz().settingControl,children:(0,r.jsx)(oq,{field:e,busy:t,onSave:i})})]})}function oK({mode:e,palette:t}){let n=t.variables["--omp-md-heading"];return(0,r.jsxs)("div",{className:oz().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,r.jsx)("div",{className:oz().themePreviewBar,style:n?{background:n}:void 0}),(0,r.jsxs)("div",{className:oz().themePreviewPanel,children:[(0,r.jsx)("div",{className:oz().themePreviewLine}),(0,r.jsx)("div",{className:oz().themePreviewLine})]})]})}let oJ='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',oG=new Set(["hideThinkingBlock"]);function oY({cwd:e,sessionId:t,initialSection:n="models",onClose:s,onModelsChanged:a,onReloaded:o}){let[l,d]=(0,i.useState)(n),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!0),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(new Set),[y,w]=(0,i.useState)({}),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),{theme:I,setPreference:T}=tC(),{locale:N}=(0,E.s)(),M=(0,i.useRef)(null),R=e=>"ko"===N?oF.shell[e]??e:e,$=(0,i.useCallback)(async()=>{h(!0),f(null);try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/settings${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);u(r)}catch(e){f(e instanceof Error?e.message:String(e))}finally{h(!1)}},[e]);(0,i.useEffect)(()=>{$()},[$]),(0,i.useEffect)(()=>{let e=M.current;if(!e)return;(Array.from(e.querySelectorAll(oJ)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll(oJ)).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],s=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),s.focus()):t.shiftKey||r!==s&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let L=(0,i.useCallback)(async(t,n)=>{b(e=>new Set(e).add(t.path)),w(e=>{let n={...e};return delete n[t.path],n});try{let r=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:i.value??n,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await tS(e),await $()):oG.has(t.path)?await t_(e):j(!0)}catch(e){w(n=>({...n,[t.path]:e instanceof Error?e.message:String(e)}))}finally{b(e=>{let n=new Set(e);return n.delete(t.path),n})}},[e,$]),A=(0,i.useMemo)(()=>new Map(c?.fields.map(e=>[e.path,e.value])??[]),[c?.fields]),P=(0,i.useMemo)(()=>c?.fields.filter(e=>(function(e,t){switch(e.condition){case void 0:default:return!0;case"hasImageProtocol":return!1;case"advisorEnabled":return!0===t.get("advisor.enabled");case"hindsightActive":return"hindsight"===t.get("memory.backend");case"mnemopiActive":return"mnemopi"===t.get("memory.backend");case"autolearnActive":return!0===t.get("autolearn.enabled");case"autoThinkingActive":return"auto"===t.get("defaultThinkingLevel");case"usageAwareFallbackEnabled":return!0===t.get("retry.usageAwareFallback");case"planModeEnabled":return!0===t.get("plan.enabled");case"unexpectedStopDetection":return!0===t.get("features.unexpectedStopDetection")}})(e,A))??[],[c?.fields,A]),z=l.startsWith("settings:")?l.slice(9):null,W=(0,i.useMemo)(()=>{let e=g.trim().toLowerCase();return e?P.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):z?P.filter(e=>e.tab===z&&("appearance"!==z||"Theme"!==e.group)):[]},[z,g,P]),F=(0,i.useCallback)(()=>{a?.(),s()},[s,a]),D=(0,i.useCallback)(async()=>{if(t){C(!0);try{await sp(t,{type:"reload"}),j(!1),o?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[o,t]),_=c?.tabs.find(e=>e.id===z),B=g.trim()?`${R("Search")} \xb7 ${W.length}`:_?.label??R("Settings"),O=(e,t)=>[...new Set([...t,...e.map(e=>e.group??"General").filter(e=>!t.includes(e))])].map(t=>{let n=e.filter(e=>(e.group??"General")===t);return n.length?(0,r.jsxs)("section",{className:oz().group,children:[(0,r.jsx)("h3",{className:oz().groupTitle,children:t}),n.map(e=>(0,r.jsx)(oV,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void L(e,t)},e.path))]},t):null}),H=()=>p?(0,r.jsx)("div",{className:oz().empty,children:R("Loading omp settings…")}):m||!c?(0,r.jsx)("div",{className:oz().empty,children:m??R("Settings unavailable")}):(0,r.jsxs)("div",{className:oz().scrollContent,children:[(0,r.jsxs)("header",{className:oz().contentHeader,children:[(0,r.jsx)("h2",{className:oz().contentTitle,children:B}),(0,r.jsx)("p",{className:oz().contentDescription,children:R(g.trim()?"Matching canonical /settings entries across every category.":"Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.")}),k&&t&&(0,r.jsxs)("div",{className:oz().reloadNotice,children:[(0,r.jsx)("span",{children:R("Saved. Reload the active session to apply runtime settings.")}),(0,r.jsx)("button",{type:"button",onClick:()=>void D(),disabled:S,children:R(S?"Reloading…":"Reload session")})]})]}),(0,r.jsx)("div",{className:oz().settingsBody,children:W.length?O(W,_?.groups??[]):(0,r.jsx)("div",{className:oz().empty,children:R("No settings match this search.")})})]});return(0,r.jsx)("div",{className:oz().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&F()},children:(0,r.jsxs)("div",{ref:M,tabIndex:-1,className:oz().window,role:"dialog","aria-modal":"true","aria-label":R("Settings"),children:[(0,r.jsxs)("aside",{className:oz().sidebar,children:[(0,r.jsxs)("div",{className:oz().brand,children:[(0,r.jsx)("div",{className:oz().eyebrow,children:"omp /settings"}),(0,r.jsx)("h1",{className:oz().title,children:R("Settings")}),(0,r.jsx)("code",{className:oz().context,title:e??R("Global configuration"),children:e??R("Global configuration")})]}),(0,r.jsxs)("div",{className:oz().searchWrap,children:[(0,r.jsxs)("svg",{className:oz().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{className:oz().search,value:g,"aria-label":R("Search /settings"),placeholder:R("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,r.jsxs)("nav",{className:oz().nav,children:[(0,r.jsx)("div",{className:oz().navLabel,children:R("Configuration")}),oD.map(t=>{let n=R(t.label);return(0,r.jsxs)("button",{type:"button",className:oz().navButton,"data-active":!g&&l===t.id,disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${n} ${R("requires a project")}`:n,onClick:()=>{x(""),d(t.id)},children:[(0,r.jsx)(oB,{kind:t.icon}),(0,r.jsx)("span",{children:n})]},t.id)}),(0,r.jsx)("div",{className:oz().navLabel,children:R("OMP settings")}),c?.tabs.map(e=>(0,r.jsxs)("button",{type:"button",className:oz().navButton,"data-active":!g&&z===e.id,onClick:()=>{x(""),d(`settings:${e.id}`)},children:[(0,r.jsx)(oB,{kind:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id))]}),(0,r.jsx)("div",{className:oz().closeRail,children:(0,r.jsxs)("button",{type:"button",className:oz().closeButton,onClick:F,children:[(0,r.jsx)("span",{children:R("Close settings")}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,r.jsx)("main",{className:oz().content,children:g.trim()?H():"models"===l?(0,r.jsx)(ou,{cwd:e,embedded:!0,onClose:F,onModelsChanged:a}):"themes"===l?c?(0,r.jsxs)("div",{className:oz().scrollContent,children:[(0,r.jsxs)("header",{className:oz().contentHeader,children:[(0,r.jsx)("h2",{className:oz().contentTitle,children:R("Themes")}),(0,r.jsxs)("p",{className:oz().contentDescription,children:[R("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,r.jsx)("code",{children:"~/.omp/agent/config.yml"}),R(" and applied here immediately.")]})]}),(0,r.jsxs)("div",{className:oz().settingsBody,children:[(0,r.jsx)("div",{className:oz().themeGrid,children:["dark","light"].map(e=>{let t=c.fields.find(t=>t.path===`theme.${e}`),n=c.theme.palettes[e];return(0,r.jsxs)("div",{className:oz().themeCard,children:[(0,r.jsx)(oK,{mode:e,palette:n}),(0,r.jsxs)("div",{className:oz().themeCardBody,children:[(0,r.jsxs)("div",{className:oz().themeCardHeader,children:[(0,r.jsxs)("span",{className:oz().themeSlot,children:[e,R(" mapping")]}),I===e&&(0,r.jsx)("span",{className:oz().themeActive,children:R("Active on web")})]}),(0,r.jsx)(ab,{value:String(t.value),disabled:v.has(t.path),ariaLabel:`${e} theme`,options:(t.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:e=>void L(t,e)}),I!==e&&(0,r.jsxs)("button",{type:"button",className:oz().closeButton,style:{marginTop:8},onClick:()=>T(e),children:[R("Preview "),e]})]})]},e)})}),O(c.fields.filter(e=>"appearance"===e.tab&&"Theme"===e.group&&!e.path.startsWith("theme.")),["Theme"])]})]}):(0,r.jsx)("div",{className:oz().empty,children:p?R("Loading themes…"):m??R("Themes unavailable")}):"skills"===l&&e?(0,r.jsx)(oy,{cwd:e,embedded:!0,onClose:F}):"plugins"===l&&e?(0,r.jsx)(oA,{cwd:e,sessionId:t,embedded:!0,onClose:F,onReloaded:o}):"mcp"===l?(0,r.jsx)(oZ,{cwd:e,sessionId:t,onReloaded:o}):"access"===l?(0,r.jsx)(oW,{}):H()})]})})}function oZ({cwd:e,sessionId:t,onReloaded:n}){let[s,a]=(0,i.useState)(null),[o,l]=(0,i.useState)("user"),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(null),w=(0,i.useCallback)(async()=>{try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/mcp${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);a(r),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=s?"user"===o?s.user:s.project:null,j=k?.servers[d]??null;(0,i.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{a(t=>{if(!t)return t;let n={..."user"===o?t.user:t.project,servers:e};return"user"===o?{...t,user:n}:{...t,project:n}})},C=async()=>{if(k){v(!0),g(null);try{let t,n=(t=k?.servers??[],(j?.editable===!1?t:t.map((e,t)=>t===d?{...e,name:h,config:JSON.parse(u)}:e)).filter(e=>!1!==e.editable).map(({name:e,config:t})=>({name:e,config:t}))),r=e?`?cwd=${encodeURIComponent(e)}`:"",i=await fetch(`/api/mcp${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:o,servers:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},I=async r=>{y(`${o}:${r.name}`),g(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",s=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:o,name:r.name,enabled:!r.enabled})}),a=await s.json();if(!s.ok||a.error)throw Error(a.error??`HTTP ${s.status}`);await w(),t&&(await sp(t,{type:"reload"}),n?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,r.jsxs)("div",{className:oz().scrollContent,children:[(0,r.jsxs)("header",{className:oz().contentHeader,children:[(0,r.jsx)("h2",{className:oz().contentTitle,children:"MCP servers"}),(0,r.jsx)("p",{className:oz().contentDescription,children:"All MCP servers discovered by OMP are listed by scope and can be enabled or disabled here. Native OMP entries are editable; configurations owned by Claude, Codex, Gemini, plugins, or other providers remain read-only at their source."})]}),(0,r.jsx)("div",{className:oz().settingsBody,children:s?(0,r.jsxs)("div",{className:oz().mcpLayout,children:[(0,r.jsxs)("aside",{className:oz().mcpList,children:[(0,r.jsxs)("div",{className:oz().scopeTabs,children:[(0,r.jsxs)("button",{type:"button",className:oz().scopeButton,"data-active":"user"===o,onClick:()=>{l("user"),c(0)},children:["User \xb7 ",s.user.servers.length]}),(0,r.jsxs)("button",{type:"button",className:oz().scopeButton,"data-active":"project"===o,disabled:!s.project,onClick:()=>{l("project"),c(0)},children:["Project \xb7 ",s.project?.servers.length??0]})]}),k?.error?(0,r.jsx)("div",{className:oz().error,style:{padding:12},children:k.error}):(0,r.jsx)("div",{className:oz().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let n=`${o}:${e.name}`;return(0,r.jsxs)("div",{className:oz().serverRow,"data-active":d===t,children:[(0,r.jsxs)("button",{type:"button",className:oz().serverSelect,title:e.source?.path,onClick:()=>c(t),children:[(0,r.jsx)("span",{className:oz().statusDot,"data-off":!e.enabled}),(0,r.jsx)("span",{className:oz().serverName,children:e.name}),!1===e.editable&&(0,r.jsx)("span",{className:oz().sourceBadge,children:e.source?.provider??"external"})]}),(0,r.jsx)("button",{type:"button",className:oz().serverToggle,"data-on":e.enabled,disabled:b===n,"aria-pressed":e.enabled,"aria-label":`${e.enabled?"Disable":"Enable"} ${e.name}`,title:`${e.enabled?"Disable":"Enable"} ${e.name}`,onClick:()=>void I(e),children:b===n?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,r.jsx)("div",{className:oz().serverListEmpty,children:"No servers in this scope."})}),(0,r.jsx)("button",{type:"button",className:oz().addServer,disabled:!!k?.error,onClick:()=>{if(!k)return;let e="new-server",t=2;for(;k.servers.some(t=>t.name===e);)e=`new-server-${t++}`;let n=[...k.servers,{name:e,config:{type:"stdio",command:""},enabled:!0,editable:!0}];S(n),c(n.length-1)},children:"+ Add OMP server"})]}),(0,r.jsx)("section",{className:oz().mcpEditor,children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:oz().editorHeader,children:[(0,r.jsx)("input",{className:oz().textInput,value:h,readOnly:!1===j.editable,onChange:e=>m(e.target.value),placeholder:"server-name"}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:oz().dangerButton,onClick:()=>{k&&j&&!1!==j.editable&&(S(k.servers.filter((e,t)=>t!==d)),c(Math.max(0,d-1)))},children:"Delete"})]}),!1===j.editable&&(0,r.jsxs)("div",{className:oz().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",j.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,r.jsx)("textarea",{className:oz().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,r.jsxs)("div",{className:oz().editorActions,children:[(0,r.jsxs)("div",{children:[f&&(0,r.jsx)("div",{className:oz().error,children:f}),(0,r.jsx)("div",{className:oz().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:oz().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,r.jsx)("div",{className:oz().empty,children:"Add or select an MCP server."})})]}):(0,r.jsx)("div",{className:oz().empty,children:f??"Loading MCP configuration…"})})]})}let oX="cuelo-notification-prompt-dismissed";function oQ({variant:e,locale:t,permission:n,dismissed:i,request:s,dismiss:a}){let o="ko"===t;return null===n||"granted"===n?null:"banner"===e?"default"!==n||i?null:(0,r.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":o?"알림 권한 안내":"Notification permission",children:[(0,r.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:o?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,children:o?"알림 켜기":"Enable notifications"}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:a,"aria-label":o?"알림 권한 안내 닫기":"Dismiss notification prompt",children:o?"닫기":"Dismiss"})]}):(0,r.jsx)(d.k.Item,{disabled:"denied"===n,onClick:"default"===n?s:void 0,children:(0,r.jsxs)(d.k.ItemBody,{children:[(0,r.jsx)(d.k.ItemLabel,{children:"default"===n?o?"알림 켜기":"Enable notifications":o?"알림 차단됨":"Notifications blocked"}),"denied"===n&&(0,r.jsx)(d.k.ItemDescription,{children:o?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function o0({cwd:e,busy:t,error:n,onCancel:i,onConfirm:s}){let{t:a}=(0,E.s)();return(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:e=>{t||e.target!==e.currentTarget||i()},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},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",style:{flexShrink:0,marginTop:1},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",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("trust.dialogTitle")}),(0,r.jsx)("div",{style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:a("trust.dialogBody")}),(0,r.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),n&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:n})]})]}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:i,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"transparent",color:"var(--text-muted)",cursor:t?"not-allowed":"pointer",fontSize:12},children:a("trust.cancel")}),(0,r.jsx)("button",{type:"button",onClick:s,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid transparent",borderRadius:5,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontSize:12,fontWeight:600},children:a(t?"trust.trusting":"trust.trustProject")})]})]})})}var o1=n(70451),o2=n(54265);let o8={kind:"loading"};function o4(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":r3(e.status)?"var(--accent)":"var(--success)"}function o5(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let o6={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function o3(e){return e.lastUpdate||e.progress?.durationMs||0}function o7(){return{display:"grid",placeItems:"center",width:32,height:30,padding:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"}}function o9({sessionId:e,sessionCwd:t,record:n,client:s,visible:a,onBack:o}){let l=(0,i.useMemo)(()=>[{key:n.key,liveId:n.live?.id,status:n.live?.status,archiveName:n.archive?.name}],[n.key,n.live?.id,n.live?.status,n.archive?.name]),d=(0,i.useRef)(null),c=it(l,{sessionId:e,client:s,enabled:a}).get(n.key)?.state??o8;(0,i.useEffect)(()=>{if(!a||"ready-live"!==c.kind&&"ready-archive"!==c.kind)return;let e=requestAnimationFrame(()=>{let e=d.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[c,a]);let u="ready-live"===c.kind?c.entries:[],p=(0,i.useMemo)(()=>{let e=new Map;for(let t of u)"message"in t&&"toolResult"===t.message.role&&e.set(t.message.toolCallId,t.message);return e},[u]),h=n.live?.id||n.archive?.name||"Subagent";return(0,r.jsxs)("div",{role:"dialog","aria-label":`${h} 기록`,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:o,"aria-label":"Subagent 목록으로 돌아가기",title:"목록",style:o7(),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m10.5 3-5 5 5 5"})})}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,fontWeight:700},children:h}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:o5(n)})]}),n.live&&(0,r.jsx)("span",{style:{color:o4(n.live),fontFamily:"var(--font-mono)",fontSize:9.5},children:n.live.status})]}),(0,r.jsxs)("div",{ref:d,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===c.kind&&(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"기록 불러오는 중…"}),"ready-live"===c.kind&&c.entries.flatMap((e,n)=>{if(!("message"in e))return[];let i=c.entries[n-1];return[(0,r.jsx)(n4,{message:e.message,toolResults:p,cwd:t,showTimestamp:!0,prevTimestamp:i&&"message"in i?i.message.timestamp:void 0},e.id)]}),"ready-archive"===c.kind&&(0,r.jsxs)(r.Fragment,{children:[c.note&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:c.note}),c.truncated&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),c.entries.map((e,t)=>(0,r.jsxs)("div",{style:{margin:"0 0 7px",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:11,lineHeight:1.55},children:[(0,r.jsxs)("div",{style:{marginBottom:5,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:8.5,letterSpacing:"0.04em"},children:[e.role," \xb7 ",e.kind]}),e.text||"(내용 없음)"]},`${e.at??0}:${t}`))]}),"empty"===c.kind&&(0,r.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[c.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:c.note}),(0,r.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===c.kind&&(0,r.jsx)("div",{role:"status",style:{padding:10,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:c.message}),"error"===c.kind&&(0,r.jsx)("div",{role:"alert",style:{padding:10,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5},children:c.message})]})]})}function le({record:e,onSelect:t}){let n,i,s,a,o,l,d,c,u=e.live,p=e.archive,h=(n=e.live,i=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,s=[n?.assignment,n?.progress?.assignment,n?.task].map(rX).find(e=>null!==e)??(i?.taskTitle?.trim()||null),a=n?.progress?.lastIntent?.trim()||"",o=n?.progress?.currentTool?.trim()||"",{title:s??"담당 업무 미확인",stage:a&&o?`${a} \xb7 ${o}`:a||(o?`${o} 실행 중`:null),explicitTitle:null!==s}),m=u?.id||p?.name||"Subagent",f=o5(e),g=(l=e.live,(c=(d=(l?.agent||l?.progress?.agent||"").trim()).toLowerCase().split(/[-_.:/\s]+/).filter(Boolean).join(" "))?{kind:"known",agent:d,source:l?.agentSource??"bundled",label:c}:{kind:"unknown"}),x=function(e){let t=e.live?.progress,n="string"==typeof t?.resolvedModel?t.resolvedModel.trim():"",r=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,i="string"==typeof r?.thinkingLevel?r.thinkingLevel.trim():"";if(n)return{model:n,modelShort:n.split("/").pop()||n,modelIsFallback:t?.resolvedModelIsFallback===!0,effort:i||null};let s="string"==typeof r?.model?r.model.trim():"";return{model:s||null,modelShort:s?s.split("/").pop()||s:null,modelIsFallback:!!s&&r?.modelIsFallback===!0,effort:i||null}}(e),v=x.modelShort??"모델 미확인",b=x.effort??"추론 미확인",y="known"===g.kind?g.label:"역할 미확인";return(0,r.jsxs)("button",{type:"button",role:"listitem",onClick:t,"data-identity":e.identity,title:`${m}
20
+ ${x.model??"모델 미확인"} \xb7 ${b}
21
+ ${h.title}${h.stage?`
22
+ 현재 단계: ${h.stage}`:""}`,"aria-label":`${y} ${m}, 업무 ${h.title}${h.stage?`, 현재 단계 ${h.stage}`:""}, ${u?u.status:p?.status??"미확인"}, 모델 ${x.model??"미확인"}, 추론 ${b}`,style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"4px 8px",width:"100%",marginBottom:8,padding:12,border:"1px solid var(--seed-color-stroke-neutral-weak)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-default)",color:"var(--seed-color-fg-neutral)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:["known"===g.kind?(0,r.jsxs)("span",{className:"subagent-role","data-role-kind":"known","data-role":g.agent,title:`${g.agent} \xb7 ${o6[g.source]}`,children:[(0,r.jsx)("span",{className:"sr-only",children:"역할 "}),g.label]}):(0,r.jsx)("span",{className:"subagent-role","data-role-kind":"unknown",title:"역할 정보가 없는 기록입니다.",children:"역할 미확인"}),(0,r.jsx)("span",{className:"subagent-task-line",style:{minWidth:0},children:h.title})]}),u?(0,r.jsx)("span",{style:{color:o4(u),fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:u.status}):p?(0,r.jsx)("span",{style:{color:"failed"===p.status?"var(--danger)":"aborted"===p.status?"var(--warning)":"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:p.status??"미확인"}):(0,r.jsx)("span",{"aria-hidden":"true"}),h.stage&&(0,r.jsxs)("span",{className:"subagent-stage-line",title:`현재 단계: ${h.stage}`,style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)"},children:[(0,r.jsx)("span",{style:{fontWeight:600},children:"현재 단계"})," \xb7 ",h.stage]}),(0,r.jsxs)("span",{className:"subagent-model-line","data-observed":x.model?x.effort?"both":"model":x.effort?"effort":"none","aria-hidden":"true",style:{gridColumn:"1 / -1"},children:[v,x.modelIsFallback&&(0,r.jsx)("span",{className:"subagent-effort",children:" (대체 모델)"}),(0,r.jsxs)("span",{className:"subagent-effort",children:[" \xb7 ",b]})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 8px",minWidth:0,color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)"},children:[(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m}),(0,r.jsx)("span",{children:f})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 10px",color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)",fontVariantNumeric:"tabular-nums"},children:[u?.progress&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{children:["도구 ",u.progress.toolCount]}),(0,r.jsxs)("span",{children:[u.progress.tokens.toLocaleString()," Token"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}초`;let n=Math.floor(t/60);return n<60?`${n}분${t%60?` ${t%60}초`:""}`:`${Math.floor(n/60)}시간 ${n%60}분`}(u.progress.durationMs)})]}),p&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:null===p.messages?"메시지 수 미확인":`메시지 ${p.messages}`}),(0,r.jsxs)("span",{children:[(p.bytes/1024).toFixed(+(p.bytes<10240))," KB"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Date.now()-e);return t<1e4?"방금 전":t<6e4?`${Math.floor(t/1e3)}초 전`:t<36e5?`${Math.floor(t/6e4)}분 전`:t<864e5?`${Math.floor(t/36e5)}시간 전`:`${Math.floor(t/864e5)}일 전`}(p.modified)})]})]})]})}function lt({title:e,sessionId:t,sessionPath:n,sessionCwd:s,liveSubagents:a,client:o,visible:l=!0,onClose:d,onReturnFocus:c}){let u=(0,i.useMemo)(()=>o??r5(),[o]),[p,h]=(0,i.useState)([]),[m,f]=(0,i.useState)({kind:"loading"}),[g,x]=(0,i.useState)({kind:"loading"}),[v,b]=(0,i.useState)(!1),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(0);(0,i.useEffect)(()=>{h([]),f({kind:"loading"}),x({kind:"loading"}),b(!1),w(null)},[t]),(0,i.useEffect)(()=>{if(!l||!t)return;let e=!1,n=!1,r=null,i=async()=>{if(e||n||"visible"!==document.visibilityState)return;n=!0,r=new AbortController;let[i,s]=await Promise.allSettled([u.getLiveSnapshots(t,r.signal),u.getArchive(t,r.signal)]);if(!e&&!r.signal.aborted){if("fulfilled"===i.status)h(i.value.subagents),f(i.value.subagents.length>0?{kind:"ready",data:i.value.subagents}:{kind:"empty",data:[]});else{let e=ie(i.reason);f("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}if("fulfilled"===s.status)b(!0===s.value.listTruncated),x(s.value.subagents.length>0?{kind:"ready",data:s.value.subagents}:{kind:"empty",data:[]});else{let e=ie(s.reason);x("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}n=!1}};i();let s=setInterval(()=>void i(),3e3),a=()=>{"visible"===document.visibilityState&&i()};return document.addEventListener("visibilitychange",a),()=>{e=!0,r?.abort(),clearInterval(s),document.removeEventListener("visibilitychange",a)}},[k,u,t,l]);let S=(0,i.useMemo)(()=>(function(e,t){let n=new Map,r=[];for(let i of[...e,...t]){let e=n.get(i.id);if(!e){r.push(i.id),n.set(i.id,i);continue}let[t,s]=o3(i)>=o3(e)?[i,e]:[e,i];n.set(i.id,{...t,assignment:t.assignment??s.assignment,description:t.description??s.description})}return r.flatMap(e=>{let t=n.get(e);return t?[t]:[]})})(a,p),[a,p]),C="ready"===g.kind||"empty"===g.kind?g.data:[],I=(0,i.useMemo)(()=>(function(e,t){let n=new Map(t.map(e=>[e.name,e])),r=new Set,i=e.map(e=>{let t=(function(e){let t=[];if(e.sessionFile){let n=e.sessionFile.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"");n&&t.push({name:n,match:"session-file"})}return t.some(t=>t.name===e.id)||t.push({name:e.id,match:"name"}),t})(e).find(e=>n.has(e.name)&&!r.has(e.name)),i=t?n.get(t.name):void 0;return i&&r.add(i.name),{key:`live:${e.id}`,identity:i?"live-archive":"live",live:e,...i&&t?{archive:i,archiveMatch:t.match}:{}}});for(let e of t)r.has(e.name)||i.push({key:`archive:${e.name}`,identity:"archive",archive:e});return i})(S,C),[C,S]),T=y?I.find(e=>e.key===y)??null:null;if((0,i.useEffect)(()=>{y&&!T&&w(null)},[T,y]),T&&t)return(0,r.jsx)(o9,{sessionId:t,sessionCwd:s,record:T,client:u,visible:l,onBack:()=>w(null)});let N=0===I.length&&"loading"===m.kind&&"loading"===g.kind,M=0===I.length&&("empty"===m.kind||0===a.length)&&"empty"===g.kind;return(0,r.jsxs)("section",{"aria-label":"Subagent 기록","data-state":N?"loading":M?"empty":"ready",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:750,letterSpacing:"0.08em",textTransform:"uppercase"},children:e}),(0,r.jsx)("div",{title:n??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:t?.slice(0,8)||"세션 없음"})]}),(0,r.jsx)("button",{type:"button",onClick:()=>j(e=>e+1),"aria-label":"Subagent 기록 새로고침",title:"새로고침",style:o7(),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 5V2m0 0h-3m3 0-2.1 2.1A5.5 5.5 0 1 0 13.3 9"})})}),d&&(0,r.jsx)("button",{type:"button",onClick:()=>{d?.(),c?.()},"aria-label":"Subagent 기록 닫기",title:"닫기",style:o7(),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"9px 10px 16px"},children:[t?N?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"Subagent 기록 불러오는 중…"}):M?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:"이 세션은 아직 Subagent를 실행한 적이 없습니다."}):(0,r.jsx)("div",{role:"list","aria-label":"Subagent 실시간 및 디스크 기록",children:I.map(e=>(0,r.jsx)(le,{record:e,onSelect:()=>w(e.key)},e.key))}):(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"세션을 선택한 뒤 다시 시도하세요."}),!N&&"loading"===m.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"실시간 상태 불러오는 중…"}),!N&&"loading"===g.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"디스크 기록 불러오는 중…"}),"unreachable"===m.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:m.message}),"error"===m.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:m.message}),"unreachable"===g.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:g.message}),"error"===g.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:g.message}),v&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--warning)",fontSize:9.5},children:"최근 디스크 기록 60개만 표시합니다."})]})]})}let ln=["process","efficiency","subagents","files","resource","sidechat"];function lr({activeView:e,onViewChange:t,viewLabels:n,sessionId:i,sessionPath:s,sessionName:l,sessionCwd:d,liveSubagents:c,subagentClient:u,processSlot:p,fileSlot:h,sideChatSlot:m,resourceSlot:f,efficiencySlot:g,visible:x=!0,onClose:v,onReturnFocus:b}){return(0,r.jsx)("aside",{className:"auxiliary-deck","aria-label":"보조 패널","data-auxiliary-view":e,children:(0,r.jsxs)(o1.J.Root,{className:"auxiliary-deck-tabs",size:"small",contentLayout:"fill",triggerLayout:"hug",value:e,onValueChange:e=>t(e),children:[(0,r.jsxs)("div",{className:"auxiliary-deck-tabbar",children:[(0,r.jsxs)(o1.J.List,{"aria-label":"보조 패널 보기",children:[ln.map(e=>{let t="subagents"===e?c.filter(e=>"pending"===e.status||"running"===e.status).length:0;return(0,r.jsxs)(o1.J.Trigger,{value:e,"aria-label":t>0?`${n[e]} (실행 중 ${t})`:void 0,children:[(0,r.jsx)("span",{className:"auxiliary-deck-tab-label",children:n[e]}),t>0&&(0,r.jsx)(o2.E,{size:"medium",variant:"weak",tone:"informative","aria-hidden":"true",children:t})]},e)}),(0,r.jsx)(o1.J.Indicator,{})]}),v&&(0,r.jsx)(a.r,{className:"auxiliary-deck-close",variant:"ghost",size:"small",layout:"iconOnly",onClick:()=>{v?.(),b?.()},"aria-label":"보조 패널 닫기",children:(0,r.jsx)(o.In,{size:"16px",svg:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})})]}),(0,r.jsx)(o1.J.Content,{value:"process",className:"auxiliary-deck-panel",children:p}),(0,r.jsx)(o1.J.Content,{value:"efficiency",className:"auxiliary-deck-panel",children:g}),(0,r.jsx)(o1.J.Content,{value:"subagents",className:"auxiliary-deck-panel",children:(0,r.jsx)(lt,{title:n.subagents,sessionId:i,sessionPath:s,sessionCwd:d,liveSubagents:c,client:u,visible:x&&"subagents"===e})}),(0,r.jsx)(o1.J.Content,{value:"files",className:"auxiliary-deck-panel",children:h}),(0,r.jsx)(o1.J.Content,{value:"sidechat",className:"auxiliary-deck-panel",children:m}),(0,r.jsx)(o1.J.Content,{value:"resource",className:"auxiliary-deck-panel",children:f})]})})}function li({title:e,data:t,onOpenFile:n}){let{t:s}=(0,E.s)(),o=t?.groups??[],[l,d]=(0,i.useState)(()=>new Set);return(0,r.jsxs)("section",{className:"process-log","aria-label":e,children:[(0,r.jsxs)("header",{className:"process-log-header",children:[(0,r.jsx)("h2",{children:e}),(0,r.jsx)("span",{className:"process-log-count",children:o.length>0?`${o.length} ${s(1===o.length?"process.turn":"process.turns")}`:""})]}),(0,r.jsxs)("div",{className:"process-log-body",children:[t?.status?(0,r.jsxs)("p",{className:"process-log-status",role:"status",children:[(0,r.jsx)("span",{className:"process-log-status-pulse","aria-hidden":"true"}),t.status]}):null,0===o.length?(0,r.jsx)("p",{className:"process-log-empty",children:s("process.empty")}):o.map((e,i)=>{let o=l.has(e.anchorIdx),c=function(e){if(!e||"user"!==e.role)return null;let t=("string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join(" ")).replace(/\s+/g," ").trim();return 0===t.length?null:t.length>72?`${t.slice(0,72)}…`:t}(t?.messages[e.anchorIdx]),u=[`${e.messageCount} ${s(1===e.messageCount?"chat.message":"chat.messages")}`];return e.toolCallCount>0&&u.push(`${e.toolCallCount} ${s(1===e.toolCallCount?"chat.toolCall":"chat.toolCalls")}`),(0,r.jsxs)("article",{className:"process-log-turn","data-process-turn":e.anchorIdx,children:[(0,r.jsxs)(a.r,{className:"process-log-turn-toggle",variant:"ghost",size:"small",layout:"withText","aria-expanded":!o,onClick:()=>d(t=>{let n=new Set(t);return n.has(e.anchorIdx)?n.delete(e.anchorIdx):n.add(e.anchorIdx),n}),title:o?s("chat.expandProcess"):s("chat.collapseProcess"),children:[(0,r.jsx)("span",{className:"process-log-turn-title",children:c??s("chat.processDetails")}),(0,r.jsx)("span",{className:"process-log-turn-meta",children:u.join(" \xb7 ")})]}),!o&&(0,r.jsx)("div",{className:"process-log-entries",children:e.entries.map((i,s)=>{let a=t?.messages[i.idx];return a?(0,r.jsx)(n4,{message:i.blocks?eT(a,i.blocks,{omitUsage:!0}):a,toolResults:t?.toolResults,modelNames:t?.modelNames,cwd:t?.cwd,onOpenFile:n,entryId:t?.entryIds[i.idx],sessionId:t?.sessionId,showTimestamp:!1},`process-${e.anchorIdx}-${s}`):null})})]},`turn-${e.anchorIdx}-${i}`)})]})]})}let ls=6,la="omp-btw-log:",lo="omp-btw-log-index";function ll(e){return e.trim().toLowerCase()}function ld(e){return e.map(e=>({q:e.q,a:e.a,at:e.at}))}function lc(e){if(!Array.isArray(e))return[];let t=[],n=0;for(let r of e){if(!r||"object"!=typeof r||"string"!=typeof r.q||"string"!=typeof r.a)continue;let e={q:r.q,a:r.a,at:"number"==typeof r.at&&Number.isFinite(r.at)?r.at:0};t.push(e),n+=e.q.length+e.a.length}for(;t.length>40||n>12e4;){let e=t.shift();if(!e)break;n-=e.q.length+e.a.length}return t}function lu(e){return!!e&&"object"==typeof e&&("QuotaExceededError"===e.name||22===e.code||1014===e.code)}function lp(e,t={}){let n=t.now??Date.now,r=new Map,i=new Set,s=!1,a=[],o=t=>{if(e)try{e.removeItem(t)}catch{}},l=e=>{r.delete(e),i.delete(e),o(la+e)},d=()=>{let e=new Set,t=[];for(let n of(a.sort((e,t)=>t.updatedAt-e.updatedAt),a))!n.id||e.has(n.id)||(e.add(n.id),t.length<20?t.push(n):l(n.id));a=t},c=()=>{if(!s){if(s=!0,e)try{let t=e.getItem(lo),n=t?JSON.parse(t):[];Array.isArray(n)&&(a=n.flatMap(e=>e&&"object"==typeof e&&"string"==typeof e.id&&e.id?[{id:ll(e.id),updatedAt:"number"==typeof e.updatedAt&&Number.isFinite(e.updatedAt)?e.updatedAt:0}]:[]))}catch{a=[]}d()}},u=e=>{c();for(let t=a.length-1;t>=0;t-=1){if(a[t].id===e)continue;let[n]=a.splice(t,1);return l(n.id),!0}return!1},p=t=>{if(e){try{e.setItem(lo,JSON.stringify(a));return}catch(e){if(!lu(e)||!u(t))return}try{e.setItem(lo,JSON.stringify(a))}catch{}}},h=t=>{let n=ll(t);if(!n)return[];if(i.has(n))return ld(r.get(n)??[]);if(e)try{let t=e.getItem(la+n);if(t){let e=JSON.parse(t),i=lc(e?.entries);return r.set(n,i),ld(i)}}catch{}return ld(r.get(n)??[])},m=e=>{let t=ll(e);t&&(c(),a=a.filter(e=>e.id!==t),l(t),p(null))};return{read:h,append:(t,s)=>((t,s)=>{let o=ll(t);if(!o)return[];let l=lc(s),h=n();if(r.set(o,ld(l)),c(),(a=a.filter(e=>e.id!==o)).unshift({id:o,updatedAt:h}),d(),p(o),!e)return ld(l);let m=JSON.stringify({updatedAt:h,entries:l});try{return e.setItem(la+o,m),i.delete(o),ld(l)}catch(e){if(!lu(e)||!u(o))return i.add(o),ld(l)}p(o);try{e.setItem(la+o,m),i.delete(o)}catch{i.add(o)}return ld(l)})(t,[...h(t),s]),history:(e,t=ls)=>h(e).slice(-Math.max(0,t)).map(({q:e,a:t})=>({q:e,a:t})),clear:m,cleanup:(t,r)=>{if(!t.complete)return;c();let i=new Map;for(let e of t.sessions){if(!e||"string"!=typeof e.id||!e.id)continue;let t=ll(e.id),n="number"==typeof e.modified?e.modified:Date.parse(e.modified);i.set(t,Number.isFinite(n)?n:0)}let s=r?ll(r):null,l=n();for(let e of[...a])if(e.id!==s){if(!i.has(e.id)){m(e.id);continue}l-Math.max(i.get(e.id)??0,e.updatedAt)>6048e5&&m(e.id)}if(!e||"function"!=typeof e.key||"number"!=typeof e.length)return;let d=[];try{for(let t=0;t<e.length;t+=1){let n=e.key(t);if(!n?.startsWith(la))continue;let r=ll(n.slice(la.length));i.has(r)||r===s||d.push(n)}}catch{return}for(let e of d)o(e)}}}function lh(){let e=new Map,t=new Map,n=new Map,r=e=>{n.get(e)?.forEach(e=>{e()})};return{read(t){let n=e.get(t);return n?{...n.snapshot}:null},begin(t,n){if(e.has(t))return null;let i=new AbortController;return e.set(t,{snapshot:{sessionId:t,question:n,text:"",model:null},controller:i}),r(t),{controller:i}},ingest(t,n){let i=e.get(t);i&&("d"===n.t?i.snapshot.text+=n.v:"done"===n.t?i.snapshot.text=n.v||i.snapshot.text:"m"===n.t&&(i.snapshot.model=n.v),r(t))},abort(t){let n=e.get(t);return!!n&&(n.controller.abort(),!0)},finish(n,i){e.has(n)&&(e.delete(n),t.set(n,i),r(n))},takeOutcome(e){let n=t.get(e)??null;return n&&t.delete(e),n},subscribe(e,t){let r=n.get(e);return r||(r=new Set,n.set(e,r)),r.add(t),()=>{r.delete(t),0===r.size&&n.delete(e)}}}}class lm extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SideChatRequestError"}}function lf(e){let t;try{t=JSON.parse(e)}catch{throw new lm("stream","사이드채팅 스트림을 해석할 수 없습니다.")}if(!t||"object"!=typeof t)throw new lm("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");let n=t;if("d"!==n.t&&"done"!==n.t&&"m"!==n.t&&"err"!==n.t||"string"!=typeof n.v)throw new lm("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");return{t:n.t,v:n.v}}class lg{push(e){this.buffer+="string"==typeof e?e:this.decoder.decode(e,{stream:!0});let t=this.buffer.split("\n");return this.buffer=t.pop()??"",t.flatMap(e=>e.trim()?[lf(e)]:[])}finish(){this.buffer+=this.decoder.decode();let e=this.buffer.trim();return this.buffer="",e?[lf(e)]:[]}constructor(){this.decoder=new TextDecoder,this.buffer=""}}async function lx(e){let t=await e.text().catch(()=>"");if(!t)return`HTTP ${e.status}`;try{let e=JSON.parse(t);if("string"==typeof e.error&&e.error)return e.error}catch{}return t}function lv(e=!1){return{minHeight:30,padding:"4px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",fontWeight:650}}function lb({children:e}){return(0,r.jsx)("div",{className:"side-chat-question",style:{alignSelf:"flex-end",maxWidth:"92%",padding:"8px 10px",border:"1px solid var(--border)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55},children:e})}function ly({children:e,streaming:t=!1}){return(0,r.jsxs)("div",{className:`side-chat-answer${t?" is-streaming":""}`,style:{alignSelf:"flex-start",maxWidth:"100%",padding:"8px 10px",border:"1px solid var(--border)",color:"var(--text)",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.58},children:[e?(0,r.jsx)(tR,{isStreaming:t,children:e}):t?"응답을 기다리는 중…":null,t&&(0,r.jsx)("span",{"aria-hidden":"true",style:{marginLeft:2,color:"var(--accent)"},children:"▍"})]})}function lw({identity:e,status:t,utteranceKey:n,children:i}){let s=ng(e?.sessionId,e?.provider,e?.credentialId),a=rD(s?.alias,t,n);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:5},children:[s&&e?.provider&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minHeight:40,marginBottom:2},children:[(0,r.jsx)(nx,{seed:s.seed,size:40,provider:e.provider}),(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:s.alias})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:7,minWidth:0,maxWidth:"100%"},children:[i,a&&(0,r.jsx)("img",{src:a.src,alt:a.alt,width:52,height:52,style:{flex:"0 0 auto",objectFit:"contain"}})]})]})}function lk({title:e,sessionId:t,sessionPath:n,sessionName:s,historyStore:a,flights:o,sessionCensus:l,client:d,visible:c=!0,onClose:u,onReturnFocus:p}){let h,m,f=(0,i.useMemo)(()=>d??function(e=(e,t)=>fetch(e,t),t="/api/sidecars/sidechat/ask"){return{async ask(n){let r;try{r=await e(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionPath:n.sessionPath,question:n.question,history:n.history.slice(-ls)}),signal:n.signal})}catch(e){if(n.signal?.aborted)throw e;throw new lm("unreachable","사이드채팅 사이드카(30143)에 연결할 수 없습니다.")}if(!r.ok)throw new lm("http",await lx(r),r.status);if(!r.body)throw new lm("stream","사이드채팅 스트림을 열 수 없습니다.");let i=r.body.getReader(),s=new lg,a="",o=null,l=e=>{for(let t of e)if(n.onEvent?.(t),"d"===t.t)a+=t.v;else if("done"===t.t)a=t.v||a;else if("m"===t.t)o=t.v;else throw new lm("server",t.v)};try{for(;;){let e=await i.read();if(e.done)break;l(s.push(e.value))}l(s.finish())}catch(e){if(n.signal?.aborted||e instanceof lm)throw e;throw new lm("stream",e instanceof Error?e.message:"사이드채팅 스트림이 중단되었습니다.")}finally{i.releaseLock()}if(!a)throw new lm("empty","사이드채팅이 빈 응답을 반환했습니다.");return{text:a,model:o}}}}(),[d]),g=t?.toLowerCase()??null,[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)({}),w=g??"",k=b[w]??"",j=(e,t)=>{y(n=>{if((n[e]??"")===t)return n;let r={...n};return t?r[e]=t:delete r[e],r})},[S,C]=(0,i.useState)(0),[I,T]=(0,i.useState)({}),[N,M]=(0,i.useState)({}),[R,E]=(0,i.useState)({}),[$,L]=(0,i.useState)(null),[A,P]=(0,i.useState)(null),[z,W]=(0,i.useState)({}),[F,D]=(0,i.useState)({}),[_,B]=(0,i.useState)({}),O=(0,i.useRef)((h=new Set,m=new Set,{claim:e=>!(!e||h.has(e)||m.has(e))&&(h.add(e),!0),markSent(e){h.delete(e),m.add(e)},release(e){h.delete(e)}})),H=(0,i.useRef)(!0),U=(0,i.useRef)(g),q=(0,i.useRef)(c),V=(0,i.useRef)(null),K=(0,i.useRef)(!1),J=(0,i.useRef)(0),G=(0,i.useRef)(null);U.current=g,q.current=c,(0,i.useEffect)(()=>(H.current=!0,()=>{H.current=!1}),[]),(0,i.useEffect)(()=>{v(g?a.read(g):[])},[a,g]),(0,i.useEffect)(()=>{if(L(null),!g)return;let e=!0;return fetch(`/api/sessions/${encodeURIComponent(g)}?deferThinking=1&deferMedia=1`,{cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return function(e){if(!e||"object"!=typeof e||!("context"in e))return null;let t=e.context;if(!t||"object"!=typeof t||!("messages"in t))return null;let n=t.messages;if(!Array.isArray(n))return null;for(let e=n.length-1;e>=0;e-=1){let t=n[e];if(!t||"object"!=typeof t||!("role"in t)||"assistant"!==t.role)continue;if(!("provider"in t)||"string"!=typeof t.provider||!t.provider)break;let r="credentialId"in t?t.credentialId:void 0;return{provider:t.provider,..."number"==typeof r&&Number.isSafeInteger(r)&&r>0?{credentialId:r}:{}}}return null}(await e.json())}).then(t=>{e&&L(t?{...t,sessionId:g}:null)}).catch(()=>{e&&L(null)}),()=>{e=!1}},[g]),(0,i.useEffect)(()=>{if(!g)return;let e=()=>{if(!H.current||U.current!==g)return;let e=o.takeOutcome(g);if(e){if("aborted"===e.kind)M(t=>({...t,[g]:e.saved?"응답 생성을 중단했습니다. 받은 내용은 현재 세션 기록에 저장했습니다.":"응답 생성을 중단했습니다."}));else if("failed"===e.kind)T(t=>({...t,[g]:[...t[g]??[],{question:e.question,partialAnswer:e.partialAnswer,kind:e.errorKind,message:e.errorMessage}]})),y(t=>(t[g]??"").trim()?t:{...t,[g]:e.question});else if(e.model){let t=e.model;E(e=>({...e,[g]:t}))}v(a.read(g))}else null===o.read(g)&&v(a.read(g));C(e=>e+1)},t=o.subscribe(g,e);return e(),t},[o,a,g]),(0,i.useEffect)(()=>{l&&a.cleanup(l,g)},[a,g,l]),(0,i.useEffect)(()=>{c&&V.current?.focus()},[c,g]),(0,i.useEffect)(()=>{if(!c)return;let e=requestAnimationFrame(()=>{let e=G.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[S,g,x.length,c]);let Y=async e=>{if(!g||!n){let e=g??"";M(t=>({...t,[e]:"세션 파일이 준비되지 않았습니다. 기록이 생성된 뒤 다시 시도하세요."}));return}let t=o.begin(g,e);if(!t)return;let{signal:r}=t.controller;M(e=>{let t={...e};return delete t[g],t});try{let t=await f.ask({sessionPath:n,question:e,history:a.history(g),signal:r,onEvent:e=>o.ingest(g,e)});a.append(g,{q:e,a:t.text,at:Date.now()}),o.finish(g,{kind:"done",model:t.model})}catch(n){let t=o.read(g)?.text??"";if(r.aborted){let n=!1;t&&(a.append(g,{q:e,a:t,at:Date.now()}),n=!0),o.finish(g,{kind:"aborted",saved:n})}else{let r=n instanceof lm?n.kind:"unknown",i=n instanceof Error?n.message:String(n);o.finish(g,{kind:"failed",question:e,partialAnswer:t,errorKind:r,errorMessage:i})}}finally{H.current&&q.current&&V.current?.focus()}},Z=async(e,t,n)=>{if(!g)return;let r=`${g}:${t}`;if(O.current.claim(r)){D(e=>({...e,[r]:"sending"})),B(e=>{let t={...e};return delete t[r],t});try{var i,s;let t,a=await fetch(`/api/agent/${encodeURIComponent(g)}`,{cache:"no-store"}),o=null;try{o=await a.json()}catch{}if(!a.ok){if(o&&"object"==typeof o&&"error"in o&&"string"==typeof o.error)throw Error(o.error);throw Error(`HTTP ${a.status}`)}let l=function(e){if(!e||"object"!=typeof e||!("running"in e)||"boolean"!=typeof e.running)return null;if(!e.running)return!1;if(!("state"in e)||!e.state||"object"!=typeof e.state)return null;let t=e.state;return"isStreaming"in t&&"boolean"==typeof t.isStreaming&&"isPromptRunning"in t&&"boolean"==typeof t.isPromptRunning&&"isBashRunning"in t&&"boolean"==typeof t.isBashRunning&&"isCompacting"in t&&"boolean"==typeof t.isCompacting&&"isHandoffRunning"in t&&"boolean"==typeof t.isHandoffRunning?t.isStreaming||t.isPromptRunning||t.isBashRunning||t.isCompacting||t.isHandoffRunning:null}(o);if(null===l)throw Error("메인 세션 실행 상태를 확인할 수 없습니다.");let d=(i=e.q,s=e.a,t=n.trim(),["사이드채팅 문답을 메인 대화에서 이어서 처리해 주세요.","","[사이드채팅 질문]",i,"","[사이드채팅 답변]",s,...t?["","[추가 지시]",t]:[]].join("\n"));await sp(g,{type:l?"steer":"prompt",message:d}),O.current.markSent(r),D(e=>({...e,[r]:"sent"}))}catch(e){O.current.release(r),D(e=>{let t={...e};return delete t[r],t}),B(t=>({...t,[r]:e instanceof Error?e.message:String(e)}))}}},X=()=>{if(g&&null!==o.read(g))return void o.abort(g);let e=k.trim();e&&(j(w,""),Y(e))},Q=I[g??""]??[],ee=N[g??""],et=g?o.read(g):null,en=x.length>0||Q.length>0||null!==et,er=et?.model??R[g??""],ei=!g||!n,es=null!==et,ea=!es&&!ei&&k.trim().length>0,eo=!g||es,el=$?.sessionId===g?$:null;return(0,r.jsxs)("section",{className:"side-chat-panel","aria-label":"사이드채팅","aria-busy":null!==et,"data-state":g&&n?et?"streaming":"ready":"unavailable",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:e}),(0,r.jsxs)("div",{title:n??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)"},children:[s||g?.slice(0,8)||"세션 없음",er?` \xb7 ${er}`:""]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{g&&null===o.read(g)&&(a.clear(g),v([]),T(e=>{let t={...e};return delete t[g],t}),M(e=>({...e,[g]:"현재 세션의 사이드채팅 기록을 비웠습니다."})))},disabled:eo,style:lv(eo),children:"Clear"}),u&&(0,r.jsx)("button",{type:"button",onClick:()=>{u?.(),p?.()},"aria-label":"사이드채팅 닫기",title:"닫기",style:{...lv(),width:32,padding:0},children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,r.jsxs)("div",{ref:G,"aria-live":"polite",style:{display:"flex",flex:1,minHeight:0,flexDirection:"column",gap:7,overflowY:"auto",padding:"11px 12px 18px"},children:[g&&n?(0,r.jsxs)(r.Fragment,{children:[x.map((e,t)=>{let n=`${e.at}:${t}`,i=`${g}:${n}`,s=F[i],a=A===i;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(lb,{children:e.q}),(0,r.jsx)(lw,{identity:el,status:"settled",utteranceKey:n,children:(0,r.jsx)(ly,{children:e.a})}),"sent"===s?(0,r.jsx)("span",{role:"status",style:{color:"var(--text-muted)",fontSize:10.5},children:"보냄"}):(0,r.jsxs)(r.Fragment,{children:[!a&&(0,r.jsx)("button",{type:"button","aria-expanded":"false",onClick:()=>P(i),style:{...lv(),alignSelf:"flex-start"},children:"메인에 보내기"}),a&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:6},children:[(0,r.jsx)("label",{htmlFor:`side-chat-forward-${t}`,style:{color:"var(--text-muted)",fontSize:10.5},children:"메인에 덧붙일 지시 (선택)"}),(0,r.jsx)("textarea",{id:`side-chat-forward-${t}`,rows:2,value:z[i]??"",onChange:e=>W(t=>({...t,[i]:e.target.value})),style:{width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",padding:"7px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void Z(e,n,z[i]??""),disabled:"sending"===s,style:lv("sending"===s),children:"sending"===s?"보내는 중…":"메인으로 전송"}),"sending"!==s&&(0,r.jsx)("button",{type:"button",onClick:()=>P(null),style:lv(),children:"취소"})]})]}),_[i]&&(0,r.jsx)("div",{role:"alert",style:{color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:_[i]})]})]},n)}),Q.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(lb,{children:e.question}),(0,r.jsxs)(lw,{identity:el,status:"failed",utteranceKey:`failed:${e.question}:${t}`,children:[e.partialAnswer&&(0,r.jsx)(ly,{children:e.partialAnswer}),(0,r.jsx)("div",{role:"alert","data-error-kind":e.kind,style:{padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:e.message})]})]},`${e.question}:${t}`)),et&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(lb,{children:et.question}),(0,r.jsx)(lw,{identity:el,status:"streaming",utteranceKey:`stream:${et.question}`,children:(0,r.jsx)(ly,{streaming:!0,children:et.text})})]}),!en&&(0,r.jsxs)("div",{style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.65},children:["현재 세션의 전체 맥락을 보고 답합니다.",(0,r.jsx)("br",{}),"사이드채팅 기록은 부모 세션별로 보관됩니다."]})]}):(0,r.jsxs)("div",{role:"status",style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.6},children:["세션 기록을 준비하는 중입니다.",(0,r.jsx)("br",{}),"세션 파일이 생성되면 사이드채팅을 사용할 수 있습니다."]}),ee&&(0,r.jsx)("div",{role:"status",style:{padding:"7px 9px",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:ee})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),X()},style:{display:"flex",flexDirection:"column",gap:6,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("label",{htmlFor:"side-chat-question",style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:"사이드채팅 질문"}),(0,r.jsx)("textarea",{ref:V,id:"side-chat-question",rows:4,value:k,onChange:e=>j(w,e.target.value),onCompositionStart:()=>{K.current=!0},onCompositionEnd:()=>{K.current=!1,J.current=Date.now()},onKeyDown:e=>{if("Enter"!==e.key||e.shiftKey)return;let t=e.nativeEvent,n=Date.now()-J.current<100;if(K.current||t.isComposing||229===t.keyCode||n){n&&e.preventDefault();return}es||(e.preventDefault(),X())},disabled:es||ei,placeholder:"질문 입력 — Enter 전송, Shift+Enter 줄바꿈",style:{width:"100%",minWidth:0,minHeight:88,maxHeight:240,boxSizing:"border-box",resize:"vertical",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{"aria-live":"polite",style:{flex:1,minWidth:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.4,overflowWrap:"anywhere"},children:ei?"세션 파일이 준비되면 질문할 수 있습니다.":es?"응답을 받는 중입니다.":"Enter 전송 \xb7 Shift+Enter 줄바꿈"}),(0,r.jsx)("button",{type:"submit",disabled:!es&&!ea,style:lv(!es&&!ea),children:es?"중단":"전송"})]})]})]})}function lj(e){let[t,n]=(0,i.useState)(()=>Date.now());return(0,i.useEffect)(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}let lS="min-h-9 border border-border bg-bg px-3 text-xs font-medium text-text transition-colors hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-50";function lC(...e){return e.filter(Boolean).join(" ")}function lI(e,t){let n=Math.floor((e-t)/6e4);if(n<=0)return"리셋됨";let r=Math.floor(n/1440),i=Math.floor(n%1440/60),s=n%60;return r>0?`${r}d ${i}h 후 리셋`:i>0?`${i}h ${s}m 후 리셋`:`${s}m 후 리셋`}function lT(e,t){if(!e)return null;let n=Date.parse(e);if(!Number.isFinite(n))return null;let r=Math.floor((n-t)/6e4);if(r<=0)return"만료됨";let i=Math.floor(r/1440),s=Math.floor(r%1440/60),a=r%60;return i>0?`${i}d ${s}h 후 만료`:s>0?`${s}h ${a}m 후 만료`:`${a}m 후 만료`}function lN(e){return"number"==typeof e&&Number.isFinite(e)?0===e?"$0":e>=100?`$${e.toFixed(0)}`:e>=1?`$${e.toFixed(2)}`:e>=.01?`$${e.toFixed(3)}`:`$${e.toFixed(4)}`:"—"}function lM(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function lR(e){return"number"==typeof e&&Number.isFinite(e)?e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e)):"—"}function lE(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function l$(e){return"number"==typeof e&&Number.isFinite(e)?`${(e/1e3).toFixed(1)}s`:"—"}function lL(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function lA({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 border-b border-border py-1.5 last:border-b-0",children:[(0,r.jsx)("dt",{className:"text-xs text-text-muted",children:e}),(0,r.jsx)("dd",{className:"m-0 font-mono text-xs tabular-nums text-text",children:t})]})}function lP({state:e,loading:t,subject:n}){return t&&"idle"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:[n," 불러오는 중…"]}):"error"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsxs)("div",{className:"font-medium",children:[n,"을 불러오지 못했습니다."]}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:e.error.message}),(0,r.jsx)("div",{className:"mt-2 text-xs text-text-dim",children:"사이드카(127.0.0.1:30142)가 실행 중인지 확인하세요."})]}):"stale"===e.status?(0,r.jsxs)("div",{className:"border-b border-border bg-bg px-4 py-2 text-xs text-text-muted",role:"status",children:["마지막 데이터를 표시합니다. 새로고침 실패: ",e.error.message]}):null}function lz(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${t.getMonth()+1}/${t.getDate()} ${n}:${r}`}function lW({limit:e,now:t,detailed:n}){let i="number"==typeof e.amount?.usedFraction?e.amount.usedFraction:0,s=Math.max(0,Math.min(100,100*i)),a=Math.round(100*i),o=function(e,t){let n=e.window,r=e.amount?.usedFraction;if(!n?.resetsAt||"number"!=typeof r)return null;let i=Math.max(0,n.resetsAt-t),s=100*r,a=Math.max(0,100-s);if(!n.durationMs){let e=i/864e5;return{burnOnly:!0,unit:"하루",partial:e<1,burn:e>=1?a/e:a}}let o=Math.min(n.durationMs,Math.max(0,n.durationMs-i)),l=n.durationMs>432e5,d=l?864e5:36e5,c=n.durationMs/d,u=i/d,p=o/n.durationMs*100;return{burnOnly:!1,unit:l?"하루":"시간",partial:u<1,burn:u>=1?a/u:a,pacePct:p,deltaPct:s-p,nominal:100/c}}(e,t),l=e.daySlot,d=l?.usedPct==null||null==l.baselinePct?null:Math.max(0,Math.min(l.baselinePct,100)),c=null==d?null:Math.max(d,Math.min(100*i,100)),u=o?.pacePct==null?null:Math.min(o.pacePct,99.6),p=a>=90,h=o?.deltaPct!=null&&o.deltaPct>=.5?o.deltaPct:null,m=l?"unknown"===l.quality||null==l.usedPct?"구간 사용 — 기록 부족":"approx"===l.quality?`구간 사용 ≈${l.usedPct.toFixed(0)}% \xb7 추정`:`구간 사용 ${l.usedPct.toFixed(1)}%`:null;return(0,r.jsxs)("div",{className:"usage-limit py-2",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-muted",children:e.label||e.id}),i>=1?(0,r.jsx)("span",{className:"usage-chip","data-tone":"danger",children:i>1?"한도 초과":"한도 도달"}):null,null!=h?(0,r.jsx)("span",{className:"usage-chip","data-tone":"warning",children:`과속 +${h.toFixed(1)}%`}):null,(0,r.jsxs)("span",{className:lC("shrink-0 font-mono text-sm font-semibold tabular-nums",p?"text-danger":"text-text"),children:[a,"%"]})]}),(0,r.jsxs)("div",{className:"relative mt-1 h-3.5 overflow-hidden border border-border-strong bg-metric-track",role:"progressbar","aria-label":`${e.label||e.id} 사용량`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":a,children:[(0,r.jsx)("div",{className:lC("absolute inset-y-0 left-0",p?"bg-danger":"bg-metric"),style:{width:`${s}%`}}),null!=d&&null!=c&&c>d?(0,r.jsx)("div",{className:"absolute inset-y-0 bg-metric-recent",style:{left:`${d}%`,width:`${c-d}%`,boxShadow:"inset 1px 0 var(--bg-panel)"}}):null,null!=u?(0,r.jsx)("div",{className:"absolute inset-y-0 w-0.5 bg-text",style:{left:`${u}%`,boxShadow:"0 0 0 1px color-mix(in srgb, var(--bg-panel) 80%, transparent)"},"aria-hidden":"true"}):null,i>1?(0,r.jsx)("div",{className:"absolute inset-y-0 right-0 w-1 bg-danger","aria-hidden":"true"}):null]}),m||e.window?.resetsAt?(0,r.jsxs)("div",{className:"mt-1 flex items-baseline justify-between gap-3 font-mono text-[11px] tabular-nums text-text-muted",children:[(0,r.jsx)("span",{className:"min-w-0 truncate",children:m??""}),e.window?.resetsAt?(0,r.jsx)("span",{className:"shrink-0",children:lI(e.window.resetsAt,t)}):null]}):null,n?(0,r.jsxs)("dl",{className:"m-0 mt-1.5 border-s-2 border-border ps-2.5",children:[o?.pacePct!=null?(0,r.jsx)(lA,{label:"페이스",value:`${o.pacePct.toFixed(1)}%`}):null,o?(0,r.jsx)(lA,{label:o.partial?"남은 한도":`앞으로 ${o.unit}`,value:`${o.burn.toFixed(1)}%`}):null,o?.nominal!=null?(0,r.jsx)(lA,{label:"균등 배분 기준",value:`${o.nominal.toFixed(1)}%/${"하루"===o.unit?"일":"시간"} \xb7 계산값`}):null,l?(0,r.jsx)(lA,{label:"구간",value:`${lz(l.slotStart)} ~ ${lz(l.slotEnd)} \xb7 ${l.slotIndex+1}/${l.slotCount}`}):null,l?(0,r.jsx)(lA,{label:"기록 품질",value:function(e){let t;if("unknown"===e.quality)return"기록 부족 \xb7 구간 시작 전 표본이 없습니다";let n=null==e.gapMs||0===e.gapMs?null:(t=Math.round(e.gapMs/6e4))<60?`${t}분`:`${Math.floor(t/60)}시간 ${t%60}분`;return"exact"===e.quality?n?`실측 \xb7 경계 ${n} 전 표본`:"실측 \xb7 구간 시작이 창의 시작":`추정 \xb7 경계 ${n??"?"} 전 표본`}(l)}):null]}):null]})}let lF={"anthropic:5h":"5시간","anthropic:7d":"주간","anthropic:7d:opus":"주간","anthropic:7d:sonnet":"주간"};function lD({confirmId:e,pending:t,primaryRef:n,summary:i,onConfirm:s,onCancel:a}){return(0,r.jsxs)("div",{className:"resource-reset resource-reset-confirm-group","data-reset-state":t?"pending":"confirming","data-dismissible-layer":!0,role:"group","aria-label":"리셋 사용 확인",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),a())},children:[(0,r.jsxs)("p",{className:"m-0 text-xs leading-5 text-text-muted",children:["저장된 리셋 ",i]}),(0,r.jsx)("p",{id:e,className:"m-0 text-xs leading-5 text-text",children:"리셋 1개를 지금 사용합니다. 되돌릴 수 없습니다."}),(0,r.jsx)("p",{className:"m-0 mt-1 text-xs leading-5 text-text-muted",children:"이 계정의 차단 기록도 함께 지워집니다."}),(0,r.jsxs)("div",{className:"mt-2 flex flex-wrap justify-end gap-2",children:[(0,r.jsx)("button",{ref:n,type:"button",className:lC(lS,"resource-reset-confirm"),"aria-describedby":e,disabled:t,onClick:s,children:t?"사용 중…":"리셋 사용"}),(0,r.jsx)("button",{type:"button",className:lS,disabled:t,onClick:a,children:"취소"})]})]})}function l_({report:e,brokerOk:t,now:n,active:s,identity:a,recommendation:o,pendingAction:l,feedback:d,onToggle:c,onReset:u}){let p=e.metadata??{},h=a??t0([e])[0],m=e.credentialId,f=Number.isSafeInteger(m)&&m>0,g=e.accountRole,x="usage-only"===g?"사용량":"control-only"===g?"계정 제어":p.planType,v=!0!==e.disabled&&"number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,b=s?"active":e.disabled?"off":v?"auto-blocked":"idle",y="toggle"===l?"전환 중…":"reset"===l?"리셋 사용 중…":f?s?"현재 사용 \xb7 이 세션":e.disabled?"꺼둠":v?`자동 차단 \xb7 ${lI(e.autoBlockedUntilMs,n)}`:"control-only"===g?"로그인 계정 \xb7 ON/OFF 제어":"대기":"usage-only"===g?"할당량 정보 \xb7 계정 연결 없음":"제어 불가 \xb7 credential id 없음",w=(0,i.useId)(),k=(0,i.useId)(),[j,S]=(0,i.useState)(!1),[C,I]=(0,i.useState)(!1),[T,N]=(0,i.useState)(null),M=(0,i.useRef)(null),R=(0,i.useRef)(null),E=(0,i.useRef)(!1),$=(0,i.useRef)(!1),L="openai-codex"===e.provider||"anthropic"===e.provider?e.savedReset:void 0,A=function(e){let t=e.savedReset?.credits??[],n=null;for(let e of t){if(!e.id)continue;let t=e.expiresAt?Date.parse(e.expiresAt):NaN,r=Number.isFinite(t)?t:null;(!n||null!=r&&(null==n.timestamp||r<n.timestamp))&&(n={id:e.id,expiresAt:e.expiresAt,timestamp:r})}return n?{id:n.id,expiresAt:n.expiresAt}:null}(e),P=A?.id??null,z=lT(A?.expiresAt??null,n),W=L?.availableCount,F=L&&"unavailable"!==L.state?"empty"===L.state||0===W?"없음":`${W??L.credits.length}개${z?` \xb7 ${z}`:""}`:"확인 불가",D=function(e){if("anthropic"!==e.provider)return null;let t=e.savedReset,n=t?.credits.find(e=>e.id===t.nextCreditId)??t?.credits[0],r=[...new Set((n?.clears??[]).map(e=>lF[e]).filter(e=>void 0!==e))];return r.length?`${r.join("\xb7")} 한도만`:null}(e),_=function(e,t){if(!e)return null;if("blocked-account"===e.reason){if(e.scope)return`권고 — ${e.scope}가 소진됐습니다. 저장된 리셋권 사용을 검토하세요.`;let n="number"==typeof e.naturalResetAt?lI(e.naturalResetAt,t).replace(/ 후 리셋$/,""):null;return n?`권고 — 지금 쓸 수 있는 다른 계정이 없고 자연 리셋까지 ${n} 남았습니다.`:"권고 — 지금 쓸 수 있는 다른 계정이 없어 저장된 리셋 사용을 검토하세요."}let n=lT(e.expiresAt??null,t),r="number"==typeof e.usedFraction?` 현재 ${Math.round(100*e.usedFraction)}% 소모한 ${"weekly"===e.window?"주간":"5시간"} 한도를 초기화할 수 있습니다.`:"";return`권고 — 리셋 1개가 ${n&&"만료됨"!==n?n:"곧 만료"}됩니다.${r}`}(o,n),B=("openai-codex"===e.provider||"anthropic"===e.provider)&&t&&!0!==e.disabled&&L?.state==="available"&&0!==W&&null!=P;(0,i.useLayoutEffect)(()=>{if(T)return void R.current?.focus();if(E.current){var e;E.current=!1,e=M.current,e?.focus()}},[T]),(0,i.useEffect)(()=>{"reset"!==l&&(e.disabled||!t||L?.state!=="available")&&(E.current=!1,N(null))},[t,l,e.disabled,L?.state]);let O=async()=>{if(T&&!$.current){$.current=!0;try{await u(e,T.creditId)}finally{$.current=!1,E.current=!0,N(null)}}},H=(e.limits??[]).reduce((e,t)=>{let r=t.window?.resetsAt;return"number"!=typeof r||r<=n?e:null==e||r<e?r:e},null),U=l?"pending":s?"active":e.disabled?"off":v?"blocked":"idle";return(0,r.jsxs)("section",{className:"resource-account border-b border-border-strong px-4 py-3 last:border-b-0","data-account-state":b,"aria-current":s?"true":void 0,children:[(0,r.jsxs)("div",{className:"resource-account-head flex min-w-0 items-start gap-2.5",children:[(0,r.jsx)(nx,{seed:h.seed,size:48,provider:e.provider}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("h3",{className:"m-0 flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-sm font-semibold text-text",children:[(0,r.jsx)("span",{children:h.alias}),(0,r.jsx)("span",{className:"min-w-0 truncate text-xs font-normal text-text-muted",children:`${tQ(e.provider)}${x?` \xb7 ${x}`:""}`})]}),(0,r.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[(0,r.jsx)("span",{className:"resource-account-state resource-account-badge","data-tone":U,role:l?"status":void 0,children:y}),null!=H&&H-n<=72e5?(0,r.jsx)("span",{className:"usage-chip",children:`곧 리셋 \xb7 ${lI(H,n).replace(/ 후 리셋$/,"")}`}):null]})]}),f?(0,r.jsxs)("span",{className:"resource-account-toggle",children:[(0,r.jsx)("span",{className:"resource-account-toggle-label",children:"사용 설정"}),(0,r.jsx)("button",{type:"button",role:"switch",className:lC(lS,"resource-account-switch min-w-[3.25rem]"),disabled:null!=l||!t,"aria-label":`${h.alias} 계정 사용 설정`,"aria-checked":!e.disabled,"aria-busy":null!=l||void 0,title:t?void 0:"제어 서버에 연결할 수 없습니다.",onClick:()=>{E.current=!1,N(null),c(e)},children:e.disabled?"OFF":"ON"})]}):null]}),e.disabled?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:"다른 계정이 있으면 이 계정을 사용하지 않습니다."}):v?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:(e.limits??[]).some(tH)?"한도를 다 써서 코어가 자동으로 차단했습니다.":"한도는 남아 있지만 토큰 갱신 실패나 일시 오류로 코어가 잠시 막았습니다. 해제 시각이 지나면 다시 씁니다."}):null,d?(0,r.jsx)("div",{className:"mt-2 text-xs text-text",role:"error"===d.tone?"alert":"status",children:d.message}):null,(0,r.jsxs)("div",{id:k,className:"resource-account-limits divide-y divide-border",children:[j?(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3 py-2",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"계정"}),(0,r.jsxs)("span",{className:"flex min-w-0 items-baseline gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 truncate font-mono text-xs text-text",children:C?h.raw:h.masked||"—"}),h.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-reveal","aria-pressed":C,onClick:()=>I(!C),children:C?"가리기":"이메일 보기"}):null]})]}):null,(e.limits??[]).map(e=>(0,r.jsx)(lW,{limit:e,now:n,detailed:j},e.id))]}),(e.limits??[]).length>0||h.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-more","aria-expanded":j,"aria-controls":k,onClick:()=>{let e=!j;S(e),e||I(!1)},children:j?"간단히":"자세히"}):null,"openai-codex"===e.provider||"anthropic"===e.provider?T?(0,r.jsx)(lD,{confirmId:w,pending:"reset"===l,primaryRef:R,summary:T.summary,onConfirm:()=>{O()},onCancel:()=>{E.current=!0,N(null)}}):(0,r.jsxs)("div",{className:"resource-reset mt-3 border-t border-border pt-2.5","data-reset-state":t?L&&"unavailable"!==L.state?"empty"===L.state||0===W?"empty":"reset"===l?"pending":"ready":"unavailable":"offline",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1.5",children:[(0,r.jsxs)("div",{className:"flex min-w-[10.5rem] flex-1 items-baseline justify-between gap-x-3",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"저장된 리셋"}),(0,r.jsx)("span",{className:lC("font-mono text-xs tabular-nums text-text",o?.reason==="expiring-credit"&&"text-warning"),children:F})]}),D?(0,r.jsx)("span",{className:"text-xs text-text-muted",children:D}):null,B?(0,r.jsx)("button",{ref:M,type:"button",className:lC(lS,"ml-auto flex-none"),disabled:null!=l,onClick:()=>{P&&N({creditId:P,summary:F})},children:"리셋 사용"}):t&&e.disabled&&L?.state==="available"?(0,r.jsx)("span",{className:"ml-auto text-xs text-text-muted",children:"켠 뒤 사용 가능"}):null]}),_?(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs leading-5 text-text-muted",children:_}):null]}):null]})}function lB({state:e,loading:t,accountState:n,pendingActions:i,feedbackByCredential:s,onToggle:a,onReset:o}){let l=lj(1e4),d=e.data,c=n?.state==="resolved"&&"session-pin"===n.source&&Number.isSafeInteger(n.credentialId)&&n.credentialId>0?n.credentialId:null,u=t0(d?.reports??[]),p=null==c?-1:d?.reports.findIndex(e=>e.credentialId===c)??-1;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lP,{state:e,loading:t,subject:"사용량"}),d?.brokerOk===!1?(0,r.jsx)("div",{className:"border-b border-border bg-bg px-4 py-2 text-xs text-text-muted",role:"status",children:"제어 서버에 연결할 수 없어 계정 전환과 리셋 사용을 잠시 쓸 수 없습니다. 사용량 표시는 계속 갱신됩니다."}):null,(0,r.jsxs)("div",{className:"flex min-h-7 items-center gap-4 border-b border-border bg-bg-raised px-4 text-[11px] font-semibold tracking-[0.08em] text-text-muted uppercase","aria-label":"사용량 그래프 범례",children:[(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric","aria-hidden":"true"}),"누적"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric-recent","aria-hidden":"true"}),"이번 구간"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"h-3 w-0.5 bg-text","aria-hidden":"true"}),"페이스"]})]}),d&&0===d.reports.length?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"인증된 계정의 사용량 정보가 없습니다. `omp usage`로 확인하세요."}):null,d?.reports.map((e,t)=>{let c=e.credentialId;return(0,r.jsx)(l_,{report:e,brokerOk:!0===d.brokerOk,now:l,active:t===p,identity:u[t],recommendation:null==c?void 0:n?.resetRecommendations.find(e=>e.credentialId===c),pendingAction:null==c?null:i.get(c)??null,feedback:null==c?void 0:s.get(c),onToggle:a,onReset:o},`${e.provider}:${c??e.metadata?.accountId??e.metadata?.email??t}`)})]})}function lO({model:e}){let t=Math.max(1,Math.min(100,100*e.costShare));return(0,r.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,r.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,r.jsx)("h3",{className:"m-0 min-w-0 flex-1 truncate text-sm font-semibold text-text",title:e.model,children:e.model}),(0,r.jsx)("span",{className:"text-xs text-text-muted",children:e.provider}),(0,r.jsxs)("span",{className:"font-mono text-xs tabular-nums text-text",children:[lN(e.cost)," \xb7 ",lE(e.costShare)]})]}),(0,r.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-full bg-metric",style:{width:`${t}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(lA,{label:"요청",value:lM(e.requests)}),(0,r.jsx)(lA,{label:"요청당",value:lN(e.costPerRequest)}),(0,r.jsx)(lA,{label:"토큰/요청",value:lR(e.tokensPerRequest)}),(0,r.jsx)(lA,{label:"출력/요청",value:lR(e.outputPerRequest)}),(0,r.jsx)(lA,{label:"캐시율",value:lE(e.cacheRate,1)}),(0,r.jsx)(lA,{label:"TTFT",value:l$(e.avgTtft)})]})]})}function lH({agent:e}){let t={main:"메인",subagent:"SubAgent",advisor:"advisor"}[e.agentType]??e.agentType,n=Math.max(1,Math.min(100,100*e.costShare));return(0,r.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3",children:[(0,r.jsx)("h3",{className:"m-0 text-sm font-semibold text-text",children:t}),(0,r.jsxs)("span",{className:"font-mono text-xs tabular-nums text-text",children:[lN(e.cost)," \xb7 ",lE(e.costShare)]})]}),(0,r.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-full bg-metric",style:{width:`${n}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(lA,{label:"요청",value:lM(e.requests)}),(0,r.jsx)(lA,{label:"요청당",value:lN(e.costPerRequest)}),(0,r.jsx)(lA,{label:"토큰/요청",value:lR(e.tokensPerRequest)})]})]})}function lU({day:e}){let t=e.models.slice(0,3).map(e=>e.model).join(", ");return(0,r.jsxs)("div",{className:"grid grid-cols-[auto_minmax(0,1fr)_auto] items-baseline gap-3 border-b border-border px-4 py-2 last:border-b-0",children:[(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text-muted",children:lL(e.timestamp)}),(0,r.jsx)("span",{className:"truncate text-xs text-text-muted",title:t,children:t}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:lN(e.cost)})]})}function lq({state:e,loading:t}){let n=e.data;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lP,{state:e,loading:t,subject:"모델 집계"}),n?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{"aria-labelledby":"resource-overall-heading",children:[(0,r.jsx)("h2",{id:"resource-overall-heading",className:"m-0 border-b border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"전체"}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4 px-4 py-3",children:[(0,r.jsx)(lA,{label:"요청",value:lM(n.overall.requests)}),(0,r.jsx)(lA,{label:"비용",value:lN(n.overall.cost)}),(0,r.jsx)(lA,{label:"토큰",value:lR(n.overall.tokens)}),(0,r.jsx)(lA,{label:"캐시율",value:lE(n.overall.cacheRate,1)}),(0,r.jsx)(lA,{label:"캐시 절감",value:lE(n.overall.cacheSavings,1)}),(0,r.jsx)(lA,{label:"평균 TTFT",value:l$(n.overall.avgTtft)})]})]}),(0,r.jsxs)("section",{"aria-labelledby":"resource-models-heading",children:[(0,r.jsx)("h2",{id:"resource-models-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"모델별"}),n.models.length?n.models.map(e=>(0,r.jsx)(lO,{model:e},`${e.provider}:${e.model}`)):(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"모델 기록이 없습니다."})]}),(0,r.jsxs)("section",{"aria-labelledby":"resource-agents-heading",children:[(0,r.jsx)("h2",{id:"resource-agents-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"에이전트 종류별"}),n.agents.length?n.agents.map(e=>(0,r.jsx)(lH,{agent:e},e.agentType)):(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"기록이 없습니다."})]}),n.daily.length?(0,r.jsxs)("section",{"aria-labelledby":"resource-daily-heading",children:[(0,r.jsx)("h2",{id:"resource-daily-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"일별 비용"}),n.daily.map(e=>(0,r.jsx)(lU,{day:e},e.timestamp))]}):null,(0,r.jsx)("p",{className:"m-0 border-t border-border px-4 py-3 text-xs leading-5 text-text-dim",children:"`omp stats` 기준 누적값입니다. 구독 한도 %는 계정 한도 탭에서 확인하세요."})]}):null]})}function lV({reports:e,providerConnections:t}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{className:"character-roster-intro","aria-labelledby":"character-roster-heading",children:[(0,r.jsx)("h2",{id:"character-roster-heading",children:"호출 가능한 캐릭터"}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"호출\xb7불러\xb7소환"}),"은 캐릭터를 SubAgent로 이 대화에 부릅니다.",(0,r.jsx)("strong",{children:" 교체"}),"는 이 대화의 Main을 바꿉니다."]})]}),(0,r.jsx)("div",{className:"character-roster",role:"list","aria-label":"호출 가능한 캐릭터 목록",children:tq.map(n=>{let i=`character-roster-${n.seed}`,s=`character-roster-${n.seed}-status`,a=`${n.provider}/${n.model}`,o=!1,l=!1;if(e){for(let t of e)if(t.provider===n.provider&&(o=!0,!0!==t.disabled)){l=!0;break}}let d="web6"!==n.provider&&(t?.get(n.provider)===!1||o&&!l);return(0,r.jsxs)("article",{className:lC("character-roster-item",d&&"is-unavailable"),role:"listitem","aria-labelledby":i,"aria-describedby":d?s:void 0,children:[(0,r.jsxs)("div",{className:"character-roster-identity",children:[(0,r.jsx)(nx,{seed:n.seed,size:48,provider:n.provider}),(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{id:i,children:n.alias}),d?(0,r.jsx)("span",{id:s,className:"character-roster-availability",children:"연결 안 됨"}):null,(0,r.jsx)("p",{children:n.voice})]})]}),(0,r.jsxs)("dl",{className:"character-roster-model",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"모델"}),(0,r.jsx)("dd",{title:a,children:a})]}),void 0!==n.oauthPosition?(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"계정"}),(0,r.jsxs)("dd",{children:["OAuth ",n.oauthPosition]})]}):null]}),(0,r.jsxs)("dl",{className:"character-roster-examples",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"호출"}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("code",{children:n.summonExample}),(0,r.jsx)("span",{children:n.summonNote??"SubAgent로 이 대화에 부릅니다."})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"Main 교체"}),(0,r.jsxs)("dd",{children:[n.switchExample?(0,r.jsx)("code",{children:n.switchExample}):(0,r.jsx)("strong",{children:"교체 불가"}),(0,r.jsx)("span",{children:n.switchNote??"이 대화의 Main을 바꿉니다."})]})]})]})]},n.alias)})})]})}function lK({open:e,sessionId:t,activeTab:n,onTabChange:s,usage:o,className:l}){let d=(0,i.useId)(),c=o.state,u=o.loading,[p,h]=(0,i.useState)({status:"idle",data:null,error:null}),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(()=>new Map),[k,j]=(0,i.useState)(()=>new Map),S=(0,i.useRef)(p),C=(0,i.useRef)(null),I=(0,i.useRef)(null),T=(0,i.useRef)(new Set),N=(0,i.useRef)(new Set);S.current=p,(0,i.useEffect)(()=>{if(!e||"characters"!==n)return;let t=new AbortController;return b(null),Promise.all([fetch("/api/auth/all-providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()}),fetch("/api/auth/providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()})]).then(([e,n])=>{if(t.signal.aborted)return;let r=new Map(e.providers.map(e=>[e.id,e.configured]));for(let e of n.providers)r.set(e.id,!0===r.get(e.id)||e.loggedIn);b(r)}).catch(()=>{t.signal.aborted||b(null)}),()=>t.abort()},[n,e,c.data]),(0,i.useEffect)(()=>{var r;let i,s,a,o,l,d,c,u,p,h;if(f(null),!e||"usage"!==n||!t)return;let m=(s=(r={onClear(){f(null)},onResult(e){f("fresh"===e.status?e.data:null)}}).intervalMs??2500,a=r.setIntervalImpl??setInterval,o=r.clearIntervalImpl??clearInterval,l=null,d=null,c=0,u=!1,p=()=>{o(i),i=void 0},h=async e=>{d?.abort();let t=d=new AbortController,n=++c,i=await ne(e,{signal:t.signal,fetchImpl:r.fetchImpl});u||n!==c||l!==e||t.signal.aborted||r.onResult(i)},{setSessionId(e){u||e===l||(c+=1,d?.abort(),d=null,p(),l=e,r.onClear(e),e&&(h(e),i=a(()=>{l&&h(l)},s)))},stop(){u||(u=!0,c+=1,d?.abort(),d=null,p(),l=null)}});return C.current=m,m.setSessionId(t),()=>{m.stop(),C.current===m&&(C.current=null)}},[n,e,t]);let M=(0,i.useCallback)(async e=>{I.current?.abort();let t=new AbortController;I.current=t,x(!0);let n=await nt({refresh:e,previous:S.current.data,signal:t.signal});I.current!==t||t.signal.aborted||(h(n),x(!1))},[]);(0,i.useEffect)(()=>{e&&"models"===n&&("idle"===S.current.status||"error"===S.current.status)&&M(!1)},[n,e,M]),(0,i.useEffect)(()=>()=>{for(let e of(I.current?.abort(),T.current))e.abort()},[]);let R=(0,i.useCallback)(()=>{"models"===n?M(!0):o.refresh()},[n,M,o]),E=(0,i.useCallback)(()=>o.refresh(),[o]),$=(0,i.useCallback)(async e=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let t=e.credentialId,n=ni(N.current,t);if(!n)return;let r=new AbortController;T.current.add(r),o.setPaused(!0),w(e=>new Map(e).set(t,"toggle")),j(e=>{let n=new Map(e);return n.delete(t),n});try{await nn(t,!0===e.disabled,{signal:r.signal});let n=await E();r.signal.aborted||j(r=>new Map(r).set(t,{tone:"status",message:"fresh"===n.status?`계정을 ${e.disabled?"켰습니다":"껐습니다"}.`:"계정 설정 저장됨 \xb7 표시 상태 새로고침 실패."}))}catch(e){if(!r.signal.aborted){let n=e instanceof t1&&("timeout"===e.kind||e.outcomeUnknown);j(r=>new Map(r).set(t,n?{tone:"error",message:"적용 여부 확인 필요 — 새로고침으로 계정 상태를 확인하세요."}:{tone:"error",message:`계정 전환 실패: ${e instanceof Error?e.message:String(e)}`}))}}finally{T.current.delete(r),n(),o.setPaused(N.current.size>0),w(e=>{let n=new Map(e);return n.delete(t),n})}},[E,o]),L=(0,i.useCallback)(async(e,t)=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let n=e.credentialId,r=ni(N.current,n);if(!r)return;let i=new AbortController;T.current.add(i),o.setPaused(!0),w(e=>new Map(e).set(n,"reset")),j(e=>{let t=new Map(e);return t.delete(n),t});try{let e=await nr(n,t,{signal:i.signal}),r=function(e){switch(e.code){case"reset":return{tone:"status",message:"리셋 사용함"};case"no_credit":return{tone:"status",message:"사용할 수 있는 리셋이 없습니다."};case"already_redeemed":return{tone:"status",message:"이미 사용된 리셋입니다."};case"nothing_to_reset":return{tone:"status",message:"지금은 초기화할 한도가 없습니다."};case"ineligible":return{tone:"status",message:"지금은 이 리셋을 쓸 수 없습니다(한도 미도달 또는 자격 없음)."};case"cooldown":return{tone:"status",message:"리셋 재사용 대기 중입니다. 잠시 뒤 다시 시도하세요."};case"offer_changed":return{tone:"status",message:"리셋 목록이 바뀌었습니다. 새로고침 후 다시 시도하세요."};case"rate_limited":return{tone:"error",message:"리셋 사용 실패: 요청이 많아 잠시 막혔습니다."};case"reset_unconfirmed":return{tone:"error",message:"이전 리셋 요청 결과를 아직 확인하지 못했습니다. 잠시 뒤 확인하세요."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return e.code.startsWith("http_")?{tone:"error",message:`리셋 사용 실패: 서비스 응답 오류 (${e.code})`}:{tone:"error",message:`리셋 사용 실패: ${e.code}`}}}(e),s=await E();if(e.ok){let e="fresh"===s.status?s.data.reports.find(e=>e.credentialId===n):void 0,t=e?.savedReset?.availableCount;r.message="number"==typeof t?`리셋 사용함 \xb7 남은 리셋 ${t}개`:"리셋 사용함 \xb7 남은 개수를 확인하지 못했습니다."}i.signal.aborted||j(e=>new Map(e).set(n,r))}catch(e){e instanceof t1&&(e.outcomeUnknown||"timeout"===e.kind)&&!i.signal.aborted&&await E(),i.signal.aborted||j(t=>new Map(t).set(n,function(e){if(e instanceof t1){if(e.outcomeUnknown||"timeout"===e.kind)return{tone:"error",message:"적용 여부 확인 필요 — 자동으로 다시 시도하지 않았습니다. 새로고침으로 남은 개수를 확인하세요."};switch(e.code){case"account_disabled":return{tone:"error",message:"리셋 사용 실패: 꺼둔 계정에서는 사용할 수 없습니다."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return{tone:"error",message:`리셋 사용 실패: ${e.message}`}}}return{tone:"error",message:`리셋 사용 실패: ${e instanceof Error?e.message:String(e)}`}}(e)))}finally{T.current.delete(i),r(),o.setPaused(N.current.size>0),w(e=>{let t=new Map(e);return t.delete(n),t})}},[E,o]);if(!e)return null;let A="models"===n?p.data?.generatedAt:c.data?.generatedAt,P="models"===n?p.data?.range:void 0,z=P?.from&&P.to?`${lL(P.from)}~${lL(P.to)}`:A?new Date(A).toLocaleTimeString():"",W="models"===n?g:"usage"===n&&u,F=W?"models"===n?"집계 중…":"불러오는 중…":"새로고침";return(0,r.jsxs)("section",{className:lC("resource-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",l),"aria-labelledby":d,"aria-busy":W,children:[(0,r.jsx)("h1",{id:d,className:"sr-only",children:"캐릭터"}),(0,r.jsxs)(o1.J.Root,{className:"resource-view-tabs",size:"small",contentLayout:"fill",triggerLayout:"fill",value:n,onValueChange:e=>s(e),children:[(0,r.jsxs)(o1.J.List,{"aria-label":"캐릭터와 사용량 보기",children:[(0,r.jsx)(o1.J.Trigger,{value:"characters",children:"캐릭터"}),(0,r.jsx)(o1.J.Trigger,{value:"usage",children:"계정 한도"}),(0,r.jsx)(o1.J.Trigger,{value:"models",children:"모델 통계"}),(0,r.jsx)(o1.J.Indicator,{})]}),(0,r.jsx)(o1.J.Content,{value:"characters",className:"resource-view-content",children:(0,r.jsx)(lV,{reports:c.data?.reports,providerConnections:v})}),(0,r.jsxs)(o1.J.Content,{value:"usage",className:"resource-view-content",children:[(0,r.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:z}),(0,r.jsx)(a.r,{variant:"neutralWeak",size:"xsmall",onClick:R,disabled:W,children:F})]}),(0,r.jsx)("h2",{className:"resource-group-heading",children:"계정 한도"}),(0,r.jsx)(lB,{state:c,loading:u,accountState:m?.sessionId===t?m:null,pendingActions:y,feedbackByCredential:k,onToggle:e=>{$(e)},onReset:L})]}),(0,r.jsxs)(o1.J.Content,{value:"models",className:"resource-view-content",children:[(0,r.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:z}),(0,r.jsx)(a.r,{variant:"neutralWeak",size:"xsmall",onClick:R,disabled:W,children:F})]}),(0,r.jsx)(lq,{state:p,loading:g})]})]})]})}let lJ="/api/runs";class lG extends Error{constructor(e,t,n=null){super(t),this.name="EfficiencyClientError",this.kind=e,this.status=n}}let lY=["completed","error","aborted","interrupted","running"],lZ=["main","maker","checker","advisor","unattributed"],lX=["primary","rework","review"],lQ=["wait-attribution","unpriced-cost","effort-unrecorded","role-unattributed","busy-unrecorded"],l0=["all","attributed"];function l1(e){return"object"==typeof e&&null!==e}function l2(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function l8(e){return!!l1(e)&&"string"==typeof e.runId&&"string"==typeof e.sessionId&&"string"==typeof e.entryId&&"number"==typeof e.index&&Number.isFinite(e.index)&&(null===e.title||"string"==typeof e.title)&&"number"==typeof e.startedAt&&Number.isFinite(e.startedAt)&&(null===e.endedAt||"number"==typeof e.endedAt&&Number.isFinite(e.endedAt))&&"number"==typeof e.wallClockMs&&Number.isFinite(e.wallClockMs)&&"string"==typeof e.outcome&&lY.includes(e.outcome)&&"number"==typeof e.busyMs&&Number.isFinite(e.busyMs)&&"number"==typeof e.childCount&&Number.isFinite(e.childCount)&&"number"==typeof e.totalTokens&&Number.isFinite(e.totalTokens)&&"number"==typeof e.estimatedCostUsd&&Number.isFinite(e.estimatedCostUsd)&&"number"==typeof e.unpricedRequests&&Number.isFinite(e.unpricedRequests)&&"string"==typeof e.configSignature}function l4(e){return!!l1(e)&&"string"==typeof e.id&&"string"==typeof e.kind&&lZ.includes(e.kind)&&(null===e.purpose||"string"==typeof e.purpose&&lX.includes(e.purpose))&&l2(e.models)&&l2(e.efforts)&&"number"==typeof e.requestCount&&Number.isFinite(e.requestCount)&&"number"==typeof e.busyMs&&Number.isFinite(e.busyMs)&&"number"==typeof e.spanMs&&Number.isFinite(e.spanMs)&&"number"==typeof e.startedAt&&Number.isFinite(e.startedAt)&&"number"==typeof e.endedAt&&Number.isFinite(e.endedAt)&&"number"==typeof e.inputTokens&&Number.isFinite(e.inputTokens)&&"number"==typeof e.outputTokens&&Number.isFinite(e.outputTokens)&&"number"==typeof e.cacheReadTokens&&Number.isFinite(e.cacheReadTokens)&&"number"==typeof e.cacheWriteTokens&&Number.isFinite(e.cacheWriteTokens)&&"number"==typeof e.totalTokens&&Number.isFinite(e.totalTokens)&&"number"==typeof e.estimatedCostUsd&&Number.isFinite(e.estimatedCostUsd)&&"number"==typeof e.unpricedRequests&&Number.isFinite(e.unpricedRequests)&&"number"==typeof e.untimedRequests&&Number.isFinite(e.untimedRequests)&&"number"==typeof e.errorCount&&Number.isFinite(e.errorCount)&&"number"==typeof e.abortedCount&&Number.isFinite(e.abortedCount)&&"number"==typeof e.toolCalls&&Number.isFinite(e.toolCalls)}function l5(e){return!!l1(e)&&("role-busy"===e.kind||"unmeasured-gap"===e.kind)&&"string"==typeof e.id&&"number"==typeof e.ms&&Number.isFinite(e.ms)&&"number"==typeof e.relative&&Number.isFinite(e.relative)}function l6(e){return!!l1(e)&&"string"==typeof e.toolName&&"number"==typeof e.calls&&Number.isFinite(e.calls)&&"number"==typeof e.errors&&Number.isFinite(e.errors)}function l3(e){return!!l1(e)&&"string"==typeof e.kind&&lZ.includes(e.kind)&&"string"==typeof e.model&&(null===e.effort||"string"==typeof e.effort)&&"number"==typeof e.count&&Number.isFinite(e.count)}function l7(e){return!!l1(e)&&"string"==typeof e.signature&&Array.isArray(e.roles)&&e.roles.every(l3)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.medianWallClockMs&&Number.isFinite(e.medianWallClockMs)&&"number"==typeof e.medianBusyMs&&Number.isFinite(e.medianBusyMs)&&"number"==typeof e.medianTotalTokens&&Number.isFinite(e.medianTotalTokens)&&"number"==typeof e.medianEstimatedCostUsd&&Number.isFinite(e.medianEstimatedCostUsd)&&"number"==typeof e.totalEstimatedCostUsd&&Number.isFinite(e.totalEstimatedCostUsd)&&"number"==typeof e.unpricedRuns&&Number.isFinite(e.unpricedRuns)&&"number"==typeof e.untimedRuns&&Number.isFinite(e.untimedRuns)&&"number"==typeof e.reworkRuns&&Number.isFinite(e.reworkRuns)&&"number"==typeof e.errorRuns&&Number.isFinite(e.errorRuns)&&"number"==typeof e.childRunsAvg&&Number.isFinite(e.childRunsAvg)&&"number"==typeof e.firstSeenAt&&Number.isFinite(e.firstSeenAt)&&"number"==typeof e.lastSeenAt&&Number.isFinite(e.lastSeenAt)}function l9(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e&&lQ.includes(e))}async function de(e){try{return await e.json()}catch{throw new lG("invalid-response","효율 응답 JSON을 해석할 수 없습니다.",e.status)}}function dt(e,t){return e instanceof lG||e instanceof Error?e.message:t}let dn={completed:"positive",error:"critical",aborted:"warning",interrupted:"warning",running:"informative"},dr={main:"informative",maker:"neutral",checker:"neutral",advisor:"neutral",unattributed:"warning"};function di(...e){return e.filter(Boolean).join(" ")}function ds(e){return"number"==typeof e&&Number.isFinite(e)?0===e?"$0":e>=100?`$${e.toFixed(0)}`:e>=1?`$${e.toFixed(2)}`:e>=.01?`$${e.toFixed(3)}`:`$${e.toFixed(4)}`:"—"}function da(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function dl(e){return"number"==typeof e&&Number.isFinite(e)?e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e)):"—"}function dd(e){if("number"!=typeof e||!Number.isFinite(e))return"—";let t=Math.max(0,e);if(t<1e3)return`${Math.round(t)}ms`;let n=Math.round(t/1e3);if(n<60)return`${(t/1e3).toFixed(1)}s`;let r=Math.floor(n/60),i=n-60*r;return r<60?0===i?`${r}m`:`${r}m ${i}s`:`${Math.floor(r/60)}h ${r%60}m`}function dc(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function du({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 border-b border-border py-1.5 last:border-b-0",children:[(0,r.jsx)("dt",{className:"min-w-0 flex-1 truncate text-xs text-text-muted",children:e}),(0,r.jsx)("dd",{className:"m-0 flex-none font-mono text-xs tabular-nums text-text",children:t})]})}function dp({share:e,label:t}){let n=Number.isFinite(e)?Math.max(1,Math.min(100,100*e)):1;return(0,r.jsxs)("div",{className:"efficiency-bar","aria-hidden":"true",children:[(0,r.jsx)("div",{className:"efficiency-bar-fill",style:{width:`${n}%`}}),(0,r.jsx)("span",{className:"efficiency-bar-value",children:t})]})}function dh({costUsd:e,unpriced:t,t:n}){return(0,r.jsxs)("span",{className:"font-mono tabular-nums",children:[n("efficiency.estimatedCostValue").replace("{value}",ds(e)),t>0?` \xb7 ${n("efficiency.unpricedLowerBound")}`:""]})}function dm({outcome:e,t}){return(0,r.jsx)(o2.E,{tone:dn[e],variant:"weak",size:"medium",children:t({completed:"efficiency.outcomeCompleted",error:"efficiency.outcomeError",aborted:"efficiency.outcomeAborted",interrupted:"efficiency.outcomeInterrupted",running:"efficiency.outcomeRunning"}[e])})}function df({purpose:e,t}){return null===e?(0,r.jsx)("span",{className:"efficiency-dim",children:t("efficiency.unmeasuredShort")}):(0,r.jsx)(o2.E,{tone:"rework"===e?"warning":"neutral",variant:"weak",size:"medium",children:t({primary:"efficiency.purposePrimary",rework:"efficiency.purposeRework",review:"efficiency.purposeReview"}[e]??"efficiency.unmeasuredShort")})}function dg({run:e,selected:t,onSelect:n,t:i}){let s=e.title&&e.title.trim().length>0?e.title:i("efficiency.noTitle");return(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",onClick:n,"aria-current":t?"true":void 0,className:di("efficiency-run-item",t&&"is-selected"),children:[(0,r.jsxs)("span",{className:"efficiency-run-top",children:[(0,r.jsxs)("span",{className:"efficiency-run-index",children:["#",e.index]}),(0,r.jsx)("span",{className:"efficiency-run-title",title:s,children:s}),(0,r.jsx)(dm,{outcome:e.outcome,t:i})]}),(0,r.jsxs)("span",{className:"efficiency-run-meta",children:[(0,r.jsx)("span",{className:"font-mono tabular-nums",children:i("efficiency.elapsedValue").replace("{value}",dd(e.wallClockMs))}),(0,r.jsx)(dh,{costUsd:e.estimatedCostUsd,unpriced:e.unpricedRequests,t:i})]})]})})}function dx({role:e,t}){let n=e.models.length>0?e.models.join(", "):t("efficiency.unmeasuredShort"),i=e.efforts.length>0?e.efforts.join(", "):t("efficiency.unmeasuredShort");return(0,r.jsxs)("section",{className:"efficiency-card",children:[(0,r.jsxs)("div",{className:"efficiency-card-top",children:[(0,r.jsx)("h4",{className:"efficiency-card-title",title:e.id,children:e.id}),(0,r.jsx)(o2.E,{tone:dr[e.kind]??"neutral",variant:"weak",size:"medium",children:t(`efficiency.role${"main"===e.kind?"Main":"maker"===e.kind?"Maker":"checker"===e.kind?"Checker":"advisor"===e.kind?"Advisor":"Unattributed"}`)}),(0,r.jsx)(df,{purpose:e.purpose,t:t})]}),(0,r.jsx)("p",{className:"efficiency-model-line",title:n,children:n}),(0,r.jsxs)("p",{className:"efficiency-dim",children:[t("efficiency.effortLabel").replace("{value}",i),` \xb7 ${t("efficiency.requestsValue").replace("{value}",String(e.requestCount))}`,` \xb7 ${t("efficiency.toolCallsValue").replace("{value}",String(e.toolCalls))}`]}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(du,{label:t("efficiency.busyTime"),value:dd(e.busyMs)}),(0,r.jsx)(du,{label:t("efficiency.estimatedCost"),value:ds(e.estimatedCostUsd)}),(0,r.jsx)(du,{label:t("efficiency.tokens"),value:dl(e.totalTokens)}),(0,r.jsx)(du,{label:t("efficiency.unpricedRequests"),value:da(e.unpricedRequests)})]}),e.untimedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.untimedLowerBound").replace("{value}",da(e.untimedRequests))}):null,e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unpricedLowerBound")}):null]})}function dv({item:e,t}){let n="unmeasured-gap"===e.kind?t("efficiency.unmeasuredGap"):e.id;return(0,r.jsxs)("li",{className:"efficiency-bottleneck",children:[(0,r.jsxs)("div",{className:"efficiency-bottleneck-top",children:[(0,r.jsx)("span",{className:"efficiency-bottleneck-label",title:n,children:n}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:dd(e.ms)})]}),(0,r.jsx)(dp,{share:e.relative,label:dd(e.ms)})]})}function db({detail:e,t}){return(0,r.jsxs)("div",{className:"efficiency-detail",children:[(0,r.jsxs)("section",{"aria-label":t("efficiency.summarySection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.summarySection")}),(0,r.jsxs)("div",{className:"efficiency-dual",children:[(0,r.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,r.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.elapsed")}),(0,r.jsx)("span",{className:"efficiency-dual-value",children:dd(e.wallClockMs)})]}),(0,r.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,r.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.busyTotal")}),(0,r.jsx)("span",{className:"efficiency-dual-value",children:dd(e.busyMs)})]})]}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.noSumNote")}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(du,{label:t("efficiency.estimatedCost"),value:ds(e.estimatedCostUsd)}),(0,r.jsx)(du,{label:t("efficiency.tokens"),value:dl(e.totalTokens)})]}),e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unpricedLowerBound")}):null]}),(0,r.jsxs)("section",{"aria-label":t("efficiency.rolesSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.rolesSection")}),e.roles.length>0?(0,r.jsx)("div",{className:"efficiency-stack",children:e.roles.map(e=>(0,r.jsx)(dx,{role:e,t:t},e.id))}):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.rolesEmpty")})]}),(0,r.jsxs)("section",{"aria-label":t("efficiency.bottlenecksSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.bottlenecksSection")}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.bottleneckOrderNote")}),e.bottlenecks.length>0?(0,r.jsx)("ul",{className:"efficiency-stack",children:e.bottlenecks.map(e=>(0,r.jsx)(dv,{item:e,t:t},`${e.kind}:${e.id}`))}):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.bottlenecksEmpty")}),e.unmeasuredMs>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unmeasuredGapValue").replace("{value}",dd(e.unmeasuredMs))}):null]}),e.toolTotals.length>0?(0,r.jsxs)("section",{"aria-label":t("efficiency.toolsSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.toolsSection")}),(0,r.jsx)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:e.toolTotals.map(e=>(0,r.jsx)(du,{label:`${e.toolName} \xb7 ${t("efficiency.toolErrorsValue").replace("{value}",String(e.errors))}`,value:da(e.calls)},e.toolName))})]}):null]})}function dy(e){return e.map(e=>{let t=e.effort??"–",n=e.count>1?` x${e.count}`:"";return`${e.kind} ${e.model}:${t}${n}`}).join(" \xb7 ")}function dw({response:e,t}){return(0,r.jsx)("section",{className:"efficiency-card",children:(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(du,{label:t("efficiency.scopeSessions"),value:da(e.sessionCount)}),(0,r.jsx)(du,{label:t("efficiency.scopeRuns"),value:da(e.runCount)}),(0,r.jsx)(du,{label:t("efficiency.scopeExcludedRuns"),value:da(e.excludedRunCount)})]})})}function dk({config:e,baselineRuns:t,t:n}){let i=t>0?e.runCount/t:0,s=e.runCount>0?e.reworkRuns/e.runCount:0,a=e.runCount>0?e.errorRuns/e.runCount:0;return(0,r.jsxs)("section",{className:"efficiency-card",children:[(0,r.jsx)("p",{className:"efficiency-model-line",title:dy(e.roles),children:dy(e.roles)}),(0,r.jsxs)("div",{className:"efficiency-bottleneck-top",children:[(0,r.jsx)("span",{className:"efficiency-dim",children:n("efficiency.runsValue").replace("{value}",String(e.runCount))}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:dc(i)})]}),(0,r.jsx)(dp,{share:i,label:dc(i)}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(du,{label:n("efficiency.medianElapsed"),value:dd(e.medianWallClockMs)}),(0,r.jsx)(du,{label:n("efficiency.medianBusy"),value:dd(e.medianBusyMs)}),(0,r.jsx)(du,{label:n("efficiency.medianTokens"),value:dl(e.medianTotalTokens)}),(0,r.jsx)(du,{label:n("efficiency.medianEstimatedCost"),value:ds(e.medianEstimatedCostUsd)}),(0,r.jsx)(du,{label:n("efficiency.totalEstimatedCost"),value:ds(e.totalEstimatedCostUsd)}),(0,r.jsx)(du,{label:n("efficiency.reworkRate"),value:dc(s,1)}),(0,r.jsx)(du,{label:n("efficiency.errorRate"),value:dc(a,1)}),(0,r.jsx)(du,{label:n("efficiency.unpricedRuns"),value:da(e.unpricedRuns)}),(0,r.jsx)(du,{label:n("efficiency.untimedRuns"),value:da(e.untimedRuns)})]}),e.untimedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.untimedMedianLowerBound").replace("{value}",da(e.untimedRuns))}):null,e.unpricedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.unpricedLowerBound")}):null]})}function dj({open:e,sessionId:t,activeTab:n,onTabChange:s,client:o,className:d}){let c=(0,i.useId)(),u=(0,i.useId)(),{t:p}=(0,E.s)(),h=function({sessionId:e,visible:t,activeTab:n,client:r}){let[s]=(0,i.useState)(()=>r??function(e=(e,t)=>fetch(e,t)){let t=async(t,n)=>{let r;try{r=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new lG("unreachable","효율 기록에 연결할 수 없습니다.")}let i=await de(r);if(!r.ok){var s;throw new lG("http",(s=`HTTP ${r.status}`,null!==i&&"object"==typeof i&&"error"in i&&"string"==typeof i.error&&i.error?i.error:s),r.status)}return{response:r,body:i}};return{async listRuns(e,n,r){let{response:i,body:s}=await t(`${lJ}?sessionId=${encodeURIComponent(e)}&limit=${encodeURIComponent(String(n))}`,{method:"GET",signal:r});return function(e,t,n=null){try{if(!l1(e)||!("string"==typeof e.sessionId&&Array.isArray(e.runs)&&e.runs.every(l8)&&l9(e.unmeasured)))throw new lG("invalid-response","실행 목록 응답이 올바르지 않습니다.");return e}catch{throw new lG("invalid-response",t,n)}}(s,"실행 목록 응답이 올바르지 않습니다.",i.status)},async getRun(e,n){let{response:r,body:i}=await t(`${lJ}/${encodeURIComponent(e)}`,{method:"GET",signal:n});return function(e,t,n=null){try{if(!l8(e)||!(Array.isArray(e.roles)&&e.roles.every(l4)&&Array.isArray(e.bottlenecks)&&e.bottlenecks.every(l5)&&"number"==typeof e.unmeasuredMs&&Number.isFinite(e.unmeasuredMs)&&Array.isArray(e.toolTotals)&&e.toolTotals.every(l6)&&l9(e.unmeasured)))throw new lG("invalid-response","실행 상세 응답이 올바르지 않습니다.");return e}catch{throw new lG("invalid-response",t,n)}}(i,"실행 상세 응답이 올바르지 않습니다.",r.status)},async listExperiments(e,n,r,i){let s=new URLSearchParams;null!==e&&""!==e&&s.set("folder",e),s.set("sessions",String(n)),s.set("scope",r);let{response:a,body:o}=await t(`/api/experiments?${s.toString()}`,{method:"GET",signal:i});return function(e,t,n=null){try{if(!l1(e)||!((null===e.folder||"string"==typeof e.folder)&&l2(e.folders)&&"string"==typeof e.scope&&l0.includes(e.scope)&&Array.isArray(e.configs)&&e.configs.every(l7)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.sessionCount&&Number.isFinite(e.sessionCount)&&"number"==typeof e.excludedRunCount&&Number.isFinite(e.excludedRunCount)&&l9(e.unmeasured)))throw new lG("invalid-response","구성 비교 응답이 올바르지 않습니다.");return e}catch{throw new lG("invalid-response",t,n)}}(o,"구성 비교 응답이 올바르지 않습니다.",a.status)}}}()),[a,o]=(0,i.useState)({status:"idle",runs:[],error:null}),[l,d]=(0,i.useState)({status:"idle",runId:null,detail:null,error:null}),[c,u]=(0,i.useState)({status:"idle",response:null,error:null}),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(null);(0,i.useEffect)(()=>{x.current?.abort(),x.current=null,h(null),d({status:"idle",runId:null,detail:null,error:null}),o({status:"idle",runs:[],error:null})},[e]);let y=(0,i.useCallback)(()=>{if(!t||"governor"!==n||!e)return;g.current?.abort();let r=new AbortController;g.current=r,o(e=>({status:"loading",runs:"ready"===e.status||"empty"===e.status?e.runs:[],error:null})),s.listRuns(e,20,r.signal).then(e=>{if(!r.signal.aborted&&g.current===r){if(0===e.runs.length)return void o({status:"empty",runs:[],error:null});o({status:"ready",runs:e.runs,error:null})}}).catch(e=>{r.signal.aborted||g.current!==r||o({status:"error",runs:[],error:dt(e,"실행 목록을 불러오지 못했습니다.")})})},[n,s,e,t]),w=(0,i.useCallback)(e=>{if(!t)return;x.current?.abort();let n=new AbortController;x.current=n,d({status:"loading",runId:e,detail:null,error:null}),s.getRun(e,n.signal).then(t=>{n.signal.aborted||x.current!==n||d({status:"ready",runId:e,detail:t,error:null})}).catch(t=>{n.signal.aborted||x.current!==n||d({status:"error",runId:e,detail:null,error:dt(t,"실행 상세를 불러오지 못했습니다.")})})},[s,t]),k=(0,i.useCallback)((e,r="all")=>{if(!t||"lab"!==n)return;v.current?.abort();let i=new AbortController;v.current=i,u(e=>({status:"loading",response:"ready"===e.status||"empty"===e.status?e.response:null,error:null})),s.listExperiments(e,30,r,i.signal).then(e=>{if(!i.signal.aborted&&v.current===i){if(0===e.configs.length)return void u({status:"empty",response:e,error:null});u({status:"ready",response:e,error:null})}}).catch(e=>{i.signal.aborted||v.current!==i||u({status:"error",response:null,error:dt(e,"구성 비교를 불러오지 못했습니다.")})})},[n,s,t]);(0,i.useEffect)(()=>{if(t&&"governor"===n)return y(),()=>{g.current?.abort(),g.current=null}},[n,y,e,t]),(0,i.useEffect)(()=>{if(t&&"lab"===n)return k(b.current),()=>{v.current?.abort(),v.current=null}},[n,k,t]),(0,i.useEffect)(()=>{if(t&&"governor"===n&&null!==p)return w(p),()=>{x.current?.abort(),x.current=null}},[n,w,p,t]),(0,i.useEffect)(()=>()=>{g.current?.abort(),x.current?.abort(),v.current?.abort()},[]);let j=(0,i.useCallback)(e=>{x.current?.abort(),x.current=null,h(e),null===e&&d({status:"idle",runId:null,detail:null,error:null})},[]);return{list:a,detail:l,experiments:c,selectedRunId:p,selectRun:j,refreshRuns:(0,i.useCallback)(()=>{y()},[y]),refreshExperiments:(0,i.useCallback)((e,t="all")=>{let n=void 0===e?b.current:e;void 0!==e&&(b.current=e,f(e)),k(n,t)},[k]),experimentFolder:m}}({sessionId:t,visible:e,activeTab:n,client:o}),[m,f]=(0,i.useState)(""),g=(0,i.useMemo)(()=>h.experiments.response?.folders??[],[h.experiments.response]),x=(0,i.useMemo)(()=>h.experiments.response?.configs.reduce((e,t)=>Math.max(e,t.runCount),0)??0,[h.experiments.response]),v=h.experimentFolder,b=h.experiments.response?.scope??"all";if(!e)return null;let y="governor"===n&&"loading"===h.list.status||"lab"===n&&"loading"===h.experiments.status,w=y?p("efficiency.refreshing"):p("efficiency.refresh"),k="governor"===n?h.list.runs.length>0?p("efficiency.runsValue").replace("{value}",String(h.list.runs.length)):"":h.experiments.response?p("efficiency.runsValue").replace("{value}",String(h.experiments.response.runCount)):"";return(0,r.jsxs)("section",{className:di("efficiency-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",d),"aria-labelledby":c,"aria-busy":y,children:[(0,r.jsxs)("header",{className:"flex min-h-12 items-center gap-3 border-b border-border bg-bg px-3",children:[(0,r.jsx)("h1",{id:c,className:"m-0 text-sm font-semibold text-text",children:p("efficiency.title")}),(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-right font-mono text-[11px] tabular-nums text-text-dim",children:k}),(0,r.jsx)(a.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{"governor"===n?h.refreshRuns():h.refreshExperiments(void 0,b)},disabled:y,children:w})]}),(0,r.jsx)("div",{className:"grid grid-cols-2 border-b border-border bg-bg",role:"tablist","aria-label":p("efficiency.title"),children:["governor","lab"].map(e=>(0,r.jsx)("button",{type:"button",role:"tab","aria-selected":n===e,id:`${u}-${e}-tab`,"aria-controls":u,className:di("min-h-10 border-0 border-r border-border bg-bg px-4 text-sm text-text-muted last:border-r-0 hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent",n===e&&"bg-bg-selected font-semibold text-text"),onClick:()=>s(e),children:"governor"===e?p("efficiency.governor"):p("efficiency.lab")},e))}),"lab"===n?(0,r.jsxs)("div",{className:"efficiency-folderbar",children:[(0,r.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${u}-folder`,children:p("efficiency.folder")}),(0,r.jsxs)("select",{id:`${u}-folder`,className:"efficiency-folder-select",value:v??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;f(t??""),h.refreshExperiments(t,b)},children:[(0,r.jsx)("option",{value:"",children:p("efficiency.folderAll")}),g.map(e=>(0,r.jsx)("option",{value:e,children:e},e)),v&&!g.includes(v)?(0,r.jsx)("option",{value:v,children:v}):null]}),(0,r.jsx)("input",{className:"efficiency-folder-input",value:m,placeholder:p("efficiency.folderPlaceholder"),"aria-label":p("efficiency.folder"),onChange:e=>f(e.target.value),onKeyDown:e=>{if("Enter"===e.key){let e=""===m.trim()?null:m.trim();h.refreshExperiments(e,b)}}}),(0,r.jsxs)("div",{className:"col-span-full flex flex-col items-start gap-2",children:[(0,r.jsx)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:"attributed"===b,onPressedChange:e=>h.refreshExperiments(void 0,e?"attributed":"all"),children:p("efficiency.scopeAttributed")}),(0,r.jsx)(o2.E,{tone:"attributed"===b?"informative":"neutral",variant:"weak",size:"medium",children:p("attributed"===b?"efficiency.scopeAttributed":"efficiency.scopeAll")})]})]}):null,(0,r.jsx)("div",{id:u,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain",role:"tabpanel","aria-labelledby":`${u}-${n}-tab`,children:"governor"===n?t?"idle"===h.list.status||"loading"===h.list.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingRuns")}):"error"===h.list.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.runsError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.list.error})]}):"empty"===h.list.status?(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.runsEmpty")}):(0,r.jsxs)("div",{className:"efficiency-governor",children:[(0,r.jsx)("ul",{className:"efficiency-run-list",children:h.list.runs.map(e=>(0,r.jsx)(dg,{run:e,selected:h.selectedRunId===e.runId,onSelect:()=>h.selectRun(h.selectedRunId===e.runId?null:e.runId),t:p},e.runId))}),(0,r.jsx)("div",{className:"efficiency-detail-pane",children:null===h.selectedRunId||"idle"===h.detail.status?(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.selectRun")}):"loading"===h.detail.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingDetail")}):"error"===h.detail.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.detailError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.detail.error})]}):h.detail.detail?(0,r.jsx)(db,{detail:h.detail.detail,t:p}):null})]}):(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.noSession")}):(()=>{if("idle"===h.experiments.status||"loading"===h.experiments.status)return(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingExperiments")});if("error"===h.experiments.status)return(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.experimentsError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.experiments.error})]});let e=h.experiments.response;return"empty"!==h.experiments.status&&e?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")}),(0,r.jsxs)("div",{className:"efficiency-stack",children:[(0,r.jsx)(dw,{response:e,t:p}),e.configs.map(e=>(0,r.jsx)(dk,{config:e,baselineRuns:x,t:p},e.signature))]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.experimentsEmpty")}),e?(0,r.jsx)("div",{className:"efficiency-stack",children:(0,r.jsx)(dw,{response:e,t:p})}):null,(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")})]})})()})]})}function dS(e){return"message"===e.type&&"message"in e}function dC(e){let t=e,n=t.branchPreview,r=dS(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&dS(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function dI({node:e,activePathIds:t,depth:n,isLast:i,parentLines:s,onSelect:a}){let{node:o,skipped:l,branchPreview:d,labelEntry:c}=dC(e),u=t.has(o.entry.id),p=t.has(e.entry.id)||t.has(o.entry.id),h=d?.text??function(e){if("message"===e.type&&"message"in 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}(c),m=d?d.role??null:dS(c)?c.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>a(o.entry.id),children:[s.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:i?"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:u?"var(--accent)":p?"var(--text-muted)":"var(--border)",border:u?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),m&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===m?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"U":"A"}),l>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",l]}),(0,r.jsx)("span",{style:{fontSize:11,color:u?"var(--text)":p?"var(--text-muted)":"var(--text-dim)",fontWeight:u?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:h})]}),o.children.map((e,l)=>(0,r.jsx)(dI,{node:e,activePathIds:t,depth:n+1,isLast:l===o.children.length-1,parentLines:[...s,!i],onSelect:a},e.entry.id))]})}function dT({tree:e,activeLeafId:t,onLeafChange:n,hasSession:s}){let{t:a}=(0,E.s)(),o=(0,i.useMemo)(()=>t?new Set(function e(n,r){for(let i of n){let n=[...r,i.entry.id];if(i.entry.id===t||i.compressedEntryIds?.includes(t))return n;let s=e(i.children,n);if(s)return s}return null}(e,[])??[]):new Set,[e,t]),l=(0,i.useCallback)(e=>{n(e)},[n]),d=s?!function e(t){if(t.length>1)return!0;for(let n of t)if(n.children.length>1||e(n.children))return!0;return!1}(e)?a("i18n.noBranches"):null:a("i18n.noActiveSession"),c=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=dC(e[0]).node;return t.children.length>1?t.children:[]}(e);return!d&&c.length>0?(0,r.jsx)("div",{className:"branch-navigator-tree",children:c.map((e,t)=>(0,r.jsx)(dI,{node:e,activePathIds:o,depth:0,isLast:t===c.length-1,parentLines:[],onSelect:l},e.entry.id))}):(0,r.jsx)("p",{className:"branch-navigator-empty",children:d??a("i18n.noBranches")})}function dN(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function dM(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function dR(e){let 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 a=t+.18*r;s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(.18,a+.02),s.gain.exponentialRampToValueAtTime(.001,a+.45),i.start(a),i.stop(a+.45)})}async function dE(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return t.arrayBuffer()}let d$="omp-sidebar-usage-collapsed";function dL(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function dA({usage:e,onOpen:t}){var n;let s,a,o,{t:l}=(0,E.s)(),d=W(),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(!0);(0,i.useEffect)(()=>{try{h("0"!==window.localStorage.getItem(d$))}catch{}},[]);let m=e.bai,f=e.state.data?.reports??[],g=lj(1e4),x=(s=t0(f),a=[],o=[],f.forEach((e,t)=>{if(!0===e.disabled)return;let n=s[t],r="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>g,i=(e.limits??[]).some(e=>e.scope?.shared===!0&&tH(e));for(let t of e.limits??[]){let s=function(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?t:null}(t);if(null===s)continue;let l=r?"blocked":i?"account-spent":tH(t)?"spent":"usable",d={key:`${e.provider}:${e.credentialId??n.seed}:${t.id}`,account:n.alias,seed:n.seed,provider:e.provider,label:t.label||t.id,percent:Math.round(100*s),state:l};("usable"===l?a:o).push(d)}}),[...a,...o]),v=c?x:x.slice(0,2),b=x.length-v.length,y="measured"===m.status?(n=m.tokens)>=1e9?`${(n/1e9).toFixed(1)}B`:n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${Math.round(n/1e3)}K`:String(Math.round(n)):l("empty"===m.status?"usage.baiEmpty":"usage.baiUnmeasured"),w="measured"===m.status&&null!==m.from&&null!==m.to?l("usage.baiRange",{from:dL(m.from),to:dL(m.to)}):null,k=e=>"usable"===e.state?null:l("blocked"===e.state?"usage.accountBlocked":"account-spent"===e.state?"usage.accountSpent":"usage.limitSpent"),j=l("usage.open",{rows:[...v.map(e=>{let t=k(e);return`${e.account} ${e.label} ${e.percent}%${null===t?"":` (${t})`}`}),`${l("usage.bai")} ${y}${null===w?"":` \xb7 ${w}`}`].join(", ")})+(b>0?l("usage.openMore",{count:b}):""),S=0===x.length?{label:l("usage.bai"),value:y,danger:!1}:{label:x[0].label,value:`${x[0].percent}%`,danger:x[0].percent>=90},C=(0,r.jsxs)("div",{role:"button",tabIndex:0,className:"navigator-usage",onClick:t,onKeyDown:e=>{e.target!==e.currentTarget||("Enter"===e.key||" "===e.key)&&(" "===e.key&&e.preventDefault(),t())},"aria-label":j,children:[0===v.length?(0,r.jsx)("span",{className:"navigator-usage-empty",children:l("usage.none")}):v.map(e=>(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:e.label}),(0,r.jsxs)("span",{className:"navigator-usage-value",style:e.percent>=90?{color:"var(--danger)"}:void 0,children:[e.percent,"%"]})]}),(0,r.jsxs)("span",{className:"navigator-usage-account",children:[(0,r.jsx)(nx,{seed:e.seed,size:24,provider:e.provider}),e.account,null===k(e)?null:(0,r.jsx)("span",{className:"navigator-usage-state",children:k(e)})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"navigator-usage-track",children:(0,r.jsx)("span",{className:"navigator-usage-fill",style:{width:`${Math.max(0,Math.min(100,e.percent))}%`,background:e.percent>=90?"var(--danger)":"var(--metric)"}})})]},e.key)),(b>0||c)&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-more","aria-expanded":c,onClick:e=>{e.stopPropagation(),u(e=>!e)},children:c?l("usage.showLess"):l("usage.showMore",{count:b})}),(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:l("usage.bai")}),(0,r.jsx)("span",{className:"navigator-usage-value",style:"measured"===m.status?void 0:{color:"var(--text-dim)"},children:y})]}),null===w?null:(0,r.jsx)("span",{className:"navigator-usage-account",children:w})]})]});return d?(0,r.jsxs)("div",{className:"navigator-usage-shell",children:[(0,r.jsxs)("button",{type:"button",className:"navigator-usage-toggle","aria-expanded":!p,"aria-label":p?j:l("usage.showLess"),onClick:()=>{let e=!p;h(e);try{window.localStorage.setItem(d$,e?"1":"0")}catch{}},children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:p?S.label:l("usage.showLess")}),p&&(0,r.jsx)("span",{className:"navigator-usage-value",style:S.danger?{color:"var(--danger)"}:void 0,children:S.value}),(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,transform:p?"rotate(0deg)":"rotate(180deg)"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})]}),p?null:C]}):C}let dP="git pull && bun install && bun run build && node Tools/CUELO_Setup/files/native-runtime-patch.js --target .";function dz(e){return"unknown"===e?e:`v${e}`}function dW(){let{locale:e,t}=(0,E.s)(),n=W(),[s,a]=(0,i.useState)(null),[o,l]=(0,i.useState)("idle"),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),f=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),[b,y]=(0,i.useState)(null),w=(0,i.useCallback)(()=>{let e=g.current?.getBoundingClientRect();if(!e)return;let t=window.visualViewport?.height??window.innerHeight,{side:n,maxHeight:r}=iW(e.top,e.bottom,t,iF(t,.72,620),{margin:12,minHeight:0}),i=Math.min(430,window.innerWidth-24),s=Math.max(12,window.innerWidth-i-12);y({left:Math.min(e.right+8,s),width:i,maxHeight:r,..."above"===n?{bottom:t-e.top+8}:{top:e.bottom+8}})},[]);(0,i.useEffect)(()=>d?(w(),window.addEventListener("resize",w),window.addEventListener("scroll",w,!0),window.visualViewport?.addEventListener("resize",w),window.visualViewport?.addEventListener("scroll",w),()=>{window.removeEventListener("resize",w),window.removeEventListener("scroll",w,!0),window.visualViewport?.removeEventListener("resize",w),window.visualViewport?.removeEventListener("scroll",w)}):void y(null),[d,w]);let k=(0,i.useCallback)(async e=>{l("loading");try{let t=await fetch("/api/updates",{cache:"no-store",signal:e});if(!t.ok)return;let n=await t.json();a(n),l("ready")}catch{e?.aborted||l("ready")}},[]);if((0,i.useEffect)(()=>{let e=new AbortController;return k(e.signal),()=>e.abort()},[k]),(0,i.useEffect)(()=>()=>{clearTimeout(f.current??void 0),f.current=null},[]),(0,i.useEffect)(()=>{if(!d)return;let e=e=>{g.current?.contains(e.target)||x.current?.contains(e.target)||c(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),c(!1),v.current?.focus({preventScroll:!0}))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[d]),"ready"!==o||!s?.updateAvailable||!s.latestRelease)return null;let j=s.latestRelease,S=j.publishedAt?new Intl.DateTimeFormat(e,{dateStyle:"medium"}).format(new Date(j.publishedAt)):null,C=j.body.trim()||j.name,I=async e=>{try{await tI(e),clearTimeout(f.current??void 0),m(e),f.current=setTimeout(()=>m(null),1600)}catch{p(t("updates.copyFailed"))}};return(0,r.jsxs)("div",{ref:g,"data-dismissible-layer":d?"":void 0,style:{position:"relative",width:"100%"},children:[(0,r.jsxs)("button",{ref:v,type:"button","aria-expanded":d,"aria-haspopup":"dialog",onClick:()=>{c(e=>!e),p(null)},title:t("updates.availableTitle",{version:dz(j.version)}),style:{width:"100%",minHeight:n?44:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"7px 10px",border:"1px solid color-mix(in srgb, var(--warning) 54%, var(--border))",borderRadius:9,background:"color-mix(in srgb, var(--warning) 8%, transparent)",color:"var(--warning)",cursor:"pointer",fontSize:11,fontFamily:"var(--font-mono)",transition:"background 0.12s, border-color 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--warning) 14%, var(--bg-hover))",e.currentTarget.style.borderColor="var(--warning)"},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--warning) 8%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--warning) 54%, var(--border))"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",background:"var(--warning)",boxShadow:"0 0 0 3px color-mix(in srgb, var(--warning) 14%, transparent)"}}),(0,r.jsx)("span",{children:t("updates.available")}),(0,r.jsx)("span",{style:{color:"var(--text)",fontVariantNumeric:"tabular-nums"},children:dz(j.version)})]}),d&&b&&(0,F.createPortal)((0,r.jsxs)("div",{ref:x,"data-dismissible-layer":"",role:"dialog","aria-label":t("updates.dialogTitle"),style:{position:"fixed",left:b.left,top:b.top,bottom:b.bottom,zIndex:700,width:b.width,maxHeight:b.maxHeight,display:"flex",flexDirection:"column",overflow:"hidden",border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-panel)",boxShadow:"0 18px 46px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("div",{style:{padding:"13px 14px 11px",borderBottom:"1px solid var(--border)",background:"linear-gradient(135deg, color-mix(in srgb, var(--warning) 10%, var(--bg-panel)), var(--bg-panel) 65%)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.dialogEyebrow")}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text)",fontSize:15,fontWeight:650},children:t("updates.dialogTitle")})]}),(0,r.jsx)("div",{style:{color:"var(--warning)",fontFamily:"var(--font-mono)",fontSize:12,fontVariantNumeric:"tabular-nums"},children:dz(j.version)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 14px",marginTop:9,color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:t("updates.current",{version:dz(s.currentAppVersion)})}),S&&(0,r.jsx)("span",{children:S})]})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"11px 14px 14px"},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.changelog")}),(0,r.jsx)("div",{className:"update-changelog",style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.5},children:(0,r.jsx)(tR,{children:C})})]}),(0,r.jsxs)("div",{style:{flexShrink:0,padding:"10px 14px 12px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:9,marginBottom:10},children:(0,r.jsx)("a",{href:j.htmlUrl,target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",fontSize:11,textDecoration:"underline",textUnderlineOffset:3},children:t("updates.viewRelease")})}),(0,r.jsxs)("div",{style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)"},children:t("updates.manual")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0,marginTop:6,padding:"6px 7px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("code",{style:{flex:1,minWidth:0,overflowWrap:"anywhere",color:"var(--text)"},children:dP}),(0,r.jsx)("button",{type:"button",onClick:()=>void I(dP),title:h===dP?t("updates.commandCopied"):t("updates.copyCommand"),"aria-label":h===dP?t("updates.commandCopied"):t("updates.copyCommand"),style:{flex:"0 0 auto",width:n?44:24,height:n?44:24,padding:0,border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:h===dP?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:h===dP?(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:"1.8",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"})]})})]})]}),u&&(0,r.jsx)("div",{role:"alert",style:{marginTop:9,color:"var(--danger)",fontSize:11,lineHeight:1.45},children:u})]})]}),document.body)]})}let dF="pi-web:last-open-by-workspace";function dD(){try{return window.localStorage}catch{return null}}function d_(e){let t=e.getItem(dF);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function dB(e,t=dD()){if(t)try{let n=d_(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(dF):t.setItem(dF,JSON.stringify(n))}catch{}}let dO="button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])";function dH(){try{return lp(window.localStorage)}catch{return lp(null)}}function dU({auxiliaryDeck:e,resourcePanel:t}={}){var n,p,m,f;let k,j,S,C,I,T,N,M,R,$,L,A,W,F,D,_,B,O,H=(0,s.useRouter)(),U=(0,s.useSearchParams)(),[q]=(0,i.useState)(()=>{let e;return{requestedCwd:e=U.get("cwd")?.trim()||null,sessionId:e?null:U.get("session")}}),{preference:V,toggleTheme:K}=tC(),{locale:J,setLocale:G,t:Y,supportedLocales:Z}=(0,E.s)(),X=function(){let[e,t]=(0,i.useState)(null),[n,r]=(0,i.useState)(!1),s=(0,i.useCallback)(()=>{t("Notification"in window?Notification.permission:null)},[]);return(0,i.useEffect)(()=>{try{r("1"===window.localStorage.getItem(oX))}catch{}return s(),window.addEventListener("focus",s),()=>window.removeEventListener("focus",s)},[s]),{permission:e,dismissed:n,request:(0,i.useCallback)(()=>{"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission().then(t,s)},[s]),dismiss:(0,i.useCallback)(()=>{r(!0);try{window.localStorage.setItem(oX,"1")}catch{}},[])}}(),ee=(0,i.useSyncExternalStore)(P.subscribe,P.getSnapshot,z);(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=()=>{let r;n=null,!function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r}){let i=.01>Math.abs(r-1);return e&&i&&t-n>1}({hasFocusedEditable:(r=document.activeElement)instanceof HTMLElement&&(r.isContentEditable||"INPUT"===r.tagName||"SELECT"===r.tagName||"TEXTAREA"===r.tagName),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?t.style.removeProperty("--app-viewport-height"):t.style.setProperty("--app-viewport-height",`${e.height}px`);let i=0!==window.scrollX||0!==window.scrollY,s=.01>Math.abs(e.scale-1);i&&s&&window.scrollTo(0,0)},i=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(r)};return i(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("focusin",i),window.addEventListener("focusout",i),window.addEventListener("pageshow",i),()=>{e.removeEventListener("resize",i),e.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("focusin",i),window.removeEventListener("focusout",i),window.removeEventListener("pageshow",i),null!==n&&window.cancelAnimationFrame(n),t.style.removeProperty("--app-viewport-height")}},[]);let{soundEnabled:et,onSoundToggle:en,playCueSound:er,preloadCueSound:ei,unlockAudio:es,soundEnabledRef:ea}=function(){let[e,t]=(0,i.useState)(()=>{let e=localStorage.getItem("omp-sound-enabled");return null===e||"true"===e}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),s=(0,i.useRef)(null),a=(0,i.useRef)(0),o=(0,i.useRef)(new Map),l=(0,i.useRef)(new Map),d=(0,i.useRef)(new Map),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),p=(0,i.useRef)(new Map),h=(0,i.useRef)(new Map),m=(0,i.useCallback)(e=>{let t=p.current.get(e);return t||(t=dE(e).catch(t=>{throw p.current.delete(e),t}),p.current.set(e,t)),t},[]),f=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),g=(0,i.useCallback)(()=>(c.current??=rP(),c.current),[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async e=>{if(!e)return;let t=await g();for(let r of rN){let i=rA(t,e,r);if(i){for(let e of i.stickers){if(h.current.has(e))continue;let t=new Image;t.decoding="async",t.src=e,h.current.set(e,t)}if(n.current)for(let e of i.voices)m(e).catch(()=>{})}}},[g,m]),v=(0,i.useCallback)(()=>{a.current+=1;let e=s.current;if(s.current=null,e)try{e.stop()}catch{}},[]),b=(0,i.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=f();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[f]);(0,i.useEffect)(()=>{let e=()=>b(),t={capture:!0,passive:!0};return window.addEventListener("pointerdown",e,t),window.addEventListener("keydown",e,t),()=>{window.removeEventListener("pointerdown",e,t),window.removeEventListener("keydown",e,t)}},[b]);let y=(0,i.useCallback)(()=>{let e=!n.current;e?b(!0):v(),n.current=e,localStorage.setItem("omp-sound-enabled",String(e)),t(e)},[v,b]),w=(0,i.useCallback)(e=>{if(!n.current)return;let t=f();if(!t)return;v();let r=a.current,i=()=>{if(r===a.current&&n.current&&(!e||e()))try{dR(t)}catch{}};"suspended"===t.state?t.resume().then(i).catch(()=>{}):i()},[f,v]);return{soundEnabled:e,onSoundToggle:y,playCueSound:(0,i.useCallback)(async(e,t="done",r)=>{let i=await g(),c=null===t?null:rA(i,e,t),p=`${e??""}\u0000${t??""}`,h=c?rz(c.stickers,l.current.get(p)??null):null;null!==h&&l.current.set(p,h);let x=c?rz(c.voices,o.current.get(p)??null):null,b=x?c?.lines.get(x)??null:null;!x&&c&&null!==(b=rz(c.captions,d.current.get(p)??null))&&d.current.set(p,b);let y={sticker:h,text:b};if(!n.current||r&&!r())return y;let k=f();if(!k)return y;if(!x)return null!==t&&rR[t]||w(r),y;v();let j=a.current,S=()=>j!==a.current||!n.current||void 0!==r&&!r();return(async()=>{if(!("suspended"===k.state&&(await k.resume().catch(()=>{}),S())))try{let e=u.current.get(x);e||(e=m(x).then(e=>k.decodeAudioData(e.slice(0))).catch(e=>{throw u.current.delete(x),e}),u.current.set(x,e));let t=await e;if(S())return;let n=k.createBufferSource(),r=k.createGain();n.buffer=t,n.connect(r),r.connect(k.destination),r.gain.setValueAtTime(.82,k.currentTime),n.onended=()=>{s.current===n&&(s.current=null)},s.current=n,n.start(),o.current.set(p,x)}catch{if(S()||null!==t&&rR[t])return;try{dR(k)}catch{}}})(),y},[f,w,v,g,m]),preloadCueSound:x,unlockAudio:b,soundEnabledRef:n}}(),eo=function(){let[e,t]=(0,i.useState)({status:"idle",data:null,error:null}),[n,r]=(0,i.useState)(!0),[s,a]=(0,i.useState)(null),o=(0,i.useRef)(null),l=(0,i.useRef)(null),d=(0,i.useCallback)(()=>{l.current?.abort();let e=new AbortController;l.current=e,nt({signal:e.signal}).then(t=>{e.signal.aborted||a(t)})},[]);(0,i.useEffect)(()=>{var e;let n,i,s,a,c,u,p,h,m,f,g=(i=(e={onResult(e){t(e),r(!1)}}).intervalMs??6e4,s=e.setIntervalImpl??setInterval,a=e.clearIntervalImpl??clearInterval,c=e.initialData??null,u=null,p=0,h=!1,m=!1,f=async t=>{u?.abort(),u=new AbortController;let n=++p,r=await t9({refresh:t,previous:c,signal:u.signal,fetchImpl:e.fetchImpl});return h&&n===p&&(r.data&&(c=r.data),e.onResult(r)),r},{start(){h||(h=!0,f(!1),n=s(()=>{m||f(!1)},i))},refresh:()=>h?f(!0):Promise.resolve(t4(c,new t1("사용량 폴링이 중지되었습니다.","aborted"))),setPaused(e){m=e},stop(){h=!1,p+=1,u?.abort(),u=null,a(n),n=void 0}});return o.current=g,g.start(),d(),()=>{g.stop(),l.current?.abort(),o.current===g&&(o.current=null)}},[d]);let c=(0,i.useCallback)(async()=>{let e=o.current;if(!e)return{status:"error",data:null,error:new t1("사용량 폴링이 시작되지 않았습니다.","aborted")};r(!0),d();let t=await e.refresh();return r(!1),t},[d]);return{state:e,loading:n,refresh:c,setPaused:(0,i.useCallback)(e=>{o.current?.setPaused(e)},[]),bai:(0,i.useMemo)(()=>(function(e){let t=e?.data;if(!t)return{status:"unmeasured"};let n=t.models.filter(e=>"b-ai"===e.provider);return 0===n.length?{status:"empty"}:{status:"measured",tokens:n.reduce((e,t)=>e+t.tokens,0),from:"number"==typeof t.range?.from?t.range.from:null,to:"number"==typeof t.range?.to?t.range.to:null}})(s),[s])}}();n=eo.state.data?.reports,(0,i.useEffect)(()=>{!function(e){let t=e??na,n=t.map(e=>[e.provider,e.credentialId??"",e.metadata?.accountId??"",e.metadata?.email??""].join("\0")).join("|");if(n===nl)return;nl=n;let r=t0(t),i=new Map;t.forEach((e,t)=>{let n=e.credentialId;if(!nh(n))return;let s=nm(e.provider,n);i.has(s)||i.set(s,{seed:r[t].seed,alias:r[t].alias})}),np({faces:i,pins:no.pins})}(n)},[n]);let el=(0,i.useRef)(new Set),ed=(0,i.useCallback)(()=>{ea.current&&er(null,"done")},[er,ea]),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[em,ef]=(0,i.useState)(null),eg=(0,i.useRef)(0),ex=(0,i.useRef)(null),[ev,eb]=(0,i.useState)(null),[ey,ew]=(0,i.useState)(()=>q.requestedCwd?"validating":"idle"),[ek,ej]=(0,i.useState)(null),[eS,eC]=(0,i.useState)(0),[eI,eT]=(0,i.useState)(0),[eN,eM]=(0,i.useState)(0),[eR,eE]=(0,i.useState)(0),[e$,eL]=(0,i.useState)(!1),[eA,eP]=(0,i.useState)(null),[ez,eW]=(0,i.useState)(!1),[eF,eD]=(0,i.useState)(!1),[e_,eB]=(0,i.useState)(null),[eO,eH]=(0,i.useReducer)(g,h),[eU,eq]=(0,i.useState)("characters"),[eV,eK]=(0,i.useState)("governor"),[eJ,eG]=(0,i.useState)(()=>x(0)),[eY]=(0,i.useState)(dH),[eX]=(0,i.useState)(lh),[eQ,e0]=(0,i.useState)([]),[e1,e2]=(0,i.useState)({sessions:[],complete:!1}),[e8,e4]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(!1),[e3,e7]=(0,i.useState)(0),e9=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useCallback)(()=>{e7(e=>e+1)},[]),tr=(0,i.useCallback)(e=>{te.current=e},[]),ti=(0,i.useRef)(!1),[ts,ta]=(0,i.useState)(!1),to=(0,i.useRef)(!1),tl=(0,i.useRef)(!1),td=(0,i.useRef)(0),[tc,tu]=(0,i.useState)(!1),[tp,th]=(0,i.useState)(!1),tm=(0,i.useRef)(null),[tf,tg]=(0,i.useState)(null),[tx,tv]=(0,i.useState)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(!1);tb.current=tf,(0,i.useEffect)(()=>{tg(sy())},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=n=>{if(e||ti.current||"IDLE"===n.phase||!n.requestId||!n.stageHash)return;let r=`${window.location.pathname}${window.location.search}${window.location.hash}`,i=function(e){let t=iC();if(!t.ok)return{entered:!1,error:t.error};let n={schemaVersion:2,requestId:e.requestId,stageHash:e.stageHash,clientId:sb(),sessionId:e.sessionId,resumeUrl:e.resumeUrl};try{sessionStorage.setItem(sm,JSON.stringify(n))}catch(e){return{entered:!1,error:e instanceof Error?e.message:String(e)}}let r=new URLSearchParams({mode:"wait",requestId:n.requestId,stageHash:n.stageHash,clientId:n.clientId});return window.location.replace(`/api/update-maintenance?${r}`),{entered:!0}}({requestId:n.requestId,stageHash:n.stageHash,sessionId:ec?.id??null,resumeUrl:r});if(i.entered){ti.current=!0;return}t=i.error},r=async()=>{if(!e&&!ti.current)try{let i=ty.current?null:tb.current,s=await sk({sessionId:ec?.id??null,resumeUrl:`${window.location.pathname}${window.location.search}${window.location.hash}`,preservationError:t,update:i?{requestId:i.requestId,stageHash:i.stageHash}:null});td.current=0;let a=!!(s.serverBootId&&tm.current&&s.serverBootId!==tm.current);if(to.current||a){var r=ec?.id??null;iC();try{sessionStorage.setItem(sg,JSON.stringify({schemaVersion:1,sessionId:r,at:Date.now()}))}catch{}window.location.reload();return}s.serverBootId&&(tm.current=s.serverBootId),tl.current=!0,!e&&s.update&&(tv(s.update),s.update.cleanup&&"running"!==s.update.cleanup.status&&(ty.current=!0)),n(s)}catch{td.current+=1,!e&&tl.current&&td.current>=2&&(to.current=!0,ta(!0))}},i=e=>{n(e.detail??{}),t&&r()};window.addEventListener("ompweb:update-maintenance",i),r();let s=window.setInterval(()=>void r(),2e3);return()=>{e=!0,window.clearInterval(s),window.removeEventListener("ompweb:update-maintenance",i)}},[ec?.id]),(0,i.useEffect)(()=>{if(!ts)return;let e=window.setTimeout(()=>tu(!0),12e4);return()=>window.clearTimeout(e)},[ts]),(0,i.useEffect)(()=>{(function(e,t=Date.now()){let n,r=sessionStorage.getItem(sg);if(!r)return!1;try{n=JSON.parse(r)}catch{n=null}return!n||1!==n.schemaVersion||"number"!=typeof n.at||t-n.at>6e4||null!==n.sessionId&&"string"!=typeof n.sessionId?(sessionStorage.removeItem(sg),!1):n.sessionId===e&&(sessionStorage.removeItem(sg),!0)})(ec?.id??null)&&th(!0)},[ec?.id]),(0,i.useEffect)(()=>{if(!tp)return;let e=window.setTimeout(()=>th(!1),8e3);return()=>window.clearTimeout(e)},[tp]);let tw=tf?.requestId??null,tk=tf?.dismissed??!0,tj=tx?.requestId??null,tS=tx?.deploymentCompleted??!1,tT=tx?.cleanup?.status??null;(0,i.useEffect)(()=>{if(!tw||tk||tj!==tw||!tS)return;let e=sv(tT);if(null===e)return;let t=window.setTimeout(()=>{tg(sw(tw))},e);return()=>window.clearTimeout(t)},[tw,tk,tj,tS,tT]),(0,i.useEffect)(()=>{let e=function(){let e=sessionStorage.getItem(sm);if(!e)return null;try{let t=JSON.parse(e);if(2!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"string"!=typeof t.clientId||"string"!=typeof t.resumeUrl||null!==t.sessionId&&"string"!=typeof t.sessionId)return null;return t}catch{return null}}();if(!e||e.sessionId&&ec?.id!==e.sessionId)return;let t=!1;return sj(e).then(()=>{t||(ty.current=!1,tg(sy()),eC(e=>e+1),eM(e=>e+1))}).catch(()=>{}),()=>{t=!0}},[ec?.id]);let tN=(0,i.useCallback)(e=>{if("Tab"!==e.key)return;let t=tt.current;if(!t)return;let n=Array.from(t.querySelectorAll(dO));if(0===n.length)return;let r=e.shiftKey?n[0]:n[n.length-1],i=document.activeElement;i!==r&&t.contains(i)||(e.preventDefault(),(e.shiftKey?n[n.length-1]:n[0]).focus())},[]),[tM,tR]=(0,i.useState)(!0),[tE,t$]=(0,i.useState)(!1),[tL,tA]=(0,i.useState)(!1),tP=(0,i.useRef)(tM),tz=(0,i.useRef)(!1),tW=(0,i.useRef)(!0),tF=(0,i.useRef)(null);tP.current=tM;let tD=(k=(p={clientPainted:tE,compactWorkspace:ee,requestedOpen:tM}).requestedOpen&&p.clientPainted,{laidOut:p.requestedOpen&&(!p.compactWorkspace||p.clientPainted),presented:k,drawer:k&&p.compactWorkspace}),t_=(0,i.useCallback)(e=>{tz.current=e,tR(e),eH(e?{type:"open-layer",layer:"navigator-drawer"}:{type:"close-layer"})},[]),tB=(0,i.useRef)(null),tO=(0,i.useRef)(!1),tH=(0,i.useRef)(260),tU=(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:!1,rightPanelWidth:0}),[]),tq=function(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,getDefaultWidth:s,getMaxWidth:a,growthDirection:o,maxWidth:l,minWidth:d,storageKey:c,widthRef:u}=e,p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(!1),[f,g]=(0,i.useState)(r),[x,v]=(0,i.useState)(!1),b=(0,i.useCallback)(()=>Math.min(l,Math.max(d,a())),[a,l,d]),y=(0,i.useCallback)(e=>{var t;let n,r;return t=b(),n=Number.isFinite(e)?e:d,r=Math.max(d,t),Math.round(Math.max(d,Math.min(r,n)))},[b,d]),w=(0,i.useCallback)(e=>{u.current=e,p.current?.style.setProperty(n,`${e}px`)},[n,u]),k=(0,i.useCallback)((e,t={})=>{let{forcePersist:n=!1,persist:r=!0}=t,i=y(e),s=i!==u.current;return w(i),g(i),r&&(s||n)&&dM(c,i),i},[w,y,c,u]),j=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),S=(0,i.useCallback)(e=>{let t=h.current;if(t&&t.pointerId===e){h.current=null,j(t),v(!1),k(u.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[k,j,u]),C=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=h.current;t&&S(t.pointerId);let n=e.currentTarget;n.focus({preventScroll:!0}),n.setPointerCapture(e.pointerId),h.current={pointerId:e.pointerId,startX:e.clientX,startWidth:u.current,target:n,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",v(!0)},[S,u]),I=(0,i.useCallback)(e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void S(e.pointerId);e.preventDefault();let n="right"===o?1:-1,r=y(t.startWidth+(e.clientX-t.startX)*n);w(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[w,y,S,o]),T=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),N=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),M=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),R=(0,i.useCallback)(()=>{k(s?.()??r,{forcePersist:!0})},[k,r,s]),E=(0,i.useCallback)(()=>{k(u.current)},[k,u]),$=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,n="right"===o?"ArrowRight":"ArrowLeft",r="right"===o?"ArrowLeft":"ArrowRight";e.key===n?(e.preventDefault(),k(u.current+t,{forcePersist:!0})):e.key===r?(e.preventDefault(),k(u.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),k(d,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),k(b(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),R())},[k,b,o,d,R,u]);return(0,i.useEffect)(()=>{if(m.current)return;m.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}}(c),t=k(e??s?.()??r,{persist:!1});null!==e&&e!==t&&dM(c,t)},[k,r,s,c]),(0,i.useEffect)(()=>{if(!m.current)return;k(u.current);let e=()=>{k(u.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[k,u]),(0,i.useEffect)(()=>{if(!x)return;let e=()=>{let e=h.current;e&&S(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[S,x]),(0,i.useEffect)(()=>()=>{let e=h.current;e&&(h.current=null,j(e))},[j]),{isResizing:x,panelRef:p,reclampWidth:E,resetWidth:R,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":b(),"aria-valuemin":d,"aria-valuenow":f,"aria-valuetext":`${f} px`,onDoubleClick:R,onKeyDown:$,onLostPointerCapture:M,onPointerCancel:N,onPointerDown:C,onPointerMove:I,onPointerUp:T,role:"separator",tabIndex:0},width:f}}({ariaLabel:Y("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:tU,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"omp-sidebar-width",widthRef:tH}),tV=tq.reclampWidth;(0,i.useEffect)(()=>{let e=tF.current;if(e===ee)return;tA(!0),null!==e&&(e?tz.current=tP.current:tW.current=tP.current),tF.current=ee;let t=ee?tz.current:tW.current;ee?t_(t):tR(t);let n=0,r=requestAnimationFrame(()=>{n=requestAnimationFrame(()=>tA(!1))});return()=>{cancelAnimationFrame(r),n&&cancelAnimationFrame(n)}},[ee,t_]),(0,i.useEffect)(()=>{t$(!0)},[]),(0,i.useEffect)(()=>{let e=tO.current;if(tO.current=tD.drawer,tD.drawer){let e=tq.panelRef.current;if(!e||e.contains(document.activeElement))return;let t=requestAnimationFrame(()=>{e.querySelector(dO)?.focus()});return()=>cancelAnimationFrame(t)}if(!e)return;let t=0,n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>{let e=document.activeElement;e&&e!==document.body||tB.current?.focus()})});return()=>{cancelAnimationFrame(n),t&&cancelAnimationFrame(t)}},[tD.drawer,tq.panelRef]),(0,i.useEffect)(()=>{tV()},[tV,eO.activeView]),(0,i.useEffect)(()=>{let e=e9.current;if(!e)return;let t=e=>{eG(t=>{let n=x(e);return t.navigator===n.navigator&&t.deck===n.deck?t:n})};t(e.getBoundingClientRect().width);let n=new ResizeObserver(e=>{let n=e[0]?.contentRect.width;"number"==typeof n&&t(n)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>{if(!e3)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>te.current?.())});return()=>{cancelAnimationFrame(t),e&&cancelAnimationFrame(e)}},[e3]),(0,i.useEffect)(()=>{if("command-palette"!==eO.transientLayer)return;let e=tt.current;if(!e)return;let t=requestAnimationFrame(()=>{e.querySelector(dO)?.focus()});return()=>cancelAnimationFrame(t)},[eO.transientLayer]),(0,i.useEffect)(()=>{ee||"navigator-drawer"!==eO.transientLayer||eH({type:"close-layer"})},[ee,eO.transientLayer]),(0,i.useEffect)(()=>{let e=new AbortController;return e2(e=>({...e,complete:!1})),fetch("/api/sessions",{cache:"no-store",signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if(!Array.isArray(t.sessions))throw Error("Invalid session census");e0(t.sessions),e2({sessions:t.sessions.map(e=>({id:e.id,modified:e.modified})),complete:!0})}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load the complete session census:",e)}),()=>e.abort()},[eS,ec?.id]);let tK=(0,i.useRef)(null),tJ=(0,i.useRef)(null),[tG,tY]=(0,i.useState)({sessionId:null,tree:[],leafId:null,navigation:0}),tZ=(0,i.useRef)(null),tX=(0,i.useCallback)((e,t,n)=>{tZ.current=n,tY(n=>{let r=nf.current;return n.sessionId!==r?{sessionId:r,tree:e,leafId:t,navigation:0}:{...n,tree:e,leafId:t}})},[]),tQ=(0,i.useCallback)(e=>{tY(t=>t.leafId===e?t:{...t,navigation:t.navigation+1}),tZ.current?.(e)},[]),[t2,t8]=(0,i.useState)(null),t5=(0,i.useCallback)(e=>{t8(e)},[]),[t6,t3]=(0,i.useState)(null),[t7,ne]=(0,i.useState)([]),[nn,nr]=(0,i.useState)(null),[ni,ns]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/settings",{cache:"no-store",signal:e.signal}).then(async t=>{if(!t.ok)return;let n=await t.json(),r=n.fields?.find(e=>"task.maxConcurrency"===e.path),i=r?.value??r?.defaultValue,s="number"==typeof i?i:"string"==typeof i?Number.parseInt(i,10):NaN;!e.signal.aborted&&Number.isFinite(s)&&s>0&&nr(s)}).catch(()=>{}),()=>e.abort()},[]);let[nd,nc]=(0,i.useState)({kind:"idle"}),nu=(0,i.useRef)(null),nf=(0,i.useRef)(ec?.id??null);nf.current=ec?.id??null;let ng=(0,i.useCallback)(e=>{t3(e)},[]),[nx,nv]=(0,i.useState)(null),nb=(0,i.useRef)(null),ny=(0,i.useCallback)((e,t)=>{tI(t).then(()=>{nb.current&&clearTimeout(nb.current),nv(e),nb.current=setTimeout(()=>nv(null),1400)})},[]);(0,i.useEffect)(()=>()=>{nb.current&&clearTimeout(nb.current),nu.current&&clearTimeout(nu.current)},[]),(0,i.useEffect)(()=>()=>ex.current?.abort(),[]);let[nw,nk]=(0,i.useState)(null),nj=(0,i.useCallback)(e=>{nk(e)},[]),[nS,nC]=(0,i.useState)(null),[nI,nT]=(0,i.useState)(null),[nN,nM]=(0,i.useState)(null),[nR,nE]=(0,i.useState)(!1),[n$,nL]=(0,i.useState)("subagents"),nA=(0,i.useCallback)((e,t=!1)=>{eH({type:"select-view",view:e}),nT(null),ee&&t_(!1),(t||"chat"===e)&&tn()},[ee,tn,t_]),nP=(0,i.useCallback)(e=>{let t=eO.transientLayer===e;nT(null),ee&&"navigator-drawer"===eO.transientLayer&&t_(!1),eH({type:"toggle-layer",layer:e}),t&&tn()},[ee,tn,t_,eO.transientLayer]),nz=(0,i.useCallback)(()=>{if("chat"!==eO.activeView){nL(eO.activeView),nA("chat",!0);return}nA(n$,!0)},[n$,nA,eO.activeView]),nW=(0,i.useCallback)(()=>ez?(eF||(eW(!1),tn()),!0):e$?(eL(!1),tn(),!0):nR?(nE(!1),tn(),!0):nI?(nT(null),tn(),!0):eO.transientLayer?("navigator-drawer"===eO.transientLayer&&t_(!1),eH({type:"close-layer"}),tn(),!0):"chat"!==eO.activeView&&(eH({type:"select-view",view:"chat"}),tn(),!0),[nR,nI,eF,ez,tn,t_,e$,eO.activeView,eO.transientLayer]),nF=(0,i.useCallback)(e=>{eH({type:"close-layer"}),ee&&t_(!1),nT(t=>t===e?null:e)},[ee,t_]),nD=(0,i.useCallback)(()=>{eH({type:"close-layer"}),ee&&t_(!1),nT("session")},[ee,t_]),n_=(0,i.useCallback)(()=>{if(nT(null),ee){let e="navigator-drawer"!==eO.transientLayer;t_(e),e||tn();return}eH({type:"close-layer"}),tR(e=>{let t=!e;return tW.current=t,t})},[ee,tn,t_,eO.transientLayer]);(0,i.useEffect)(()=>{if(!nI||!tJ.current)return;let e=()=>{let e=tJ.current.getBoundingClientRect();nM({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(tJ.current),()=>t.disconnect()},[nI]);let[nB,nO]=(0,i.useState)([]),[nH,nU]=(0,i.useState)(null),nq=(0,i.useCallback)(()=>{"view-stack"===eJ.deck&&eH({type:"select-view",view:"chat"}),ee&&t_(!1),tn()},[ee,eJ.deck,tn,t_]),nV=(0,i.useCallback)((e,t)=>{let n;tK.current?.insertText((n=t?`${e}/`:e).includes(" ")?`@"${n}" `:`@${n} `),nq()},[nq]),nK=(0,i.useCallback)((e,t,n)=>{let r,i,s,a;tK.current?.insertText((r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),s=e.includes(" ")?`@"${e}"`:`@${e}`,a=r===i?`:${r}`:`:${r}-${i}`,`${s}${a} `)),nq()},[nq]),nJ=q.sessionId,[nG,nY]=(0,i.useState)(null);tC({cwd:ec?.cwd??ev??nG,syncWithOmp:!0});let nZ=(0,i.useRef)(null),[nX,nQ]=(0,i.useState)(()=>!nJ),n0=(0,i.useRef)(!1),n1=(0,i.useRef)(0),n2=(0,i.useCallback)(()=>{n1.current+=1},[]);(0,i.useEffect)(()=>{ec&&function(e,t,n=dD()){if(n)try{let r=d_(n);r[e]=t,n.setItem(dF,JSON.stringify(r))}catch{}}(ec.projectRoot??nZ.current??ec.cwd,ec.id)},[ec]),(0,i.useEffect)(()=>{let e=q.requestedCwd;if(!e)return;let t=new AbortController;return ew("validating"),ej(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);n0.current=!0,eb(t.cwd),ew("ready")}).catch(e=>{t.signal.aborted||(ej(e instanceof Error?e.message:String(e)),ew("error"))}),()=>t.abort()},[q]);let n8=(0,i.useCallback)(e=>{let t=++n1.current,n=function(e,t=dD()){if(!t)return null;try{let n=d_(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);n&&fetch("/api/sessions").then(e=>e.ok?e.json():null).then(r=>{if(t!==n1.current)return;let i=r?.sessions.find(e=>e.id===n);if(!i){r&&dB(e);return}(i.projectRoot??i.cwd)!==e?dB(e):(eu(i),eT(e=>e+1),new URLSearchParams(window.location.search).get("session")!==i.id&&H.replace(`?session=${encodeURIComponent(i.id)}`,{scroll:!1}))}).catch(()=>{})},[H]),n4=(0,i.useCallback)((e,t)=>{if(n2(),nY(e),!e)return;let n=t??e,r=nZ.current??(ec?ec.projectRoot??ec.cwd:null);if(nZ.current=n,n0.current){n0.current=!1;return}r!==n&&(eg.current+=1,ex.current?.abort(),ex.current=null,eh(null),ef(null),eu(null),eb(t=>t&&t!==e?null:t),eT(e=>e+1),tY({sessionId:null,tree:[],leafId:null,navigation:0}),t8(null),nT(null),nO([]),nU(null),eH({type:"select-view",view:"chat"}),n8(n),H.replace("/",{scroll:!1}))},[H,ec,n2,n8]),n5=(0,i.useCallback)((e,t,n)=>{eb(null),ef(n),eu(e),tY({sessionId:e.id,tree:[],leafId:null,navigation:0}),eT(e=>e+1),t8(null),nQ(!0),ee&&!t&&(t_(!1),eH({type:"select-view",view:"chat"})),t&&(n0.current=!0),t||H.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[ee,H,t_]),n6=(0,i.useCallback)((e,t=!1)=>{if(nZ.current=e.projectRoot??e.cwd,n2(),!t&&ec){let t=(ec.projectRoot??ec.cwd)===(e.projectRoot??e.cwd);if(ec.id===e.id&&t){eg.current+=1,ex.current?.abort(),ex.current=null,eh(null),ee&&t_(!1);return}}if(!t&&ep?.id===e.id)return;eg.current+=1;let n=eg.current;if(ex.current?.abort(),t||!ec){ex.current=null,eh(null),n5(e,t,null);return}let r=new AbortController;ex.current=r,eh(e);let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});fetch(`/api/sessions/${encodeURIComponent(e.id)}?${i}`,{cache:"no-store",signal:r.signal}).then(async t=>{if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();if(r.sessionId!==e.id)throw Error("Session preload returned the wrong session");eg.current===n&&n5(e,!1,r)}).catch(t=>{r.signal.aborted||eg.current!==n||(console.error("Failed to preload session before switching:",t),n5(e,!1,null))}).finally(()=>{eg.current===n&&(ex.current=null,eh(null))})},[n5,n2,ee,ep?.id,ec,t_]),n3=(0,i.useCallback)((e,t)=>{eg.current+=1,ex.current?.abort(),ex.current=null,eh(null),ef(null),n2(),eu(null),eb(t),eT(e=>e+1),tY({sessionId:null,tree:[],leafId:null,navigation:0}),t8(null),nT(null),eH({type:"select-view",view:"chat"}),ee&&t_(!1),H.replace("/",{scroll:!1})},[n2,ee,H,t_]),n7=(0,i.useCallback)(e=>{let t=ec?.projectRoot??nZ.current??ec?.cwd??nG;if(!t||!ec)return;let n=eQ.filter(e=>(e.projectRoot??e.cwd)===t),r=n.findIndex(e=>e.id===ec.id);if(r<0)return;let i=n[r+e];i&&(nT(null),eH({type:"close-layer"}),n6(i),tn())},[nG,eQ,n6,tn,ec]);m={onNewSession:e=>n3(`kb-${Date.now()}`,e),onToggleCommandPalette:()=>nP("command-palette"),onToggleNavigator:n_,onToggleResources:()=>nA("resource"===eO.activeView?"chat":"resource",!0),onSelectView:e=>nA(e,!0),onCycleView:(0,i.useCallback)(e=>{let t=(c.indexOf(eO.activeView)+e+c.length)%c.length;nA(c[t],!0)},[nA,eO.activeView]),onNavigateSession:n7,onEscape:nW,enabled:!e$&&!ez,activeCwd:nG},(j=(0,i.useRef)(m)).current=m,(0,i.useEffect)(()=>{let e=e=>{!function(e,t){if(e.defaultPrevented)return;let n=t.now?.()??Date.now();if(b||e.isComposing||229===e.keyCode||n-y<100)return;let r=e.target,i="u">typeof Element&&r instanceof Element?r:null,s=!!i?.closest("input, textarea, select, [contenteditable='true']");if("Escape"===e.key)return!i?.closest("[data-dismissible-layer], [data-capture-keys], [role='listbox'], [role='menu'], [role='combobox'][aria-expanded='true'], [aria-haspopup][aria-expanded='true']")&&(t.onEscape?.()?(e.preventDefault(),e.stopPropagation()):!(s||i?.closest("[role='dialog']"))&&v&&(e.preventDefault(),v()));if(i?.closest("[data-capture-keys]")||!1===t.enabled)return;let a=e.key.toLowerCase(),o=(e.ctrlKey||e.metaKey)&&!e.altKey;if(o&&!e.shiftKey&&"k"===a)return t.onToggleCommandPalette&&(e.preventDefault(),t.onToggleCommandPalette());if(o&&!e.shiftKey&&"b"===a)return t.onToggleNavigator&&(e.preventDefault(),t.onToggleNavigator());if(o&&!e.shiftKey&&"u"===a)return t.onToggleResources&&(e.preventDefault(),t.onToggleResources());if(o&&!e.shiftKey&&/^[1-7]$/.test(a)){if(!t.onSelectView)return;let n=c[Number(a)-1];return n&&(e.preventDefault(),t.onSelectView(n))}o&&e.shiftKey&&("Period"===e.code||"Comma"===e.code)?t.onCycleView&&(e.preventDefault(),t.onCycleView("Period"===e.code?1:-1)):!e.altKey||e.ctrlKey||e.metaKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key?e.ctrlKey&&e.altKey&&!e.metaKey&&"n"===a&&t.activeCwd&&t.onNewSession&&(e.preventDefault(),t.onNewSession(t.activeCwd)):t.onNavigateSession&&(e.preventDefault(),t.onNavigateSession("ArrowUp"===e.key?-1:1))}(e,j.current)},t=()=>w(!0),n=()=>w(!1);return window.addEventListener("compositionstart",t,{capture:!0}),window.addEventListener("compositionend",n,{capture:!0}),window.addEventListener("keydown",e,{capture:!0}),()=>{window.removeEventListener("keydown",e,{capture:!0}),window.removeEventListener("compositionstart",t,{capture:!0}),window.removeEventListener("compositionend",n,{capture:!0})}},[]);let n9=(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&&eu(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),re=(0,i.useCallback)(e=>{n2(),eb(null),eu(e),eC(e=>e+1),n9(e.id),H.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[n2,H,n9]),rt=(0,i.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{"Notification"in window&&"granted"===Notification.permission&&sc({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&n6(e)}})},[n6]),rn=(0,i.useCallback)(e=>{eC(e=>e+1),eM(e=>e+1),ec&&n9(ec.id),"completed"===e.outcome&&sl()&&rt({targetSession:ec,title:ec?.name??Y("i18n.sessionComplete"),body:Y("i18n.taskFinished")})},[rt,n9,ec,Y]),rr=(0,i.useCallback)(e=>{var t;sl()&&(t=el.current,!(!sd(e)||t.has(e.id))&&(t.add(e.id),1)&&rt({targetSession:ec,title:Y("i18n.attentionNeeded"),body:"custom"===e.method?Y("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[rt,ec,Y]),ri=(0,i.useCallback)(async()=>{let e=ec?.id;if(e&&"naming"!==nd.kind){nu.current&&clearTimeout(nu.current),nT(null),nc({kind:"naming"});try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/auto-name`,{method:"POST"}),n=await t.json().catch(()=>({}));if(!t.ok||!n.title)throw Error(n.error||`HTTP ${t.status}`);let r=n.title.trim();if(eC(e=>e+1),nf.current!==e)return;eu(t=>t?.id===e?{...t,name:r}:t),t3(t=>t?.sessionId===e?{...t,sessionName:r}:t),nc({kind:"success"}),nu.current=setTimeout(()=>nc({kind:"idle"}),1800)}catch(t){if(nf.current!==e)return;nc({kind:"error",message:t instanceof Error?t.message:String(t)}),nu.current=setTimeout(()=>nc({kind:"idle"}),5e3)}}},[nd.kind,ec?.id]);(0,i.useEffect)(()=>{nu.current&&clearTimeout(nu.current),nc({kind:"idle"})},[ec?.id]);let rs=(0,i.useCallback)(e=>{n2(),eC(e=>e+1),eT(e=>e+1),eb(null),eu(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),n9(e),H.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[n2,H,n9]),ra=(0,i.useCallback)(()=>{nQ(!0)},[]),ro=(0,i.useCallback)(e=>{if(n2(),eC(e=>e+1),ec?.id===e){let e=ec.cwd;eu(null),eb(e??null),eT(e=>e+1),tY({sessionId:null,tree:[],leafId:null,navigation:0}),t8(null),nT(null),eH({type:"select-view",view:"chat"}),tn(),H.replace("/",{scroll:!1})}},[n2,tn,ec,H]),rl=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,s=`file:${e}`;nO(n=>{let a=n.find(e=>e.id===s);if(!a)return[...n,{id:s,label:t,filePath:e,sourceSessionId:r,initialDisplayMode:i}];let o=!r||a.sourceSessionId===r,l=!i||a.initialDisplayMode===i;return o&&l?n:n.map(e=>{if(e.id!==s)return e;let t={...e};return r&&(t.sourceSessionId=r),i&&(t.initialDisplayMode=i),t})}),nU(s),eH({type:"select-view",view:"files"}),nT(null),ee&&t_(!1)},[ee,t_]),rd=(0,i.useCallback)(e=>{rl(e,eZ(e),{sourceSessionId:ec?.id??null})},[rl,ec?.id]),rc=(0,i.useCallback)(e=>{let t=nB.filter(t=>t.id!==e);nO(t),nU(n=>n!==e?n:t.length>0?t[t.length-1].id:null),0===t.length&&"files"===eO.activeView&&nA("chat",!0)},[nB,nA,eO.activeView]),ru=(0,i.useCallback)(()=>{ec&&window.open(`/api/sessions/${encodeURIComponent(ec.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[ec]),rp=ev??(null===ec&&nG?nG:null),rh=null!==ec||null!==rp,rm="chat"!==eO.activeView,rf=ec?.cwd??rp,rg=nX&&!rh;(0,i.useEffect)(()=>{if(eP(null),eW(!1),eB(null),!rf)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(rf)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);eP(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[rf]);let rx=(0,i.useCallback)(async()=>{if(rf&&!eF){eD(!0),eB(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:rf})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);eP(t),eW(!1),tn(),eE(e=>e+1),eT(e=>e+1)}catch(e){eB(e instanceof Error?e.message:String(e))}finally{eD(!1)}}},[eF,rf,tn]),rv=nB.find(e=>e.id===nH)??null,rb=nG?eZ(nG)||nG:null,ry=(ec?.name?.trim()||ec?.firstMessage?.trim()||(rp?Y("i18n.newSession"):rb)||"CUELO").replace(/\s+/g," ").trim(),rw=ry.length>96?`${ry.slice(0,93)}…`:ry,rk=rb?`${rw} — ${rb} — CUELO`:`${rw} — CUELO`,rj=rb?`${ry} — ${rb}`:ry,rS=ec?.transient?`${rj} \xb7 ${Y("session.inMemory")}`:rj,rC=t7.filter(e=>"pending"===e.status||"running"===e.status).length,rI=ni?Y("workspace.mainAttention"):e5?Y("workspace.mainWaiting"):e8?Y("workspace.mainWorking"):Y("workspace.mainIdle"),rT=`${ni?"⚠":e5?"○":e8?"●":"○"} Main ${rI} \xb7 Sub ${rC}${nn?`/${nn}`:""}`;(0,i.useEffect)(()=>{let e=()=>{document.title!==rk&&(document.title=rk)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[rk]);let rM="ko"===J?{chat:"대화",process:"작업 과정",efficiency:"효율",subagents:"서브에이전트",files:"파일",resource:"캐릭터",sidechat:"사이드챗"}:{chat:"Chat",process:"Process",efficiency:"Efficiency",subagents:"Subagents",files:"Files",resource:"캐릭터",sidechat:"Side Chat"},rE="chat"!==eO.activeView,r$=rE?rM[eO.activeView]:rM[n$],rL=(S=nw&&Number.isFinite(nw.contextWindow)&&nw.contextWindow>0?nw.contextWindow:null,C=nw&&"number"==typeof nw.tokens&&Number.isFinite(nw.tokens)?Math.max(0,nw.tokens):null,T=null===(I=nw&&"number"==typeof nw.percent&&Number.isFinite(nw.percent)?nw.percent:null!==C&&null!==S?C/S*100:null)?"normal":I>90?"critical":I>70?"warning":"normal",N=null===C?"?":dN(C),M=null===S?"?":dN(S),R=null===I?"?":`${I.toFixed(0)}%`,{level:T,percent:I,fillPercent:null===I?0:Math.min(100,Math.max(0,I)),readout:null===S?null:`${R} \xb7 ${N}/${M}`,usedLabel:N,limitLabel:M,percentLabel:R}),rW=rL.readout,rF=rW?Y("chat.contextUsageTitle",{used:rL.usedLabel,limit:rL.limitLabel,percent:rL.percentLabel}):null,rD="critical"===rL.level?Y("chat.contextUsageCritical"):"warning"===rL.level?Y("chat.contextUsageWarning"):null,r_=(f=t6?.userMessages,!ec||ec.transient?"unsaved":("number"==typeof f?f:0)>0||ec.messageCount>0?null:"no-messages"),rB="unsaved"===r_?Y("title.unsaved"):"no-messages"===r_?Y("title.noMessages"):null,rO=rB??("error"===nd.kind?nd.message:null),rH="naming"===nd.kind?Y("title.generating"):"success"===nd.kind?Y("title.updated"):"error"===nd.kind?Y("title.failed"):Y("title.generate"),rU=(0,r.jsxs)("div",{id:"workspace-file-view",className:"workspace-file-view",children:[(0,r.jsx)("div",{className:"workspace-file-tabs",children:(0,r.jsx)(ad,{tabs:nB,activeTabId:nH??"",onSelectTab:nU,onCloseTab:rc})}),(0,r.jsx)("div",{className:"workspace-file-content",children:rv?.filePath?(0,r.jsx)(ao,{filePath:rv.filePath,cwd:nG??void 0,sourceSessionId:rv.sourceSessionId,gitRefreshKey:eN,initialDisplayMode:rv.initialDisplayMode,onMentionLines:nK,onAtMention:nV,onOpenFile:e=>rl(e,eZ(e),{sourceSessionId:rv.sourceSessionId})}):(0,r.jsx)("div",{className:"workspace-file-empty",children:Y("files.noneOpen")})})]}),rq=(0,r.jsx)(lK,{open:"resource"===eO.activeView,sessionId:ec?.id??null,activeTab:eU,onTabChange:eq,usage:eo}),rV=(0,r.jsx)(dj,{open:"efficiency"===eO.activeView,sessionId:ec?.id??null,activeTab:eV,onTabChange:eK}),rK=(0,r.jsx)(li,{title:rM.process,data:nS,onOpenFile:rd}),rJ=ec?ec.path?ec.path:t6?.sessionId===ec.id&&t6.sessionFile?t6.sessionFile:null:null,rG=(0,r.jsx)(lk,{title:rM.sidechat,sessionId:ec?.id??null,sessionPath:rJ,sessionName:ec?.name,historyStore:eY,flights:eX,sessionCensus:e1,visible:"sidechat"===eO.activeView}),rY=rm?(0,r.jsx)(lr,{activeView:eO.activeView,onViewChange:e=>nA(e),viewLabels:rM,sessionId:ec?.id??null,sessionPath:rJ,sessionName:ec?.name,sessionCwd:ec?.cwd??rp??void 0,liveSubagents:t7,processSlot:rK,fileSlot:rU,sideChatSlot:rG,resourceSlot:t??rq,efficiencySlot:rV,visible:!0,onClose:()=>eH({type:"select-view",view:"chat"}),onReturnFocus:tn}):null,rZ=e??rY,rX=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(Q,{selectedSessionId:ep?.id??ec?.id??null,optimisticSession:ep??ec,onSelectSession:n6,onNewSession:n3,initialSessionId:nJ,skipInitialProjectSelection:null!==q.requestedCwd,onInitialRestoreDone:ra,refreshKey:eS,onSessionDeleted:ro,selectedCwd:ec?.cwd??ev??null,onCwdChange:n4,onBackgroundTaskDone:ed}),(0,r.jsxs)("div",{className:"navigator-footer",style:{padding:"8px",flexShrink:0},children:[(0,r.jsx)(dA,{usage:eo,onOpen:()=>{eq("usage"),nA("resource",!1)}}),(0,r.jsx)(dW,{}),(0,r.jsxs)("button",{className:"navigator-settings-action",onClick:()=>{nT(null),eH({type:"close-layer"}),ee&&t_(!1),eL(!0)},title:Y("common.settings"),style:{width:"100%",height:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,background:"none",border:"1px solid var(--border)",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontFamily:"var(--font-mono)",transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.borderColor="var(--text-dim)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},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",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-2.83 2.83-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21h-4v-.09A1.7 1.7 0 0 0 8.5 19.4a1.7 1.7 0 0 0-1.88.34l-.06.06-2.83-2.83.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3v-4h.09A1.7 1.7 0 0 0 4.6 8.5a1.7 1.7 0 0 0-.34-1.88l-.06-.06 2.83-2.83.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3h4v.09A1.7 1.7 0 0 0 15.5 4.6a1.7 1.7 0 0 0 1.88-.34l.06-.06 2.83 2.83-.06.06A1.7 1.7 0 0 0 19.4 9c.12.39.33.74.6 1 .3.28.69.42 1.1.4h.09v4h-.09A1.7 1.7 0 0 0 19.4 15Z"})]}),Y("common.settings")]})]})]}),rQ=tf&&tx&&tx.requestId===tf.requestId&&tx.deploymentCompleted?tx:null,r0=rQ?.cleanup??null,r1=rQ&&!tf?.dismissed?function(e){if(!e)return{tone:"neutral",title:"업데이트 완료",detail:"임시 산출물 정리 상태를 확인하고 있습니다.",dismissible:!0,autoHideMs:null};let t=`${e.completedCount}/${e.totalCount} 완료`,n=`${Math.round(e.elapsedSeconds)}초 경과`;return"running"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 중",detail:`${t} \xb7 ${n} \xb7 현재 ${e.currentTarget??"대상 선택 중"}`,dismissible:!1,autoHideMs:null}:"failed"===e.status?{tone:"warning",title:"업데이트 완료 \xb7 산출물 정리 실패",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건 \xb7 실패 ${e.failureCount}건. 업데이트 자체는 성공했고 실패 증거는 보존했습니다.`,dismissible:!0,autoHideMs:sv(e.status)}:"pending-approval"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 승인 대기",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건. 삭제는 승인 후 실행합니다.`,dismissible:!0,autoHideMs:sv(e.status)}:"skipped"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 건너뜀",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:sv(e.status)}:{tone:"positive",title:"업데이트 완료 \xb7 산출물 정리 완료",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:sv(e.status)}}(r0):null;return(0,r.jsxs)(r.Fragment,{children:[ts?(0,r.jsx)("div",{className:"server-restart-overlay",role:"status","aria-live":"polite",children:(0,r.jsxs)("div",{className:"server-restart-card",children:[(0,r.jsx)("div",{className:"server-restart-spinner","aria-hidden":"true"}),(0,r.jsx)("strong",{children:Y("restart.title")}),(0,r.jsx)("span",{children:Y(tc?"restart.slow":"restart.body")})]})}):null,(0,r.jsxs)("div",{ref:e9,className:"workspace-shell","data-active-view":eO.activeView,"data-deck-mode":eJ.deck,"data-deck-visible":rm,children:[(0,r.jsx)("div",{"aria-hidden":"true",className:`sidebar-overlay-backdrop${tD.drawer?" is-open":""}${tE?"":" sidebar-mobile-pending"}${tL?" sidebar-mode-shift":""}`,onClick:()=>{t_(!1),tn()}}),(0,r.jsx)("div",{ref:tq.panelRef,id:"session-sidebar",className:`sidebar-container${tD.laidOut?" sidebar-open":" sidebar-closed"}${tE?"":" sidebar-mobile-pending"}${tL?" sidebar-mode-shift":""}${tq.isResizing?" sidebar-resizing":""}`,"aria-hidden":ee&&!tD.presented,inert:ee&&!tD.presented,style:{"--sidebar-width":`${tq.width}px`},children:rX}),tD.laidOut&&(0,r.jsx)("div",{...tq.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${tq.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${Y("layout.resizeSidebar")}: ${Y("layout.resizeHint")}`}),(0,r.jsxs)("div",{className:"workspace-session-region","data-active-view":eO.activeView,"aria-hidden":tD.drawer,inert:tD.drawer,children:[(0,r.jsxs)("div",{ref:tJ,className:"workspace-header-stack",children:[r1&&tf&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":r1.tone,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:r1.title}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:r1.detail}),r1.dismissible&&(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>tg(sw(tf.requestId)),"aria-label":"업데이트 상태 알림 닫기",children:"닫기"})]}),tp&&!(r1&&tf)&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":"positive",role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:Y("restart.returnedTitle")}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:Y("restart.returnedBody")}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>th(!1),"aria-label":Y("restart.returnedDismiss"),children:Y("i18n.close")})]}),(0,r.jsx)(oQ,{variant:"banner",locale:J,...X}),(0,r.jsxs)("header",{className:"workspace-header-seam",children:[(0,r.jsx)(a.r,{ref:tB,className:"workspace-header-nav-toggle",variant:"ghost",size:"small",layout:"iconOnly",type:"button",onClick:n_,"aria-controls":"session-sidebar","aria-expanded":tD.presented,title:tD.presented?Y("sidebar.hide"):Y("sidebar.show"),"aria-label":tD.presented?Y("sidebar.hide"):Y("sidebar.show"),children:tD.presented?(0,r.jsx)(o.In,{size:"16px",svg:(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:"9",y1:"3",x2:"9",y2:"21"})]})}):(0,r.jsx)(o.In,{size:"18px",svg:(0,r.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",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"})]})})}),(0,r.jsxs)("div",{className:"workspace-session-identity",title:rS,children:[(0,r.jsx)("strong",{children:rw}),(0,r.jsx)("span",{"aria-live":"polite",children:rT})]}),(0,r.jsx)("span",{className:"sr-only",role:"status",children:"error"===nd.kind?nd.message:""}),rh&&eA?.requiresTrust&&!eA.trusted&&(0,r.jsxs)(a.r,{className:"workspace-header-action",variant:"ghost",size:"small",color:"fg.warning",type:"button",onClick:()=>{eB(null),nT(null),eH({type:"close-layer"}),eW(!0)},title:Y("trust.resourcesNotLoaded"),"aria-label":Y("trust.resourcesNotLoaded"),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:"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"})]}),!ee&&(0,r.jsx)("span",{children:Y("trust.resourcesNotLoaded")})]}),rh&&rW&&(0,r.jsxs)(a.r,{className:"workspace-context-usage",variant:"ghost",size:"small",type:"button",onClick:nD,"aria-expanded":"session"===nI,title:rF??Y("session.title"),"aria-label":rD?`${rF}. ${rD}`:rF??void 0,children:[(0,r.jsx)("span",{className:"workspace-context-meter","aria-hidden":"true",children:(0,r.jsx)("span",{className:"workspace-context-meter-fill","data-level":rL.level,style:{inlineSize:`${rL.fillPercent}%`}})}),(0,r.jsx)("span",{className:"workspace-context-readout","data-level":rL.level,children:rW})]}),rh&&(0,r.jsx)(l.f,{className:"workspace-panel-toggle",variant:"neutralWeak",size:"small",pressed:rE,onPressedChange:nz,"aria-controls":"workspace-auxiliary-panel",title:"ko"===J?"보조 패널":"Auxiliary panel",children:r$}),(0,r.jsxs)(d.k.Root,{open:nR,onOpenChange:e=>nE(e),placement:"bottom-end",children:[(0,r.jsx)(d.k.Trigger,{asChild:!0,children:(0,r.jsx)(a.r,{className:"workspace-header-more",variant:"ghost",size:"small",layout:"iconOnly",type:"button",title:"ko"===J?"더 보기":"More","aria-label":"ko"===J?"더 보기":"More",children:(0,r.jsx)(o.In,{size:"16px",svg:(0,r.jsxs)("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)("circle",{cx:"12",cy:"5",r:"1"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"1"})]})})})}),(0,r.jsx)(d.k.Positioner,{children:(0,r.jsx)(d.k.Content,{"aria-label":"ko"===J?"세션 및 환경 메뉴":"Session and environment menu",children:(0,r.jsxs)(d.k.ScrollArea,{children:[(0,r.jsxs)(d.k.Group,{children:[(0,r.jsx)(d.k.GroupLabel,{children:"ko"===J?"세션":"Session"}),(0,r.jsx)(d.k.Item,{onClick:nD,children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Y("session.title")})})}),(0,r.jsx)(d.k.Item,{onClick:ru,disabled:!ec,children:(0,r.jsxs)(d.k.ItemBody,{children:[(0,r.jsx)(d.k.ItemLabel,{children:Y("history.label")}),!ec&&(0,r.jsx)(d.k.ItemDescription,{children:Y("history.unsaved")})]})}),(0,r.jsx)(d.k.Item,{onClick:()=>void ri(),disabled:null!==rB||"naming"===nd.kind,children:(0,r.jsxs)(d.k.ItemBody,{children:[(0,r.jsx)(d.k.ItemLabel,{children:rH}),rO&&(0,r.jsx)(d.k.ItemDescription,{children:rO})]})}),(0,r.jsx)(d.k.Item,{onClick:()=>nF("branches"),children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Y("i18n.branches")})})}),(0,r.jsx)(d.k.Item,{onClick:()=>nF("system"),children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Y("system.label")})})})]}),(0,r.jsxs)(d.k.Group,{children:[(0,r.jsx)(d.k.GroupLabel,{children:"ko"===J?"환경":"Environment"}),(0,r.jsx)(oQ,{variant:"menu",locale:J,...X}),(0,r.jsx)(d.k.Item,{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();K({x:t.left+t.width/2,y:t.top+t.height/2})},children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Y("light"===V?"theme.light":"dark"===V?"theme.dark":"theme.auto")})})}),Z.map(e=>(0,r.jsx)(d.k.Item,{role:"menuitemradio","aria-checked":J===e.id,onClick:()=>G(e.id),children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:e.label})})},e.id)),(0,r.jsx)(d.k.Item,{onClick:()=>{nT(null),eH({type:"close-layer"}),ee&&t_(!1),eL(!0)},children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Y("common.settings")})})})]})]})})})]})]}),nI&&nN&&(0,r.jsxs)("div",{style:{position:"fixed",top:nN.top,left:nN.left,width:nN.width,maxHeight:`calc(100dvh - ${nN.top}px - var(--omp-dock-h, 204px) - 8px)`,overflowY:"auto",zIndex:500},children:["branches"===nI&&(0,r.jsx)("div",{className:"workspace-top-panel","aria-label":Y("i18n.branches"),children:(0,r.jsx)(dT,{tree:tG.sessionId===(ec?.id??null)?tG.tree:[],activeLeafId:tG.sessionId===(ec?.id??null)?tG.leafId:null,onLeafChange:tQ,hasSession:!!ec})}),"system"===nI&&(0,r.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:t2?(0,r.jsx)("div",{style:{maxHeight:"min(600px, 75vh)",overflowY:"auto",padding:"12px 16px",color:"var(--text-muted)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",fontFamily:"var(--font-mono)"},children:t2}):""===t2?(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Y("system.empty")}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Y("system.load")})}),"session"===nI&&(0,r.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",padding:"12px 16px"},children:t6?($=t6.totalActiveMs??0,L=[...t6.sessionName?[{label:Y("session.name"),value:t6.sessionName,copyField:null}]:[],{label:Y("session.file"),value:t6.sessionFile??Y("session.inMemory"),copyField:"file"},{label:Y("session.id"),value:t6.sessionId,copyField:"id"},...$>0?[{label:Y("session.totalActive"),value:(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`})($),copyField:null}]:[]],A=[[Y("session.user"),t6.userMessages.toLocaleString(J)],[Y("session.assistant"),t6.assistantMessages.toLocaleString(J)],[Y("session.toolCalls"),t6.toolCalls.toLocaleString(J)],[Y("session.toolResults"),t6.toolResults.toLocaleString(J)],[Y("session.total"),t6.totalMessages.toLocaleString(J)]],W=[[Y("session.input"),t6.tokens.input.toLocaleString(J)],[Y("session.output"),t6.tokens.output.toLocaleString(J)],...t6.tokens.cacheRead>0?[[Y("session.cacheRead"),t6.tokens.cacheRead.toLocaleString(J)]]:[],...t6.tokens.cacheWrite>0?[[Y("session.cacheWrite"),t6.tokens.cacheWrite.toLocaleString(J)]]:[],[Y("session.total"),t6.tokens.total.toLocaleString(J)]],F=nw??t6.contextUsage,D=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),_=[...t6.cost>0?[[Y("session.cost"),`$${t6.cost.toFixed(4)}`]]:[],...F?.contextWindow?[[Y("session.context"),`${null!==F.tokens?D(F.tokens):"?"} / ${D(F.contextWindow)}${null!==F.percent?` \xb7 ${F.percent.toFixed(1)}%`:""}`]]:[],...t6.tokens.cacheRead+t6.tokens.cacheWrite>0&&t6.tokens.cacheRead+t6.tokens.cacheWrite+t6.tokens.input>0?[[Y("session.cacheHitRate"),`${(t6.tokens.cacheRead/(t6.tokens.cacheRead+t6.tokens.cacheWrite+t6.tokens.input)*100).toFixed(1)}%`]]:[]],B=(e,t,n="left",i=!1)=>(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,s])=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:i?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:s})]},`${e}:${t}`))})]}),O=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:Y("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:L.map(e=>{var t,n;let i;return(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?(t=e.copyField,n=e.value,i=nx===t,(0,r.jsx)("button",{type:"button",title:i?Y("session.copied"):Y("file"===t?"session.copyFile":"session.copyId"),onClick:()=>ny(t,n),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:i?"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=i?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:i?(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"})]})})):null})]},`session-info:${e.label}`)})})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:ee?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:ee?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[O,B(Y("session.messages"),A),B(Y("session.tokens"),[...W,..._],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Y("session.load")})})]})]}),(0,r.jsxs)("div",{className:"chat-content-layout",children:[(0,r.jsx)("div",{id:"workspace-transcript",className:"chat-session-column",children:rh?(0,r.jsx)(sU,{session:ec,newSessionCwd:rp,initialSessionData:em,transitioning:null!==ep,onAgentEnd:rn,onAttentionNeeded:rr,onSessionCreated:re,onSessionForked:rs,modelsRefreshKey:eR,chatInputRef:tK,onBranchDataChange:tX,onSystemPromptChange:t5,onSessionStatsChange:ng,onSessionStatsPanelOpen:nD,onContextUsageChange:nj,onSubagentsChange:ne,onProcessLogChange:nC,onOpenFile:rd,transcriptReplacement:"view-stack"===eJ.deck&&rm?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:rZ}):null,onComposerFocusChange:tr,onSessionBusyChange:e4,onWaitingChange:e6,onAttentionChange:ns,soundEnabled:et,onSoundToggle:en,playCueSound:er,preloadCueSound:ei,unlockAudio:es},eI):rm&&"view-stack"===eJ.deck?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:rZ}):"validating"===ey?(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:Y("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:q.requestedCwd})]}):"error"===ey?(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:"var(--danger)"},children:Y("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:q.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:ek})]}):rg?nG?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:Y("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:Y("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."}),Y("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),Y("workspace.addModels")]})]})]}):null}),"pinned"===eJ.deck&&rm&&(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-pinned","data-workspace-region":"deck",children:rZ})]})]}),"command-palette"===eO.transientLayer&&(0,r.jsx)("div",{className:"workspace-command-layer",onMouseDown:e=>{e.target===e.currentTarget&&(eH({type:"close-layer"}),tn())},children:(0,r.jsxs)("div",{ref:tt,className:"workspace-command-palette",role:"dialog","aria-modal":"true",onKeyDown:tN,"aria-label":"ko"===J?"명령 팔레트":"Command palette",children:[(0,r.jsxs)("header",{children:[(0,r.jsx)("strong",{children:"ko"===J?"명령 팔레트":"Command palette"}),(0,r.jsx)("kbd",{children:"Ctrl K"})]}),(0,r.jsxs)("div",{className:"workspace-command-list",children:[c.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>nA(e,!0),children:[(0,r.jsx)("span",{children:rM[e]}),(0,r.jsx)("small",{children:eO.activeView===e?"ko"===J?"현재 보기":"Current view":""})]},e)),u.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{eq(e),nA("resource",!1)},children:[(0,r.jsx)("span",{children:"characters"===e?"캐릭터":"usage"===e?"계정 한도":"모델 통계"}),(0,r.jsx)("small",{children:rM.resource})]},e)),(0,r.jsxs)("button",{type:"button",onClick:n_,children:[(0,r.jsx)("span",{children:tD.presented?Y("sidebar.hide"):Y("sidebar.show")}),(0,r.jsx)("small",{children:"Ctrl B"})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{eH({type:"close-layer"}),eL(!0)},children:(0,r.jsx)("span",{children:Y("common.settings")})})]})]})})]}),e$&&(0,r.jsx)(oY,{cwd:rf,sessionId:ec?.id??null,onClose:()=>{eL(!1),tn()},onModelsChanged:()=>eE(e=>e+1),onReloaded:()=>eT(e=>e+1)}),ez&&rf&&(0,r.jsx)(o0,{cwd:rf,busy:eF,error:e_,onCancel:()=>{eF||(eW(!1),tn())},onConfirm:()=>void rx()})]})}},69575:(e,t,n)=>{Promise.resolve().then(n.bind(n,64830)),Promise.resolve().then(n.bind(n,96244))},96244:(e,t,n)=>{"use strict";n.d(t,{I18nProvider:()=>p,s:()=>h});var r=n(95155),i=n(12115);let s=JSON.parse('{"common.ok":"확인","common.language":"언어","common.models":"모델","common.skills":"스킬","common.plugins":"플러그인","common.settings":"설정","updates.available":"CUELO 업데이트 있음","updates.availableTitle":"CUELO {version} 릴리스가 나왔습니다","updates.dialogEyebrow":"CUELO 릴리스","updates.dialogTitle":"새 CUELO 버전","updates.current":"현재 CUELO {version}","updates.changelog":"변경 사항","updates.viewRelease":"릴리스 보기","updates.manual":"소스에서 실행 중이면 아래 명령으로 갱신한 뒤 다시 시작하세요.","updates.copyCommand":"명령어 복사","updates.commandCopied":"명령어 복사됨","updates.copyFailed":"명령어를 복사할 수 없습니다","sidebar.hide":"사이드바 숨기기","sidebar.show":"사이드바 표시","theme.light":"라이트 모드 (클릭하면 다크)","theme.dark":"다크 모드 (클릭하면 시스템)","theme.auto":"시스템 테마 (클릭하면 라이트)","history.full":"전체 기록","history.unsaved":"전체 기록은 세션 저장 후 사용할 수 있습니다","history.label":"전체 기록","title.generating":"생성 중...","title.updated":"제목 업데이트됨","title.failed":"생성 실패","title.generate":"제목 생성","title.unsaved":"제목 생성은 세션 저장 후 사용할 수 있습니다","title.noMessages":"세션 이름을 지정하기 전에 메시지를 보내세요","title.generateSession":"세션 제목 생성","system.prompt":"시스템 프롬프트","system.empty":"시스템 프롬프트가 비어 있습니다 (도구 비활성화됨)","system.load":"시스템 프롬프트를 불러오려면 메시지를 보내세요","system.label":"시스템","session.info":"세션 정보","session.name":"이름","session.file":"파일","session.inMemory":"메모리 내","session.id":"ID","session.user":"사용자","session.assistant":"어시스턴트","session.toolCalls":"도구 호출","session.toolResults":"도구 결과","session.total":"합계","session.input":"입력","session.output":"출력","session.cacheRead":"캐시 읽기","session.cacheWrite":"캐시 쓰기","session.cost":"비용","session.context":"컨텍스트","session.copy":"{value} 복사","session.copied":"복사됨","session.title":"세션 정보","session.load":"세션 정보를 불러오려면 메시지를 보내거나 /session을 실행하세요","session.infoSection":"세션 정보","session.messages":"메시지","session.tokens":"Token","session.copyFile":"파일 경로 복사","session.copyId":"세션 ID 복사","session.cacheHitRate":"평균 캐시 적중률","session.totalActive":"활동 시간","workspace.opening":"워크스페이스를 여는 중...","workspace.unable":"워크스페이스를 열 수 없습니다","workspace.selectSession":"사이드바에서 세션을 선택하세요","workspace.getStarted":"시작하기","workspace.selectProject":"사이드바에서 프로젝트 디렉터리를 선택하세요","workspace.addModels":"하단의 모델 버튼으로 모델을 추가하세요","workspace.stepProject":"사이드바에서 프로젝트 디렉터리를 선택하세요","workspace.stepModels":"하단의 모델 버튼으로 모델을 추가하세요","workspace.mainWorking":"작업중","workspace.mainWaiting":"대기중","workspace.mainIdle":"대기","workspace.mainAttention":"입력필요","files.hidePanel":"파일 패널 숨기기","files.showPanel":"파일 패널 표시","files.noneOpen":"열린 파일 없음","layout.resizeSidebar":"사이드바 크기 조절","layout.resizeFilePanel":"파일 패널 크기 조절","layout.resizeHint":"드래그하여 크기를 조절합니다. 더블 클릭 또는 Enter 키로 초기화합니다.","sidebar.new":"새로 만들기","sidebar.newSessionTitle":"{path}에서 새 세션","sidebar.refresh":"새로고침","sidebar.projects":"프로젝트","subagents.title":"서브 Agent","subagents.running":"실행 중","subagents.finished":"완료됨","subagents.history":"기록","subagents.runningCount":"{count}개 실행 중","subagents.finishedCount":"{count}개 완료됨","subagents.failed":"실패","subagents.aborted":"중단됨","subagents.back":"서브 Agent 목록으로 돌아가기","subagents.retrying":"재시도 중 {attempt}/{max}","subagents.usingTool":"{tool} 사용 중","subagents.details":"서브 Agent 실행 상세","subagents.closeDetails":"서브 Agent 상세 닫기","subagents.noTask":"작업 설명 없음","subagents.tools":"도구 {count}개","subagents.tokens":"{count} Token","subagents.loadingTranscript":"실시간 기록을 불러오는 중…","subagents.noTranscript":"서브 Agent가 아직 기록 메시지를 작성하지 않았습니다.","subagents.transcriptUnavailable":"실시간 기록을 아직 사용할 수 없습니다. 서브 Agent가 실행되는 동안 재시도합니다.","sidebar.searchProjectsAndSessions":"프로젝트 및 세션 제목 검색…","sidebar.addProject":"사용자 지정 프로젝트 경로 추가","sidebar.projectActions":"프로젝트 작업","sidebar.projectAlias":"별칭","sidebar.projectAliasEdit":"별칭 편집","sidebar.projectHide":"숨기기","sidebar.projectUnhide":"숨김 해제","sidebar.projectShowHidden":"숨긴 프로젝트 표시","sidebar.temporaryProjects":"임시\xb7시스템 경로","sidebar.projectMoveUp":"위로 이동","sidebar.projectMoveDown":"아래로 이동","sidebar.projectMoveDisabledWhileFiltering":"프로젝트 순서를 변경하려면 검색 필터를 지우세요","sidebar.projectUpdateFailed":"프로젝트 변경 사항을 저장할 수 없습니다. 다시 시도하세요.","sidebar.expandProject":"프로젝트 펼치기","sidebar.collapseProject":"프로젝트 접기","sidebar.showMore":"더 보기","sidebar.showLess":"간략히 보기","sidebar.selectProject":"프로젝트 선택…","sidebar.filterProjects":"프로젝트 필터…","sidebar.noMatchingProjects":"일치하는 프로젝트 없음","sidebar.useDefaultDirectory":"기본 디렉터리 사용","sidebar.customPath":"사용자 지정 경로…","directoryPicker.selectDirectory":"디렉터리 선택","directoryPicker.goToParent":"상위 디렉터리로 이동","directoryPicker.directoryPath":"디렉터리 경로","directoryPicker.goToDirectory":"디렉터리로 이동","directoryPicker.go":"이동","directoryPicker.loadingDirectories":"디렉터리를 불러오는 중…","directoryPicker.noSubdirectories":"하위 디렉터리 없음","directoryPicker.openBeforeSelecting":"선택하기 전에 이 경로를 엽니다","directoryPicker.selectCurrentDirectory":"현재 디렉터리 선택","directoryPicker.selectThisFolder":"이 폴더 선택","directoryPicker.noDrives":"드라이브를 찾을 수 없음","sidebar.checking":"확인 중…","sidebar.open":"열기","sidebar.cancel":"취소","sidebar.openRepoRoot":"저장소 루트 열기","sidebar.openRepoRootTitle":"worktree를 관리하려면 저장소 루트를 여세요.","sidebar.gitRepoRootOnly":"Git 저장소 루트 전용","sidebar.gitRepoRootOnlyTitle":"worktree는 Git 저장소 루트에서만 사용할 수 있습니다.","sidebar.worktrees":"Worktree...","sidebar.checkingWorktrees":"이 디렉터리의 worktree를 확인합니다.","sidebar.filterWorktrees":"worktree 필터…","sidebar.noMatchingWorktrees":"일치하는 worktree 없음","sidebar.switchWorktree":"worktree 전환","sidebar.switchWorktreeTitle":"worktree 전환: {path}","sidebar.main":"main","sidebar.forceRemoveCheckout":"커밋되지 않은 변경 사항이 있습니다. 체크아웃을 강제로 제거할까요?","sidebar.force":"강제","sidebar.createWorktreeTitle":"Branch에 대한 worktree 체크아웃을 생성합니다","sidebar.newWorktree":"새 worktree…","sidebar.branchName":"Branch 이름","sidebar.creating":"생성 중…","sidebar.create":"생성","sidebar.loading":"불러오는 중...","sidebar.noSessions":"세션 없음","sidebar.agentRunning":"Agent 실행 중…","sidebar.newActivity":"새 활동","sidebar.newSessionActivity":"새 세션 활동","sidebar.deleteSession":"{title}을(를) 삭제할까요?","sidebar.rename":"이름 변경","sidebar.pin":"맨 위에 고정","sidebar.unpin":"고정 해제","sidebar.pinned":"고정됨","sidebar.delete":"삭제","sidebar.deleteWithShiftClick":"삭제 (Shift+클릭으로 확인 없이 삭제)","sidebar.clearProjectSessions":"세션 비우기","sidebar.clearPriorityList":"목록 비우기","sidebar.clearSessionsTitle":"세션 삭제 확인","sidebar.clearSessionsProjectBody":"{project} 프로젝트의 세션 {count}개를 영구 삭제합니다. 되돌릴 수 없습니다.","sidebar.clearSessionsPriorityBody":"우선순위 목록의 세션 {count}개를 영구 삭제합니다. 되돌릴 수 없습니다.","sidebar.clearSessionsRunningExcluded":"실행 중인 세션 {count}개는 삭제하지 않습니다.","sidebar.clearSessionsNone":"지금 삭제할 수 있는 세션이 없습니다.","sidebar.clearSessionsConfirm":"삭제","sidebar.clearSessionsCancel":"취소","sidebar.clearSessionsBusy":"삭제 중…","sidebar.clearSessionsFailed":"{count}개 세션을 삭제하지 못했습니다: {names}","sidebar.archive":"보관 (목록에서 숨김, 복원 가능)","sidebar.archived":"보관됨","sidebar.restore":"복원","sidebar.noArchivedSessions":"보관된 세션 없음","sidebar.expandForks":"Fork 펼치기","sidebar.collapseForks":"Fork 접기","sidebar.messagesCount":"메시지 {count}개","sidebar.worktreePath":"Worktree: {path}","sidebar.removeWorktreeTitle":"worktree 체크아웃 {path}을(를) 제거합니다. Branch는 유지됩니다","files.deleted":"삭제됨","files.insertPath":"채팅에 경로 삽입","files.mention":"멘션","chat.loadingSession":"세션 불러오는 중...","chat.runningTool":"도구 실행 중...","chat.runningNamedTool":"{name} 실행 중...","chat.runningTools":"{names} 실행 중...","chat.runningToolsMore":"{names} (+{count}) 실행 중...","chat.waitingModel":"모델 응답 대기 중...","todo.progress":"{percent}% \xb7 {total}개 중 {completed}개 완료 \xb7 {remaining}개 남음","todo.progressDone":"{percent}% \xb7 {total}개 중 {completed}개 완료","todo.allDone":"{count}개 모두 완료","todo.showCompleted":"완료 {count}개 보기","todo.hideCompleted":"완료 {count}개 접기","chat.runningCommand":"명령 실행 중...","chat.thinking":"생각 중...","chat.contextUsageTitle":"컨텍스트 윈도우: {limit} Token 중 {used} 사용 ({percent})","chat.contextUsageWarning":"컨텍스트 윈도우가 거의 차고 있습니다","chat.contextUsageCritical":"컨텍스트 윈도우가 거의 가득 찼습니다","chat.processDetails":"프로세스 상세","chat.message":"메시지","chat.messages":"메시지","chat.toolCall":"도구 호출","chat.toolCalls":"도구 호출","chat.collapseProcess":"프로세스 상세 접기","chat.expandProcess":"프로세스 상세 펼치기","process.empty":"이 세션에는 아직 작업 과정 기록이 없습니다","process.turn":"턴","process.turns":"턴","chat.loadEarlier":"위로 스크롤하면 이전 메시지를 불러옵니다 ({count}개 숨김)","chat.extensionRequest":"확장 요청","chat.responseSending":"응답을 보내는 중...","chat.responseFailed":"응답이 Agent에 전달되지 않았습니다. 아직 기다리는 중이니 다시 시도하세요.","chat.cancel":"취소","chat.confirm":"확인","chat.submit":"제출","chat.agentQuestion":"Agent가 입력을 기다립니다","chat.agentQuestionHint":"옵션을 선택하거나 직접 응답을 입력하세요.","chat.recommended":"추천","chat.customAnswer":"기타 응답 (선택)","chat.chatAboutThis":"이것에 대해 대화","chat.submitAnswer":"답변 제출","chat.planApproval":"계획 승인","chat.planFeedback":"추가 계획 수립을 위한 피드백 (선택)","chat.refinePlan":"계획 계속하기","chat.approvePlan":"승인 후 구현","chat.extensionInput":"확장 터미널 입력","chat.extensionPanel":"확장 패널","chat.close":"닫기","chat.queued":"대기 중 \xb7 {count}","chat.recall":"입력창으로 되돌리기","chat.recallTitle":"대기 중인 메시지를 모두 제거하고 편집할 수 있도록 입력창에 다시 넣습니다","chat.retrying":"재시도 중 ({attempt}/{max})…","chat.loadingCommands":"명령 불러오는 중...","chat.slashCommands":"슬래시 명령 \xb7 {label}","chat.tabEnter":"Tab / Enter","chat.noCommands":"명령이 없습니다","chat.match":"일치 1개","chat.matches":"일치 {count}개","chat.command":"명령 1개","chat.commands":"명령 {count}개","chat.loadingFiles":"파일 불러오는 중...","chat.files":"파일 \xb7 {label}{hint}","chat.searching":"검색 중…","chat.noMatchingFiles":"일치하는 파일 없음","chat.searchingAll":" \xb7 전체 파일 검색 중…","chat.indexTruncated":" \xb7 인덱스 일부 생략됨","chat.steerPlaceholder":"지금 지시하거나 후속 메시지를 대기열에 추가하세요...","chat.agentPlaceholder":"Agent 실행 중…","chat.messagePlaceholder":"메시지 입력… 명령어는 /, 파일은 @ 입력","chat.steer":"지시","chat.followUp":"후속 메시지","chat.send":"보내기","chat.attachImageLimit":"메시지 하나에 이미지를 최대 {count}개까지 첨부할 수 있습니다.","chat.attachImageTooLarge":"{name} 파일이 이미지당 {limit} 제한을 초과합니다.","chat.attachFile":"파일 첨부","chat.attachments":"첨부 파일","chat.removeImage":"이미지 {index} 제거","chat.removeAttachment":"{name} 제거","chat.attachExtracting":"텍스트 추출 중","chat.attachExtractingWait":"첨부 파일 처리가 끝날 때까지 기다려 주세요","chat.attachLimit":"메시지 하나에 이미지를 제외한 첨부 파일을 최대 {count}개까지 넣을 수 있습니다.","chat.attachTooLarge":"{name} 파일이 문서당 {limit} 제한을 초과합니다.","chat.attachTotalTooLarge":"첨부 문서의 합계가 {limit} 제한을 초과합니다.","chat.attachTextTooLarge":"{name}에서 추출한 텍스트가 {limit}자 제한을 초과합니다.","chat.attachTooManyPages":"{name} 파일이 PDF {limit}페이지 제한을 초과합니다.","chat.attachNoPdfText":"{name}에서 추출할 수 있는 텍스트가 없습니다. 스캔 또는 이미지 전용 PDF에 필요한 OCR은 지원하지 않습니다.","chat.attachPasswordProtected":"{name}은(는) 암호로 보호되어 텍스트를 추출할 수 없습니다.","chat.attachExtractFailed":"{name}에서 텍스트를 추출하지 못했습니다.","chat.attachKindAudio":"음성","chat.attachKindFile":"파일","chat.attachUploading":"저장 중","chat.attachTranscribing":"받아쓰기 중","chat.attachTranscribeFailed":"받아쓰기 실패","chat.attachTranscribeFailedNotice":"{name} 받아쓰기에 실패해 저장된 파일 경로만 첨부했습니다: {error}","chat.attachStoredTooLarge":"{name} 파일이 파일당 {limit} 제한을 초과합니다.","chat.attachUploadFailed":"{name} 파일을 저장하지 못했습니다: {error}","chat.steerTitle":"현재 실행을 중단하고 이 메시지를 바로 전달합니다","chat.followUpTitle":"Agent가 끝난 후 이 메시지를 전달하도록 대기열에 추가합니다","chat.filterModels":"모델 필터…","chat.noMatchingModels":"일치하는 모델 없음","chat.modelRoles":"역할","chat.allModels":"전체 모델","chat.mainPreset":"Main 프리셋","roles.title":"모델 역할","roles.description":"omp는 하나의 현재 모델이 아니라 역할별로 작업을 라우팅합니다. 각 역할에 모델을 지정하면 CUELO과 omp CLI 모두에서 사용됩니다.","roles.scope":"저장 위치","roles.scopeGlobal":"전역","roles.scopeProject":"이 프로젝트","roles.unset":"— 미설정 —","roles.needsProject":"모델 역할을 편집하려면 프로젝트를 여세요.","roles.source.global":"전역 설정에서","roles.source.project":"프로젝트 설정에서","roles.source.default":"omp 기본값","roles.thinking":"Thinking","roles.thinkingInherit":"설정된 기본 thinking 수준 사용","chat.moreControls":"실행 옵션","chat.collapseControls":"실행 옵션 닫기","chat.shell":"Shell","chat.outputLocal":"출력은 로컬에만 유지","chat.outputModel":"출력을 모델로 전송","chat.noTools":"도구 없음, 읽기 전용","chat.builtInTools":"코어: {tools} \xb7 그 외 등록된 도구는 계속 활성화됨","chat.allBuiltInTools":"코어: {tools} \xb7 그 외 등록된 도구는 계속 활성화됨","chat.changeReasoning":"추론 수준 변경: {level}","chat.changeReasoningLabel":"추론 수준 변경","chat.changeToolPreset":"도구 프리셋 변경","chat.stopCompaction":"압축 중지","chat.compactContext":"컨텍스트 압축","chat.compacting":"압축 중…","chat.compact":"Compact","chat.stopAgent":"Agent 중지","chat.stop":"중지","chat.liveVoice":"라이브 음성","chat.liveStart":"라이브 음성 시작","chat.liveStop":"라이브 음성 종료","chat.liveConnecting":"연결 중","chat.liveOn":"통화 중","chat.liveWorking":"작업 수행 중","chat.liveUnsupported":"이 브라우저에서는 라이브 통화를 할 수 없습니다","chat.liveMicDenied":"마이크 권한이 거부됐습니다","chat.liveMicUnavailable":"사용할 수 있는 마이크가 없습니다","chat.liveAuthRequired":"라이브 음성을 쓰려면 Codex 로그인이 필요합니다","chat.liveUpstreamFailed":"Codex가 라이브 통화를 거부했습니다","chat.liveFailed":"라이브 통화를 시작하지 못했습니다","chat.liveNeedsSession":"먼저 폴더를 선택하세요 — 라이브 통화는 이 대화의 에이전트로 말합니다","chat.disableSound":"완료 알림음 끄기","chat.enableSound":"완료 알림음 켜기","chat.thinkingAuto":"추론 강도 자동 선택","chat.thinkingOff":"추론 끔","chat.thinkingMinimal":"최소 추론","chat.thinkingLow":"낮은 추론","chat.thinkingMedium":"중간 추론","chat.thinkingHigh":"높은 추론","chat.thinkingXhigh":"매우 높은 추론","chat.thinkingMax":"최대 추론","chat.builtIn":"기본 제공","chat.extensions":"확장","chat.customCommands":"사용자 지정 명령어","chat.mcpPrompts":"MCP 프롬프트","chat.prompts":"프롬프트","chat.fileCommands":"명령어 파일","chat.skills":"Skill","chat.dormant":"휴면","chat.commandCompact":"컨텍스트를 압축합니다. 선택적으로 지침을 지정할 수 있습니다","chat.commandReload":"확장, Skill, 프롬프트, 도구를 다시 불러옵니다","chat.commandName":"세션 표시 이름을 설정합니다","chat.commandSession":"세션의 메시지, Token, 비용 통계를 표시합니다","chat.commandCopy":"마지막 어시스턴트 메시지를 복사합니다","chat.goalLabel":"목표","chat.goalPaused":"일시정지됨","chat.goalBudgetLeft":"{left} 남음","chat.goalTokensUsed":"{used} 사용","chat.jumpToBottom":"맨 아래로 이동","chat.compacted":"압축됨","chat.tokensSaved":"{saved} 절약","chat.filesWritten":"변경된 파일","chat.openWrittenFile":"{name} 열기","i18n.close":"닫기","i18n.copy":"복사","i18n.copied":"복사됨","i18n.cancel":"취소","i18n.save":"저장","i18n.saving":"저장 중…","i18n.saved":"저장됨","i18n.remove":"제거","i18n.removing":"제거 중…","i18n.delete":"삭제","i18n.loading":"불러오는 중...","i18n.search":"검색","i18n.refresh":"새로고침","i18n.update":"업데이트","i18n.updating":"업데이트 중...","restart.title":"CUELO 재시작 중","restart.body":"서버가 돌아오면 이 페이지가 자동으로 새로고침됩니다.","restart.slow":"재시작이 2분 넘게 끝나지 않았습니다. 서버 PC의 %USERPROFILE%\\\\.omp\\\\restart-ompweb.log에서 READY/FAILED를 확인하세요. 서버가 돌아오면 이 페이지는 그대로 새로고침됩니다.","restart.returnedTitle":"CUELO 재시작 완료","restart.returnedBody":"서버가 돌아와 이 탭을 같은 대화로 다시 연결했습니다.","restart.returnedDismiss":"재시작 알림 닫기","i18n.check":"확인","i18n.checking":"확인 중...","i18n.install":"설치","i18n.installing":"설치 중...","i18n.noResults":"결과 없음","i18n.searchProviders":"Provider 검색…","i18n.noProviders":"일치하는 Provider 없음","i18n.newModel":"새 모델","i18n.addProvider":"Provider 추가","i18n.selectProviderModel":"Provider 또는 모델을 선택하세요","i18n.visibleInPrompt":"모델 프롬프트에 표시됨 — 클릭하여 비활성화","i18n.hiddenFromPrompt":"모델 프롬프트에서 숨겨짐 — 클릭하여 활성화","i18n.dormant":"휴면","i18n.hiddenButInvocable":"모델에서 숨겨졌지만 수동 호출은 가능합니다","i18n.skillSearchPlaceholder":"예: react, testing, deploy","i18n.searching":"검색 중…","i18n.noSkills":"Skill을 찾을 수 없음","i18n.checkUpdates":"업데이트 확인","i18n.updates":"업데이트","i18n.noResolvedResources":"확인된 리소스 없음","i18n.enablePackage":"패키지 활성화","i18n.disablePackage":"패키지 비활성화","i18n.filtered":"필터링됨","i18n.openSessionToReload":"다시 불러오려면 세션을 여세요","i18n.notFound":"찾을 수 없음","i18n.noPlugins":"구성된 Plugin 없음","trust.resourcesNotLoaded":"제한 모드","trust.trustProject":"프로젝트 신뢰","trust.trusting":"신뢰 처리 중...","trust.cancel":"취소","trust.dialogTitle":"이 프로젝트를 신뢰하시겠습니까?","trust.dialogBody":"프로젝트 리소스는 로컬 코드를 실행할 수 있습니다. 내용을 알고 있는 프로젝트만 신뢰하세요.","trust.skillsNotLoaded":"이 프로젝트가 신뢰되지 않아 프로젝트 Skill이 로드되지 않았습니다.","trust.pluginsNotLoaded":"이 프로젝트가 신뢰되지 않아 프로젝트 Plugin이 로드되지 않았습니다.","trust.projectScopeUnavailable":"프로젝트 리소스가 로드되지 않은 동안에는 프로젝트 설치를 사용할 수 없습니다.","i18n.creatingSession":"새 세션 생성 중…","i18n.creating":"생성 중…","i18n.subscription":"구독","i18n.subscriptions":"구독 목록","i18n.customEndpoint":"사용자 지정 엔드포인트 형식","i18n.noChanges":"변경 사항 없음","i18n.branches":"Branch 목록","i18n.noActiveSession":"활성 세션 없음","i18n.noBranches":"이 세션에는 Branch가 없습니다","i18n.source":"소스","i18n.preview":"미리보기","i18n.diff":"Diff","i18n.downloadFile":"파일 다운로드","i18n.liveSync":"실시간 동기화 활성","i18n.notWatching":"감시 안 함","i18n.fileViewMode":"파일 보기 모드","i18n.compareHead":"작업 트리를 HEAD와 비교","i18n.mentionSelectedLines":"선택한 줄 멘션","i18n.disableWrap":"자동 줄바꿈 끄기","i18n.enableWrap":"자동 줄바꿈 켜기","i18n.htmlPreview":"HTML 미리보기","i18n.previewFile":"{file} 미리보기","i18n.invalidMermaid":"잘못된 Mermaid 다이어그램","i18n.renderingMermaid":"Mermaid 다이어그램 렌더링 중","i18n.previewAfterStreaming":"스트리밍 완료 후 미리보기 가능","i18n.showMermaidSource":"Mermaid 소스 보기","i18n.previewMermaid":"Mermaid 다이어그램 미리보기","i18n.openMermaidViewer":"다이어그램 뷰어 열기","i18n.mermaidViewer":"Mermaid 다이어그램 뷰어","i18n.mermaidDiagram":"Mermaid 다이어그램","i18n.zoomOut":"축소","i18n.zoomIn":"확대","i18n.fitToWidth":"너비에 맞춤","models.discoveryFetching":"모델 가져오는 중…","models.discoveryFetch":"모델 가져오기…","models.discoveryFilterPlaceholder":"{count}개 모델 필터…","models.discoveryFilter":"업스트림 모델 필터","models.discoverySelectShown":"표시된 항목 선택","models.discoveryNoMatches":"일치하는 모델이 없습니다.","models.discoveryAdded":"추가됨","models.discoveryShowing":"전체 {total}개 중 처음 {shown}개 표시","models.discoveryFetched":"{count}개 모델을 가져왔습니다","models.discoveryAddSelected":"선택 항목 추가","models.discoveryAddSelectedCount":"선택 항목 추가 ({count})","models.catalogSource":"출처: models.dev ↗","models.catalogFilling":"세부 정보 채우는 중…","models.catalogFill":"모델 세부 정보 채우기","models.catalogFilled":"{count}개 필드가 채워졌습니다","models.catalogNoEmptyFields":"채울 빈 필드가 없습니다","models.catalogNoExactMatch":"models.dev에서 정확히 일치하는 항목 없음","models.catalogPriceProvider":"Provider {provider}와 가격 일치","models.catalogPriceBaseUrl":"Base URL이 {provider}와 가격 일치","models.catalogPriceConsensus":"{total}개 중 {support}개 레코드에서 가격 일치","models.catalogPriceUnreliable":"신뢰할 수 있는 가격을 찾지 못했습니다","models.catalogUndo":"실행 취소","i18n.testingModel":"모델 연결 테스트 중...","i18n.connected":"연결됨","i18n.failed":"실패","i18n.test":"테스트","i18n.testConnection":"모델 연결 테스트","i18n.provider":"제공자","i18n.model":"모델","i18n.providerName":"Provider 이름","i18n.rename":"이름 변경","i18n.default":"기본값","i18n.disabled":"비활성화됨","i18n.noResources":"리소스 없음","i18n.unknown":"알 수 없음","i18n.installedVersion":"설치됨 {version}","i18n.configuredVersion":"설정됨 {version}","i18n.extensions":"확장","i18n.prompts":"프롬프트","i18n.themes":"테마","i18n.resourceCount":"{count} {label}","i18n.extensionShort":"확장","i18n.skillShort":"Skill","i18n.promptShort":"프롬프트","i18n.themeShort":"테마","i18n.custom":"사용자 지정","i18n.clearAll":"모두 지우기","i18n.connectedSuccessfully":"연결에 성공했습니다.","i18n.notConnected":"연결 안 됨","i18n.configured":"설정됨","i18n.notConfigured":"설정 안 됨","i18n.openingBrowser":"브라우저를 여는 중…","i18n.submit":"제출","i18n.login":"로그인","i18n.relogin":"다시 로그인","i18n.disconnect":"연결 해제","i18n.networkError":"네트워크 오류","i18n.continuing":"계속 진행 중…","i18n.skills":"Skill","i18n.plugins":"Plugin","i18n.addSkill":"Skill 추가","i18n.addPlugin":"Plugin 추가","i18n.selectSkill":"Skill 선택","i18n.selectPackage":"패키지 선택","i18n.updateAvailable":"업데이트 있음","i18n.upToDate":"최신 상태","i18n.automaticChecksUnavailable":"자동 확인 불가","i18n.checkFailed":"확인 실패","i18n.installed":"설치됨","i18n.status":"상태","i18n.version":"버전","i18n.package":"패키지","i18n.resources":"리소스","i18n.installedPath":"설치 경로","i18n.cwd":"CWD","i18n.resolvedResources":"확인된 리소스","i18n.reloadSession":"세션 다시 불러오기","i18n.reloading":"다시 불러오는 중...","i18n.packageRemoved":"패키지가 제거되었습니다.","i18n.packageInstalled":"패키지가 설치되었습니다.","i18n.packageUpdated":"패키지가 업데이트되었습니다.","i18n.packageDisabled":"패키지가 비활성화되었습니다.","i18n.packageEnabled":"패키지가 활성화되었습니다.","i18n.sessionReloaded":"세션을 다시 불러왔습니다.","i18n.thinking":"사고 과정","i18n.loadingThinking":"사고 과정 불러오는 중...","i18n.copyMessage":"메시지 복사","i18n.editFromHere":"여기서부터 편집","i18n.editFromHereTitle":"여기서부터 편집 — 이 세션 내에서 분기합니다","i18n.newSession":"새 세션","i18n.newSessionTitle":"새 세션 — 여기서부터 독립된 복사본을 만듭니다","i18n.estimatedTokens":"스트리밍 중 예상 Token 수","i18n.messageUsage":"사용량","i18n.messageUsageTitle":"이 메시지의 Token\xb7비용 보기","i18n.noOutput":"(출력 없음)","i18n.noSummary":"(요약 없음)","i18n.conversationCompacted":"대화가 압축됨","i18n.compactionDescription":"이 지점 이전의 대화 기록이 다음 요약으로 압축되었습니다:","i18n.fileContext":"파일 컨텍스트: {details}","i18n.readFiles":"읽은 파일","i18n.modifiedFiles":"수정된 파일","i18n.hiddenExtensionMessage":"숨겨진 확장 메시지","i18n.noMessage":"(메시지 없음)","i18n.showExtensionMessage":"확장 메시지 표시","i18n.collapse":"접기","i18n.expand":"펼치기","i18n.hideDetails":"세부 정보 숨기기","i18n.showDetails":"세부 정보 표시","i18n.thinkingUnavailable":"사고 내용을 사용할 수 없음","i18n.before":"이전","i18n.after":"이후","i18n.largeMessageReveal":"메시지 내용이 매우 큽니다 ({size}). 클릭하면 일반 텍스트로 표시합니다 — 페이지 반응성을 유지하기 위해 마크다운 렌더링은 비활성화됩니다.","i18n.sessionComplete":"세션 완료","i18n.taskFinished":"작업이 완료되었습니다.","i18n.attentionNeeded":"확인이 필요합니다","i18n.extensionInputNeeded":"확장이 입력을 기다립니다.","navigator.toolbar":"탐색 보기","navigator.priority":"우선순위","navigator.view":"{label} 보기","gpt6.boundBadge":"6PRO {handle}","gpt6.boundBadgeHint":"이 세션은 6 Pro 연결번호 {handle}에 묶여 있습니다.","usage.none":"사용량 —","usage.open":"사용량 자세히 보기: {rows}","usage.openMore":", 그 외 {count}개","usage.showMore":"나머지 {count}개 보기","usage.showLess":"접기","usage.accountBlocked":"자동 차단","usage.accountSpent":"계정 한도 소진","usage.limitSpent":"한도 소진","usage.bai":"B.AI 누적토큰","usage.baiEmpty":"기록 없음","usage.baiRange":"집계 {from}~{to}","usage.baiUnmeasured":"미측정","efficiency.title":"효율","efficiency.governor":"실행 통제","efficiency.lab":"구성 비교","efficiency.refresh":"새로고침","efficiency.refreshing":"불러오는 중…","efficiency.noSession":"세션을 선택하면 실행 기록을 볼 수 있습니다.","efficiency.loadingRuns":"실행 목록을 불러오는 중…","efficiency.runsEmpty":"이 세션에 기록된 실행이 없습니다.","efficiency.runsError":"실행 목록을 불러오지 못했습니다.","efficiency.selectRun":"실행을 고르면 역할\xb7병목\xb7미측정 공백을 볼 수 있습니다.","efficiency.loadingDetail":"실행 상세를 불러오는 중…","efficiency.detailError":"실행 상세를 불러오지 못했습니다.","efficiency.noTitle":"제목 없는 요청","efficiency.elapsed":"경과","efficiency.busyTotal":"생성시간 합","efficiency.noSumNote":"경과와 생성시간 합은 나란히만 두고 더하지 않습니다.","efficiency.summarySection":"요약","efficiency.rolesSection":"역할","efficiency.rolesEmpty":"이 실행에서 요청을 처리한 역할이 없습니다.","efficiency.bottlenecksSection":"병목","efficiency.bottlenecksEmpty":"측정된 병목이 없습니다.","efficiency.toolsSection":"도구 호출","efficiency.unmeasuredGap":"원인 미측정 공백","efficiency.elapsedValue":"경과 {value}","efficiency.estimatedCostValue":"추정 {value}","efficiency.estimatedCost":"추정 비용","efficiency.untimedLowerBound":"소요시간이 기록되지 않은 요청 {value}건 — 생성시간은 하한입니다.","efficiency.bottleneckOrderNote":"관측된 크기가 큰 순서입니다. 막대는 1위 대비 길이이며 경과시간 대비가 아닙니다.","efficiency.untimedRuns":"소요시간 미기록 run","efficiency.untimedMedianLowerBound":"소요시간이 기록되지 않은 요청이 있는 run {value}건 — 생성시간 중앙값은 하한입니다.","efficiency.unpricedLowerBound":"가격 미기록 포함 — 하한","efficiency.unmeasuredShort":"미측정","efficiency.effortLabel":"effort {value}","efficiency.requestsValue":"요청 {value}회","efficiency.toolCallsValue":"도구 호출 {value}회","efficiency.busyTime":"생성시간","efficiency.tokens":"토큰","efficiency.unpricedRequests":"가격 미기록 요청","efficiency.toolErrorsValue":"오류 {value}회","efficiency.unmeasuredGapValue":"원인 미측정 공백 {value}","efficiency.roleMain":"Main","efficiency.roleMaker":"Maker","efficiency.roleChecker":"Checker","efficiency.roleAdvisor":"Advisor","efficiency.roleUnattributed":"미배정","efficiency.purposePrimary":"Primary","efficiency.purposeRework":"Rework","efficiency.purposeReview":"Review","efficiency.outcomeCompleted":"완료","efficiency.outcomeError":"오류","efficiency.outcomeAborted":"중단됨","efficiency.outcomeInterrupted":"요청으로 끊김","efficiency.outcomeRunning":"실행 중","efficiency.folder":"폴더","efficiency.folderAll":"전체 폴더","efficiency.folderPlaceholder":"폴더로 걸러보기, Enter로 적용","efficiency.loadingExperiments":"구성 비교를 불러오는 중…","efficiency.experimentsEmpty":"비교할 구성이 기록되지 않았습니다.","efficiency.experimentsError":"구성 비교를 불러오지 못했습니다.","efficiency.difficultyNote":"작업 난이도는 보정되지 않음","efficiency.runsValue":"실행 {value}회","efficiency.medianElapsed":"경과 중앙값","efficiency.medianBusy":"생성시간 중앙값","efficiency.medianTokens":"토큰 중앙값","efficiency.medianEstimatedCost":"추정 비용 중앙값","efficiency.totalEstimatedCost":"추정 비용 합","efficiency.reworkRate":"재작업률","efficiency.errorRate":"오류율","efficiency.unpricedRuns":"가격 미기록 run","efficiency.scopeAttributed":"현재 역할 체계만","efficiency.scopeAll":"전체 기록","efficiency.scopeSessions":"집계 세션","efficiency.scopeRuns":"집계 run","efficiency.scopeExcludedRuns":"제외된 run"}'),a=["en","zh-CN","ko"],o=new Map;function l(e){if(!e.id.trim())throw Error("Locale id must not be empty");if(o.has(e.id))throw Error(`Locale already registered: ${e.id}`);o.set(e.id,e)}function d(){return[...o.keys()]}l({id:"en",label:"English",messages:{"common.ok":"OK","common.language":"Language","common.models":"Models","common.skills":"Skills","common.plugins":"Plugins","common.settings":"Settings","updates.available":"CUELO update available","updates.availableTitle":"CUELO {version} is available","updates.dialogEyebrow":"CUELO release","updates.dialogTitle":"New CUELO version","updates.current":"Running CUELO {version}","updates.changelog":"Changelog","updates.viewRelease":"View release","updates.manual":"Running from source? Update with this command, then restart.","updates.copyCommand":"Copy command","updates.commandCopied":"Command copied","updates.copyFailed":"Unable to copy the command","sidebar.hide":"Hide sidebar","sidebar.show":"Show sidebar","theme.light":"Light mode (click for dark)","theme.dark":"Dark mode (click for system)","theme.auto":"System theme (click for light)","history.full":"Full history","history.unsaved":"Full history is available after the session is saved","history.label":"Full history","title.generating":"Generating...","title.updated":"Title updated","title.failed":"Generation failed","title.generate":"Generate title","title.unsaved":"Title generation is available after the session is saved","title.noMessages":"Send a message before naming this session","title.generateSession":"Generate a session title","system.prompt":"System prompt","system.empty":"System prompt is empty (tools are disabled)","system.load":"Send a message to load the system prompt","system.label":"System","session.info":"Session info","session.name":"Name","session.file":"File","session.inMemory":"In-memory","session.id":"ID","session.user":"User","session.assistant":"Assistant","session.toolCalls":"Tool Calls","session.toolResults":"Tool Results","session.total":"Total","session.input":"Input","session.output":"Output","session.cacheRead":"Cache Read","session.cacheWrite":"Cache Write","session.cost":"Cost","session.context":"Context","session.cacheHitRate":"Avg cache hit rate","session.copy":"Copy {value}","session.copied":"Copied","session.title":"Session info","session.load":"Send a message or run /session to load session info","session.infoSection":"Session Info","session.messages":"Messages","session.tokens":"Tokens","session.totalActive":"Active Time","session.copyFile":"Copy file path","session.copyId":"Copy session ID","workspace.opening":"Opening workspace...","workspace.unable":"Unable to open workspace","workspace.selectSession":"Select a session from the sidebar","workspace.getStarted":"Get Started","workspace.selectProject":"Select a project directory from the sidebar","workspace.addModels":"Add models via the Models button at the bottom","workspace.stepProject":"Select a project directory from the sidebar","workspace.stepModels":"Add models via the Models button at the bottom","workspace.mainWorking":"Working","workspace.mainWaiting":"Waiting","workspace.mainIdle":"Idle","workspace.mainAttention":"Input needed","files.hidePanel":"Hide file panel","files.showPanel":"Show file panel","files.noneOpen":"No file open","layout.resizeSidebar":"Resize sidebar","layout.resizeFilePanel":"Resize file panel","layout.resizeHint":"Drag to resize. Double-click or press Enter to reset.","sidebar.new":"New","sidebar.newSessionTitle":"New session in {path}","sidebar.refresh":"Refresh","sidebar.projects":"Projects","subagents.title":"Subagents","subagents.running":"Running","subagents.finished":"Finished","subagents.history":"History","subagents.runningCount":"{count} running","subagents.finishedCount":"{count} finished","subagents.failed":"Failed","subagents.aborted":"Aborted","subagents.back":"Back to subagents","subagents.retrying":"Retrying {attempt}/{max}","subagents.usingTool":"Using {tool}","subagents.details":"Subagent execution details","subagents.closeDetails":"Close subagent details","subagents.noTask":"No task description","subagents.tools":"{count} tools","subagents.tokens":"{count} tokens","subagents.loadingTranscript":"Loading live transcript…","subagents.noTranscript":"The subagent has not written any transcript messages yet.","subagents.transcriptUnavailable":"Live transcript is not available yet. Retrying while the subagent runs.","sidebar.searchProjectsAndSessions":"Search projects and session titles…","sidebar.addProject":"Add custom project path","sidebar.projectActions":"Project actions","sidebar.projectAlias":"Alias","sidebar.projectAliasEdit":"Edit alias","sidebar.projectHide":"Hide","sidebar.projectUnhide":"Unhide","sidebar.projectShowHidden":"Show hidden projects","sidebar.temporaryProjects":"Temporary / system paths","sidebar.projectMoveUp":"Move up","sidebar.projectMoveDown":"Move down","sidebar.projectMoveDisabledWhileFiltering":"Clear the search filter to reorder projects","sidebar.projectUpdateFailed":"Unable to save project changes. Try again.","sidebar.expandProject":"Expand project","sidebar.collapseProject":"Collapse project","sidebar.showMore":"Show more","sidebar.showLess":"Show less","sidebar.selectProject":"Select project…","sidebar.filterProjects":"Filter projects…","sidebar.noMatchingProjects":"No matching projects","sidebar.useDefaultDirectory":"Use default directory","sidebar.customPath":"Custom path…","directoryPicker.selectDirectory":"Select directory","directoryPicker.goToParent":"Go to parent directory","directoryPicker.directoryPath":"Directory path","directoryPicker.goToDirectory":"Go to directory","directoryPicker.go":"Go","directoryPicker.loadingDirectories":"Loading directories…","directoryPicker.noSubdirectories":"No subdirectories","directoryPicker.openBeforeSelecting":"Open this path before selecting it","directoryPicker.selectCurrentDirectory":"Select current directory","directoryPicker.selectThisFolder":"Select this folder","directoryPicker.noDrives":"No drives found","sidebar.checking":"Checking…","sidebar.open":"Open","sidebar.cancel":"Cancel","sidebar.openRepoRoot":"Open repo root","sidebar.openRepoRootTitle":"Open the repository root to manage worktrees.","sidebar.gitRepoRootOnly":"Git repo root only","sidebar.gitRepoRootOnlyTitle":"Worktrees are available in Git repository roots.","sidebar.worktrees":"Worktrees...","sidebar.checkingWorktrees":"Checking worktrees for this directory.","sidebar.filterWorktrees":"Filter worktrees…","sidebar.noMatchingWorktrees":"No matching worktrees","sidebar.switchWorktree":"Switch worktree","sidebar.switchWorktreeTitle":"Switch worktree: {path}","sidebar.main":"main","sidebar.forceRemoveCheckout":"Uncommitted changes. Force remove checkout?","sidebar.force":"Force","sidebar.createWorktreeTitle":"Create a worktree checkout for a branch","sidebar.newWorktree":"New worktree…","sidebar.branchName":"branch name","sidebar.creating":"Creating…","sidebar.create":"Create","sidebar.loading":"Loading...","sidebar.noSessions":"No sessions found","sidebar.agentRunning":"Agent running…","sidebar.newActivity":"New activity","sidebar.newSessionActivity":"New session activity","sidebar.deleteSession":"Delete {title}?","sidebar.rename":"Rename","sidebar.pin":"Pin to top","sidebar.unpin":"Unpin","sidebar.pinned":"Pinned","sidebar.delete":"Delete","sidebar.deleteWithShiftClick":"Delete (Shift+click to delete without confirmation)","sidebar.clearProjectSessions":"Clear sessions","sidebar.clearPriorityList":"Clear list","sidebar.clearSessionsTitle":"Confirm session deletion","sidebar.clearSessionsProjectBody":"Permanently delete {count} session(s) in {project}. This cannot be undone.","sidebar.clearSessionsPriorityBody":"Permanently delete {count} session(s) in the priority list. This cannot be undone.","sidebar.clearSessionsRunningExcluded":"{count} running session(s) will be kept.","sidebar.clearSessionsNone":"No session can be deleted right now.","sidebar.clearSessionsConfirm":"Delete","sidebar.clearSessionsCancel":"Cancel","sidebar.clearSessionsBusy":"Deleting…","sidebar.clearSessionsFailed":"Could not delete {count} session(s): {names}","sidebar.archive":"Archive (hide from list, restorable)","sidebar.archived":"Archived","sidebar.restore":"Restore","sidebar.noArchivedSessions":"No archived sessions","sidebar.expandForks":"Expand forks","sidebar.collapseForks":"Collapse forks","sidebar.messagesCount":"{count} msgs","sidebar.worktreePath":"Worktree: {path}","sidebar.removeWorktreeTitle":"Remove worktree checkout {path}; the branch is kept","files.deleted":"Deleted","files.insertPath":"Insert path into chat","files.mention":"mention","chat.loadingSession":"Loading session...","chat.runningTool":"Running tool...","chat.runningNamedTool":"Running {name}...","chat.runningTools":"Running {names}...","chat.runningToolsMore":"Running {names} (+{count})...","chat.waitingModel":"Waiting for model...","todo.progress":"{percent}% \xb7 {completed} of {total} done \xb7 {remaining} remaining","todo.progressDone":"{percent}% \xb7 {completed} of {total} done","todo.allDone":"All {count} done","todo.showCompleted":"Show {count} completed","todo.hideCompleted":"Hide {count} completed","chat.runningCommand":"Running command...","chat.thinking":"Thinking...","chat.contextUsageTitle":"Context window: {used} of {limit} tokens ({percent})","chat.contextUsageWarning":"Context window is getting full","chat.contextUsageCritical":"Context window is nearly full","chat.processDetails":"Process details","chat.message":"message","chat.messages":"messages","chat.toolCall":"tool call","chat.toolCalls":"tool calls","chat.collapseProcess":"Collapse process details","chat.expandProcess":"Expand process details","process.empty":"No process activity in this session yet","process.turn":"turn","process.turns":"turns","chat.filesWritten":"Files changed","chat.openWrittenFile":"Open {name}","chat.loadEarlier":"Scroll up to load earlier messages ({count} hidden)","chat.extensionRequest":"extension request","chat.responseSending":"Sending your answer...","chat.responseFailed":"Your answer did not reach the agent. It is still waiting - try again.","chat.cancel":"Cancel","chat.confirm":"Confirm","chat.submit":"Submit","chat.agentQuestion":"Agent needs your input","chat.agentQuestionHint":"Choose an option or provide a custom response.","chat.recommended":"Recommended","chat.customAnswer":"Other response (optional)","chat.chatAboutThis":"Chat about this","chat.submitAnswer":"Submit answer","chat.planApproval":"Plan approval","chat.planFeedback":"Feedback for another planning pass (optional)","chat.refinePlan":"Continue planning","chat.approvePlan":"Approve and implement","chat.extensionInput":"Extension terminal input","chat.extensionPanel":"Extension panel","chat.close":"Close","chat.queued":"Queued \xb7 {count}","chat.recall":"Recall to input","chat.recallTitle":"Remove all queued messages and put them back into the input box for editing","chat.retrying":"Retrying ({attempt}/{max})…","chat.loadingCommands":"Loading commands...","chat.slashCommands":"Slash commands \xb7 {label}","chat.tabEnter":"Tab / Enter","chat.noCommands":"No commands found","chat.match":"1 match","chat.matches":"{count} matches","chat.command":"1 command","chat.commands":"{count} commands","chat.loadingFiles":"Loading files...","chat.files":"Files \xb7 {label}{hint}","chat.searching":"Searching…","chat.noMatchingFiles":"No matching files","chat.searchingAll":" \xb7 searching all files…","chat.indexTruncated":" \xb7 index truncated","chat.steerPlaceholder":"Steer now / queue follow-up...","chat.agentPlaceholder":"Agent is running…","chat.messagePlaceholder":"Message… Type / for commands, @ for files","chat.steer":"Steer","chat.followUp":"Follow-up","chat.send":"Send","chat.attachImageLimit":"A message can include at most {count} images.","chat.attachImageTooLarge":"{name} exceeds the {limit} per-image limit.","chat.attachFile":"Attach files","chat.attachments":"Attachments","chat.removeImage":"Remove image {index}","chat.removeAttachment":"Remove {name}","chat.attachExtracting":"Extracting text","chat.attachExtractingWait":"Wait for the attachments to finish processing","chat.attachLimit":"A message can include at most {count} non-image attachments.","chat.attachTooLarge":"{name} exceeds the {limit} per-document limit.","chat.attachTotalTooLarge":"Attached documents exceed the {limit} combined size limit.","chat.attachTextTooLarge":"{name} exceeds the {limit}-character extracted text limit.","chat.attachTooManyPages":"{name} exceeds the {limit}-page PDF limit.","chat.attachNoPdfText":"{name} has no extractable text. Scanned or image-only PDFs require OCR, which is not supported.","chat.attachPasswordProtected":"{name} is password-protected and cannot be extracted.","chat.attachExtractFailed":"Could not extract text from {name}.","chat.attachKindAudio":"Audio","chat.attachKindFile":"File","chat.attachUploading":"Saving","chat.attachTranscribing":"Transcribing","chat.attachTranscribeFailed":"Transcription failed","chat.attachTranscribeFailedNotice":"Could not transcribe {name}; only the saved file path is attached: {error}","chat.attachStoredTooLarge":"{name} exceeds the {limit} per-file limit.","chat.attachUploadFailed":"Could not save {name}: {error}","chat.steerTitle":"Interrupt the current run and inject this message now","chat.followUpTitle":"Queue this message after the agent finishes","chat.filterModels":"Filter models…","chat.noMatchingModels":"No matching models","chat.modelRoles":"Roles","chat.allModels":"All models","chat.mainPreset":"Main preset","roles.title":"Model roles","roles.description":"omp routes work by role, not by one current model. Assign a model to each role and both CUELO and the omp CLI use it.","roles.scope":"Save to","roles.scopeGlobal":"Global","roles.scopeProject":"This project","roles.unset":"— not set —","roles.needsProject":"Open a project to edit its model roles.","roles.source.global":"from global config","roles.source.project":"from project config","roles.source.default":"omp default","roles.thinking":"Thinking","roles.thinkingInherit":"Use the configured default thinking level","chat.moreControls":"Run options","chat.collapseControls":"Close run options","chat.shell":"Shell","chat.outputLocal":"output stays local","chat.outputModel":"output sent to model","chat.noTools":"No tools, read-only","chat.builtInTools":"Core: {tools} \xb7 other registered tools stay enabled","chat.allBuiltInTools":"Core: {tools} \xb7 other registered tools stay enabled","chat.changeReasoning":"Change reasoning level: {level}","chat.changeReasoningLabel":"Change reasoning level","chat.changeToolPreset":"Change tool preset","chat.stopCompaction":"Stop compaction","chat.compactContext":"Compact context","chat.compacting":"Compacting…","chat.compact":"Compact","chat.stopAgent":"Stop agent","chat.stop":"Stop","chat.liveVoice":"Live voice","chat.liveStart":"Start live voice","chat.liveStop":"End live voice","chat.liveConnecting":"Connecting","chat.liveOn":"Live","chat.liveWorking":"Working","chat.liveUnsupported":"This browser cannot make live calls","chat.liveMicDenied":"Microphone access was denied","chat.liveMicUnavailable":"No microphone is available","chat.liveAuthRequired":"Sign in to Codex to use live voice","chat.liveUpstreamFailed":"Codex refused the live call","chat.liveFailed":"The live call could not start","chat.liveNeedsSession":"Choose a folder first — a live call speaks as this conversation's agent","chat.disableSound":"Disable completion sound","chat.enableSound":"Enable completion sound","chat.thinkingAuto":"Automatically select reasoning effort","chat.thinkingOff":"Reasoning off","chat.thinkingMinimal":"Minimal reasoning","chat.thinkingLow":"Low reasoning","chat.thinkingMedium":"Medium reasoning","chat.thinkingHigh":"High reasoning","chat.thinkingXhigh":"Extra-high reasoning","chat.thinkingMax":"Max reasoning","chat.builtIn":"Built-in","chat.extensions":"Extensions","chat.customCommands":"Custom commands","chat.mcpPrompts":"MCP prompts","chat.prompts":"Prompts","chat.fileCommands":"Command files","chat.skills":"Skills","chat.dormant":"dormant","chat.commandCompact":"Compress context, optionally with instructions","chat.commandReload":"Reload extensions, skills, prompts, and tools","chat.commandName":"Set the session display name","chat.commandSession":"Show session message, token, and cost stats","chat.commandCopy":"Copy the last assistant message","chat.goalLabel":"Goal","chat.goalPaused":"paused","chat.goalBudgetLeft":"{left} left","chat.goalTokensUsed":"{used} used","chat.jumpToBottom":"Jump to bottom","chat.compacted":"Compacted","chat.tokensSaved":"{saved} saved","i18n.close":"Close","i18n.copy":"Copy","i18n.copied":"Copied","i18n.cancel":"Cancel","i18n.save":"Save","i18n.saving":"Saving…","i18n.saved":"Saved","i18n.remove":"Remove","i18n.removing":"Removing…","i18n.delete":"Delete","i18n.loading":"Loading...","i18n.search":"Search","i18n.refresh":"Refresh","i18n.update":"Update","i18n.updating":"Updating...","restart.title":"CUELO is restarting","restart.body":"This page reloads automatically when the server is back.","restart.slow":"The restart is taking longer than two minutes. Check READY or FAILED in %USERPROFILE%\\.omp\\restart-ompweb.log on the server PC. This page still reloads when the server is back.","restart.returnedTitle":"CUELO restarted","restart.returnedBody":"The server is back and this tab reconnected to the same conversation.","restart.returnedDismiss":"Dismiss restart notice","i18n.check":"Check","i18n.checking":"Checking...","i18n.install":"Install","i18n.installing":"Installing...","i18n.noResults":"No results","i18n.searchProviders":"Search providers…","i18n.noProviders":"No providers match","i18n.newModel":"new model","i18n.addProvider":"Add provider","i18n.selectProviderModel":"Select a provider or model","i18n.visibleInPrompt":"Visible in model prompt — click to disable","i18n.hiddenFromPrompt":"Hidden from model prompt — click to enable","i18n.dormant":"Dormant","i18n.hiddenButInvocable":"Hidden from model, still manually invocable","i18n.skillSearchPlaceholder":"e.g. react, testing, deploy","i18n.searching":"Searching…","i18n.noSkills":"No skills found","i18n.checkUpdates":"Check updates","i18n.updates":"updates","i18n.noResolvedResources":"No resolved resources","i18n.enablePackage":"Enable package","i18n.disablePackage":"Disable package","i18n.filtered":"filtered","i18n.openSessionToReload":"Open a session to reload","i18n.notFound":"Not found","i18n.noPlugins":"No plugins configured","trust.resourcesNotLoaded":"Restricted mode","trust.trustProject":"Trust project","trust.trusting":"Trusting...","trust.cancel":"Cancel","trust.dialogTitle":"Trust this project?","trust.dialogBody":"Project resources can run local code. Trust only projects whose contents you know.","trust.skillsNotLoaded":"Project skills are not loaded because this project is not trusted.","trust.pluginsNotLoaded":"Project plugins are not loaded because this project is not trusted.","trust.projectScopeUnavailable":"Project installs are unavailable while project resources are not loaded.","i18n.creatingSession":"Creating new session…","i18n.creating":"Creating…","i18n.subscription":"Subscription","i18n.subscriptions":"Subscriptions","i18n.customEndpoint":"Custom endpoint format","i18n.noChanges":"No changes","i18n.branches":"Branches","i18n.noActiveSession":"No active session","i18n.noBranches":"This session has no branches","i18n.source":"Source","i18n.preview":"Preview","i18n.diff":"Diff","i18n.downloadFile":"Download file","i18n.liveSync":"Live sync active","i18n.notWatching":"Not watching","i18n.fileViewMode":"File view mode","i18n.compareHead":"Compare working tree with HEAD","i18n.mentionSelectedLines":"Mention selected lines","i18n.disableWrap":"Disable word wrap","i18n.enableWrap":"Enable word wrap","i18n.htmlPreview":"HTML preview","i18n.previewFile":"Preview {file}","i18n.invalidMermaid":"Invalid Mermaid diagram","i18n.renderingMermaid":"Rendering Mermaid diagram","i18n.previewAfterStreaming":"Preview available after streaming","i18n.showMermaidSource":"Show Mermaid source","i18n.previewMermaid":"Preview Mermaid diagram","i18n.openMermaidViewer":"Open diagram viewer","i18n.mermaidViewer":"Mermaid diagram viewer","i18n.mermaidDiagram":"Mermaid diagram","i18n.zoomOut":"Zoom out","i18n.zoomIn":"Zoom in","i18n.fitToWidth":"Fit to width","models.discoveryFetching":"Importing models…","models.discoveryFetch":"Import models…","models.discoveryFilterPlaceholder":"Filter {count} models…","models.discoveryFilter":"Filter upstream models","models.discoverySelectShown":"Select shown","models.discoveryNoMatches":"No matching models.","models.discoveryAdded":"added","models.discoveryShowing":"Showing first {shown} of {total}","models.discoveryFetched":"{count} models fetched","models.discoveryAddSelected":"Add selected","models.discoveryAddSelectedCount":"Add selected ({count})","models.catalogSource":"source: models.dev ↗","models.catalogFilling":"Filling details…","models.catalogFill":"Fill model details","models.catalogFilled":"{count} fields filled","models.catalogNoEmptyFields":"No empty fields to fill","models.catalogNoExactMatch":"No exact models.dev match","models.catalogPriceProvider":"Price matched Provider {provider}","models.catalogPriceBaseUrl":"Price matched Base URL to {provider}","models.catalogPriceConsensus":"Price agreed by {support}/{total} records","models.catalogPriceUnreliable":"No reliable price found","models.catalogUndo":"Undo","i18n.testingModel":"Testing model connection...","i18n.connected":"Connected","i18n.failed":"Failed","i18n.test":"Test","i18n.testConnection":"Test model connection","i18n.provider":"Provider","i18n.model":"Model","i18n.providerName":"Provider name","i18n.rename":"Rename","i18n.default":"Default","i18n.disabled":"Disabled","i18n.noResources":"No resources","i18n.unknown":"Unknown","i18n.installedVersion":"installed {version}","i18n.configuredVersion":"configured {version}","i18n.extensions":"Extensions","i18n.prompts":"Prompts","i18n.themes":"Themes","i18n.resourceCount":"{count} {label}","i18n.extensionShort":"ext","i18n.skillShort":"skills","i18n.promptShort":"prompts","i18n.themeShort":"themes","i18n.custom":"Custom","i18n.clearAll":"clear all","i18n.connectedSuccessfully":"Connected successfully.","i18n.notConnected":"not connected","i18n.configured":"configured","i18n.notConfigured":"not configured","i18n.openingBrowser":"Opening browser…","i18n.submit":"Submit","i18n.login":"Login","i18n.relogin":"Re-login","i18n.disconnect":"Disconnect","i18n.networkError":"Network error","i18n.continuing":"Continuing…","i18n.skills":"Skills","i18n.plugins":"Plugins","i18n.addSkill":"Add skill","i18n.addPlugin":"Add plugin","i18n.selectSkill":"Select a skill","i18n.selectPackage":"Select a package","i18n.updateAvailable":"Update available","i18n.upToDate":"Up to date","i18n.automaticChecksUnavailable":"Automatic checks unavailable","i18n.checkFailed":"Check failed","i18n.installed":"Installed","i18n.status":"Status","i18n.version":"Version","i18n.package":"Package","i18n.resources":"Resources","i18n.installedPath":"Installed path","i18n.cwd":"CWD","i18n.resolvedResources":"Resolved Resources","i18n.reloadSession":"Reload session","i18n.reloading":"Reloading...","i18n.packageRemoved":"Package removed.","i18n.packageInstalled":"Package installed.","i18n.packageUpdated":"Package updated.","i18n.packageDisabled":"Package disabled.","i18n.packageEnabled":"Package enabled.","i18n.sessionReloaded":"Session reloaded.","i18n.thinking":"Thinking","i18n.largeMessageReveal":"Message content is very large ({size}). Click to view as plain text — markdown rendering is disabled to keep the page responsive.","i18n.loadingThinking":"Loading thinking...","i18n.copyMessage":"Copy message","i18n.editFromHere":"Edit from here","i18n.editFromHereTitle":"Edit from here — branches within this session","i18n.newSession":"New session","i18n.newSessionTitle":"New session — creates an independent copy from here","i18n.estimatedTokens":"Estimated token count while streaming","i18n.messageUsage":"Usage","i18n.messageUsageTitle":"Show this message's tokens and cost","i18n.noOutput":"(no output)","i18n.noSummary":"(no summary)","i18n.conversationCompacted":"Conversation compacted","i18n.compactionDescription":"The conversation history before this point was compacted into the following summary:","i18n.fileContext":"File context: {details}","i18n.readFiles":"Read files","i18n.modifiedFiles":"Modified files","i18n.hiddenExtensionMessage":"hidden extension message","i18n.noMessage":"(no message)","i18n.showExtensionMessage":"Show extension message","i18n.collapse":"Collapse","i18n.expand":"Expand","i18n.hideDetails":"Hide details","i18n.showDetails":"Show details","i18n.thinkingUnavailable":"Thinking content unavailable","i18n.before":"Before","i18n.after":"After","i18n.sessionComplete":"Session complete","i18n.taskFinished":"Task finished.","i18n.attentionNeeded":"Pi needs your attention","i18n.extensionInputNeeded":"An extension is waiting for your input.","navigator.toolbar":"Navigator views","navigator.priority":"Priority","navigator.view":"{label} navigator","gpt6.boundBadge":"6PRO {handle}","gpt6.boundBadgeHint":"This session is bound to 6 Pro connection number {handle}.","usage.none":"Usage —","usage.open":"Open usage details: {rows}","usage.openMore":", and {count} more","usage.showMore":"Show {count} more","usage.showLess":"Show less","usage.accountBlocked":"auto-blocked","usage.accountSpent":"account limit used up","usage.limitSpent":"limit used up","usage.bai":"B.AI tokens","usage.baiEmpty":"none recorded","usage.baiRange":"aggregated {from}–{to}","usage.baiUnmeasured":"not measured","efficiency.title":"Efficiency","efficiency.governor":"Run control","efficiency.lab":"Experiment Lab","efficiency.refresh":"Refresh","efficiency.refreshing":"Loading…","efficiency.noSession":"Select a session to see its runs.","efficiency.loadingRuns":"Loading runs…","efficiency.runsEmpty":"No runs recorded in this session.","efficiency.runsError":"Could not load runs.","efficiency.selectRun":"Select a run to see roles, bottlenecks, and unmeasured gaps.","efficiency.loadingDetail":"Loading run detail…","efficiency.detailError":"Could not load the run detail.","efficiency.noTitle":"Untitled request","efficiency.elapsed":"Elapsed","efficiency.busyTotal":"Generation time total","efficiency.noSumNote":"Elapsed and generation total are shown side by side, never added.","efficiency.summarySection":"Summary","efficiency.rolesSection":"Roles","efficiency.rolesEmpty":"No role recorded a request in this run.","efficiency.bottlenecksSection":"Bottlenecks","efficiency.bottlenecksEmpty":"No bottleneck measured.","efficiency.toolsSection":"Tool calls","efficiency.unmeasuredGap":"Unmeasured gap","efficiency.elapsedValue":"Elapsed {value}","efficiency.estimatedCostValue":"Est. {value}","efficiency.estimatedCost":"Est. cost","efficiency.untimedLowerBound":"{value} request(s) have no recorded duration — generation time is a lower bound.","efficiency.bottleneckOrderNote":"Largest observed items, longest first. Bar length is relative to the top item, not to elapsed time.","efficiency.untimedRuns":"Runs missing duration","efficiency.untimedMedianLowerBound":"{value} run(s) contain requests with no recorded duration — the median generation time is a lower bound.","efficiency.unpricedLowerBound":"Includes unpriced records — lower bound","efficiency.unmeasuredShort":"Unmeasured","efficiency.effortLabel":"Effort {value}","efficiency.requestsValue":"{value} requests","efficiency.toolCallsValue":"{value} tool calls","efficiency.busyTime":"Generation time","efficiency.tokens":"Tokens","efficiency.unpricedRequests":"Unpriced requests","efficiency.toolErrorsValue":"{value} errors","efficiency.unmeasuredGapValue":"Unmeasured gap {value}","efficiency.roleMain":"Main","efficiency.roleMaker":"Maker","efficiency.roleChecker":"Checker","efficiency.roleAdvisor":"Advisor","efficiency.roleUnattributed":"Unattributed","efficiency.purposePrimary":"Primary","efficiency.purposeRework":"Rework","efficiency.purposeReview":"Review","efficiency.outcomeCompleted":"Completed","efficiency.outcomeError":"Error","efficiency.outcomeAborted":"Aborted","efficiency.outcomeInterrupted":"Interrupted","efficiency.outcomeRunning":"Running","efficiency.folder":"Folder","efficiency.folderAll":"All folders","efficiency.folderPlaceholder":"Filter by folder, Enter to apply","efficiency.loadingExperiments":"Loading config comparison…","efficiency.experimentsEmpty":"No config recorded for comparison.","efficiency.experimentsError":"Could not load the config comparison.","efficiency.difficultyNote":"Task difficulty is not normalized.","efficiency.runsValue":"{value} runs","efficiency.medianElapsed":"Median elapsed","efficiency.medianBusy":"Median generation","efficiency.medianTokens":"Median tokens","efficiency.medianEstimatedCost":"Median est. cost","efficiency.totalEstimatedCost":"Total est. cost","efficiency.reworkRate":"Rework rate","efficiency.errorRate":"Error rate","efficiency.unpricedRuns":"Unpriced runs","efficiency.scopeAttributed":"Current roles only","efficiency.scopeAll":"All runs","efficiency.scopeSessions":"Sessions counted","efficiency.scopeRuns":"Runs counted","efficiency.scopeExcludedRuns":"Runs excluded"}}),l({id:"zh-CN",label:"简体中文",messages:{"common.ok":"确定","common.language":"语言","common.models":"模型","common.skills":"技能","common.plugins":"插件","common.settings":"设置","updates.available":"有可用的 CUELO 更新","updates.availableTitle":"CUELO {version} 可用","updates.dialogEyebrow":"CUELO 发布","updates.dialogTitle":"新的 CUELO 版本","updates.current":"当前 CUELO {version}","updates.changelog":"更新日志","updates.viewRelease":"查看发布","updates.manual":"从源码运行时,用以下命令更新后重启。","updates.copyCommand":"复制命令","updates.commandCopied":"命令已复制","updates.copyFailed":"无法复制命令","sidebar.hide":"隐藏侧边栏","sidebar.show":"显示侧边栏","theme.light":"浅色模式(点击切换到深色)","theme.dark":"深色模式(点击切换到跟随系统)","theme.auto":"跟随系统(点击切换到浅色)","history.full":"完整历史","history.unsaved":"会话保存后才能查看完整历史","history.label":"完整历史","title.generating":"正在生成...","title.updated":"标题已更新","title.failed":"生成失败","title.generate":"生成标题","title.unsaved":"会话保存后才能生成标题","title.noMessages":"请先发送消息,再为会话命名","title.generateSession":"生成会话标题","system.prompt":"系统提示词","system.empty":"系统提示词为空(工具已禁用)","system.load":"发送消息以加载系统提示词","system.label":"系统","session.info":"会话信息","session.name":"名称","session.file":"文件","session.inMemory":"内存中","session.id":"ID","session.user":"用户","session.assistant":"助手","session.toolCalls":"工具调用","session.toolResults":"工具结果","session.total":"总计","session.input":"输入","session.output":"输出","session.cacheRead":"缓存读取","session.cacheWrite":"缓存写入","session.cost":"费用","session.context":"上下文","session.cacheHitRate":"平均缓存命中率","session.copy":"复制{value}","session.copied":"已复制","session.title":"会话信息","session.load":"发送消息或运行 /session 以加载会话信息","session.infoSection":"会话信息","session.messages":"消息","session.tokens":"Token","session.totalActive":"活跃时长","session.copyFile":"复制文件路径","session.copyId":"复制会话 ID","workspace.opening":"正在打开工作区...","workspace.unable":"无法打开工作区","workspace.selectSession":"从侧边栏选择一个会话","workspace.getStarted":"开始使用","workspace.selectProject":"从侧边栏选择项目目录","workspace.addModels":"点击底部的“模型”按钮添加模型","workspace.stepProject":"从侧边栏选择项目目录","workspace.stepModels":"点击底部的“模型”按钮添加模型","workspace.mainWorking":"工作中","workspace.mainWaiting":"等待中","workspace.mainIdle":"空闲","workspace.mainAttention":"需要输入","files.hidePanel":"隐藏文件面板","files.showPanel":"显示文件面板","files.noneOpen":"没有打开的文件","layout.resizeSidebar":"调整侧边栏宽度","layout.resizeFilePanel":"调整文件面板宽度","layout.resizeHint":"拖动调整宽度。双击或按 Enter 恢复默认值。","sidebar.new":"新建","sidebar.newSessionTitle":"在 {path} 中新建会话","sidebar.refresh":"刷新","sidebar.projects":"项目","subagents.title":"子代理","subagents.running":"运行中","subagents.finished":"已完成","subagents.history":"历史","subagents.runningCount":"运行中 {count}","subagents.finishedCount":"已完成 {count}","subagents.failed":"失败","subagents.aborted":"已中止","subagents.back":"返回子代理列表","subagents.retrying":"正在重试 {attempt}/{max}","subagents.usingTool":"正在使用 {tool}","subagents.details":"子代理执行详情","subagents.closeDetails":"关闭子代理详情","subagents.noTask":"无任务描述","subagents.tools":"{count} 个工具","subagents.tokens":"{count} 个 Token","subagents.loadingTranscript":"正在加载实时记录…","subagents.noTranscript":"子代理尚未写入任何会话记录。","subagents.transcriptUnavailable":"实时记录暂不可用。子代理运行期间将继续重试。","sidebar.searchProjectsAndSessions":"搜索项目和会话标题…","sidebar.addProject":"添加自定义项目路径","sidebar.projectActions":"项目操作","sidebar.projectAlias":"别名","sidebar.projectAliasEdit":"编辑别名","sidebar.projectHide":"隐藏","sidebar.projectUnhide":"取消隐藏","sidebar.projectShowHidden":"显示隐藏的项目","sidebar.temporaryProjects":"临时/系统路径","sidebar.projectMoveUp":"上移","sidebar.projectMoveDown":"下移","sidebar.projectMoveDisabledWhileFiltering":"清除搜索筛选后才能重新排序项目","sidebar.projectUpdateFailed":"无法保存项目更改,请重试。","sidebar.expandProject":"展开项目","sidebar.collapseProject":"收起项目","sidebar.showMore":"显示更多","sidebar.showLess":"收起","sidebar.selectProject":"选择项目…","sidebar.filterProjects":"筛选项目…","sidebar.noMatchingProjects":"没有匹配的项目","sidebar.useDefaultDirectory":"使用默认目录","sidebar.customPath":"自定义路径…","directoryPicker.selectDirectory":"选择目录","directoryPicker.goToParent":"转到上级目录","directoryPicker.directoryPath":"目录路径","directoryPicker.goToDirectory":"转到目录","directoryPicker.go":"转到","directoryPicker.loadingDirectories":"正在加载目录…","directoryPicker.noSubdirectories":"没有子目录","directoryPicker.openBeforeSelecting":"选择前请先打开此路径","directoryPicker.selectCurrentDirectory":"选择当前目录","directoryPicker.selectThisFolder":"选择此文件夹","directoryPicker.noDrives":"未找到盘符","sidebar.checking":"检查中…","sidebar.open":"打开","sidebar.cancel":"取消","sidebar.openRepoRoot":"打开仓库根目录","sidebar.openRepoRootTitle":"打开仓库根目录以管理 worktree。","sidebar.gitRepoRootOnly":"仅 Git 仓库根目录","sidebar.gitRepoRootOnlyTitle":"只能在 Git 仓库根目录使用 worktree。","sidebar.worktrees":"Worktrees...","sidebar.checkingWorktrees":"正在检查此目录的 worktree。","sidebar.filterWorktrees":"筛选 worktree…","sidebar.noMatchingWorktrees":"没有匹配的 worktree","sidebar.switchWorktree":"切换 worktree","sidebar.switchWorktreeTitle":"切换 worktree:{path}","sidebar.main":"主分支","sidebar.forceRemoveCheckout":"存在未提交的更改。强制移除 checkout?","sidebar.force":"强制移除","sidebar.createWorktreeTitle":"为分支创建 worktree checkout","sidebar.newWorktree":"新建 worktree…","sidebar.branchName":"分支名称","sidebar.creating":"创建中…","sidebar.create":"创建","sidebar.loading":"加载中...","sidebar.noSessions":"未找到会话","sidebar.agentRunning":"Agent 运行中…","sidebar.newActivity":"有新活动","sidebar.newSessionActivity":"会话有新活动","sidebar.deleteSession":"删除 {title}?","sidebar.rename":"重命名","sidebar.pin":"固定到顶部","sidebar.unpin":"取消固定","sidebar.pinned":"已固定","sidebar.delete":"删除","sidebar.deleteWithShiftClick":"删除(按住 Shift 点击可跳过确认)","sidebar.clearProjectSessions":"清空会话","sidebar.clearPriorityList":"清空列表","sidebar.clearSessionsTitle":"确认删除会话","sidebar.clearSessionsProjectBody":"将永久删除 {project} 中的 {count} 个会话,且无法恢复。","sidebar.clearSessionsPriorityBody":"将永久删除优先级列表中的 {count} 个会话,且无法恢复。","sidebar.clearSessionsRunningExcluded":"保留 {count} 个正在运行的会话。","sidebar.clearSessionsNone":"当前没有可删除的会话。","sidebar.clearSessionsConfirm":"删除","sidebar.clearSessionsCancel":"取消","sidebar.clearSessionsBusy":"删除中…","sidebar.clearSessionsFailed":"有 {count} 个会话删除失败:{names}","sidebar.archive":"归档(从列表隐藏,可恢复)","sidebar.archived":"已归档","sidebar.restore":"恢复","sidebar.noArchivedSessions":"没有已归档的会话","sidebar.expandForks":"展开分叉","sidebar.collapseForks":"折叠分叉","sidebar.messagesCount":"{count} 条消息","sidebar.worktreePath":"Worktree:{path}","sidebar.removeWorktreeTitle":"移除 worktree checkout {path};保留分支","files.deleted":"已删除","files.insertPath":"将路径插入聊天","files.mention":"提及","chat.loadingSession":"正在加载会话...","chat.runningTool":"正在运行工具...","chat.runningNamedTool":"正在运行 {name}...","chat.runningTools":"正在运行 {names}...","chat.runningToolsMore":"正在运行 {names}(另有 {count} 个)...","chat.waitingModel":"正在等待模型...","todo.progress":"{percent}% \xb7 {total} 项中完成 {completed} 项 \xb7 剩余 {remaining} 项","todo.progressDone":"{percent}% \xb7 {total} 项中完成 {completed} 项","todo.allDone":"{count} 项全部完成","todo.showCompleted":"查看已完成 {count} 项","todo.hideCompleted":"收起已完成 {count} 项","chat.runningCommand":"正在运行命令...","chat.thinking":"正在思考...","chat.contextUsageTitle":"上下文窗口:已用 {used} / {limit} Token({percent})","chat.contextUsageWarning":"上下文窗口正在接近上限","chat.contextUsageCritical":"上下文窗口几乎已满","chat.processDetails":"处理详情","chat.message":"条消息","chat.messages":"条消息","chat.toolCall":"次工具调用","chat.toolCalls":"次工具调用","chat.collapseProcess":"收起处理详情","chat.expandProcess":"展开处理详情","process.empty":"此会话还没有处理记录","process.turn":"轮","process.turns":"轮","chat.filesWritten":"改动的文件","chat.openWrittenFile":"打开 {name}","chat.loadEarlier":"向上滚动以加载更早的消息(隐藏 {count} 条)","chat.extensionRequest":"扩展请求","chat.responseSending":"正在发送你的回复...","chat.responseFailed":"回复未送达代理。它仍在等待 - 请重试。","chat.cancel":"取消","chat.confirm":"确认","chat.submit":"提交","chat.agentQuestion":"代理需要你的输入","chat.agentQuestionHint":"选择一个选项,或提供自定义回复。","chat.recommended":"推荐","chat.customAnswer":"其他回复(可选)","chat.chatAboutThis":"对此进行讨论","chat.submitAnswer":"提交回答","chat.planApproval":"计划审批","chat.planFeedback":"下一轮计划的反馈(可选)","chat.refinePlan":"继续规划","chat.approvePlan":"批准并实施","chat.extensionInput":"扩展终端输入","chat.extensionPanel":"扩展面板","chat.close":"关闭","chat.queued":"已排队 \xb7 {count}","chat.recall":"移回输入框","chat.recallTitle":"移除所有排队消息并将其放回输入框编辑","chat.retrying":"正在重试({attempt}/{max})…","chat.loadingCommands":"正在加载命令...","chat.slashCommands":"斜杠命令 \xb7 {label}","chat.tabEnter":"Tab / Enter","chat.noCommands":"未找到命令","chat.match":"1 个匹配项","chat.matches":"{count} 个匹配项","chat.command":"1 个命令","chat.commands":"{count} 个命令","chat.loadingFiles":"正在加载文件...","chat.files":"文件 \xb7 {label}{hint}","chat.searching":"搜索中…","chat.noMatchingFiles":"未找到匹配的文件","chat.searchingAll":" \xb7 正在搜索所有文件…","chat.indexTruncated":" \xb7 索引不完整","chat.steerPlaceholder":"立即引导 / 排队后续消息...","chat.agentPlaceholder":"Agent 运行中…","chat.messagePlaceholder":"消息…输入 / 使用命令,输入 @ 查找文件","chat.steer":"引导","chat.followUp":"后续消息","chat.send":"发送","chat.attachImageLimit":"每条消息最多可附加 {count} 张图片。","chat.attachImageTooLarge":"{name} 超出每张图片 {limit} 的限制。","chat.attachFile":"附加文件","chat.attachments":"附件","chat.removeImage":"移除图片 {index}","chat.removeAttachment":"移除 {name}","chat.attachExtracting":"正在提取文本","chat.attachExtractingWait":"请等待附件处理完成","chat.attachLimit":"每条消息最多可附加 {count} 个非图片附件。","chat.attachTooLarge":"{name} 超出每个文档 {limit} 的限制。","chat.attachTotalTooLarge":"附加文档总大小超出 {limit} 的限制。","chat.attachTextTooLarge":"从 {name} 提取的文本超出 {limit} 个字符的限制。","chat.attachTooManyPages":"{name} 超出 PDF {limit} 页的限制。","chat.attachNoPdfText":"无法从 {name} 提取文本。扫描版或纯图片 PDF 需要 OCR,目前不支持。","chat.attachPasswordProtected":"{name} 受密码保护,无法提取文本。","chat.attachExtractFailed":"无法从 {name} 提取文本。","chat.attachKindAudio":"音频","chat.attachKindFile":"文件","chat.attachUploading":"正在保存","chat.attachTranscribing":"正在转写","chat.attachTranscribeFailed":"转写失败","chat.attachTranscribeFailedNotice":"无法转写 {name},仅附加了已保存的文件路径:{error}","chat.attachStoredTooLarge":"{name} 超出每个文件 {limit} 的限制。","chat.attachUploadFailed":"无法保存 {name}:{error}","chat.steerTitle":"中断当前运行并立即注入此消息","chat.followUpTitle":"在 Agent 完成后将此消息加入队列","chat.filterModels":"筛选模型…","chat.noMatchingModels":"没有匹配的模型","chat.modelRoles":"角色","chat.allModels":"全部模型","chat.mainPreset":"Main 预设","roles.title":"模型角色","roles.description":"omp 按角色分派任务,而非只用一个当前模型。为每个角色分配模型后,CUELO 与 omp 命令行都会使用该配置。","roles.scope":"保存到","roles.scopeGlobal":"全局","roles.scopeProject":"当前项目","roles.unset":"— 未设置 —","roles.needsProject":"打开一个项目后即可编辑其模型角色。","roles.source.global":"来自全局配置","roles.source.project":"来自项目配置","roles.source.default":"omp 默认值","roles.thinking":"推理","roles.thinkingInherit":"使用配置的默认推理级别","chat.moreControls":"运行选项","chat.collapseControls":"关闭运行选项","chat.shell":"Shell","chat.outputLocal":"输出保留在本地","chat.outputModel":"输出发送给模型","chat.noTools":"不使用工具,仅只读","chat.builtInTools":"核心:{tools} \xb7 其他已注册工具仍保持启用","chat.allBuiltInTools":"核心:{tools} \xb7 其他已注册工具仍保持启用","chat.changeReasoning":"更改推理级别:{level}","chat.changeReasoningLabel":"更改推理级别","chat.changeToolPreset":"更改工具预设","chat.stopCompaction":"停止压缩","chat.compactContext":"压缩上下文","chat.compacting":"正在压缩…","chat.compact":"压缩","chat.stopAgent":"停止 Agent","chat.stop":"停止","chat.liveVoice":"实时语音","chat.liveStart":"开始实时语音","chat.liveStop":"结束实时语音","chat.liveConnecting":"正在连接","chat.liveOn":"通话中","chat.liveWorking":"正在执行","chat.liveUnsupported":"当前浏览器无法进行实时通话","chat.liveMicDenied":"麦克风权限被拒绝","chat.liveMicUnavailable":"没有可用的麦克风","chat.liveAuthRequired":"使用实时语音需要登录 Codex","chat.liveUpstreamFailed":"Codex 拒绝了本次实时通话","chat.liveFailed":"无法启动实时通话","chat.liveNeedsSession":"请先选择文件夹 — 实时通话以本对话的智能体身份说话","chat.disableSound":"关闭完成提示音","chat.enableSound":"开启完成提示音","chat.thinkingAuto":"自动选择推理强度","chat.thinkingOff":"关闭推理","chat.thinkingMinimal":"最低限度推理","chat.thinkingLow":"低强度推理","chat.thinkingMedium":"中等强度推理","chat.thinkingHigh":"高强度推理","chat.thinkingXhigh":"超高强度推理","chat.thinkingMax":"最高强度推理","chat.builtIn":"内置","chat.extensions":"扩展","chat.customCommands":"自定义命令","chat.mcpPrompts":"MCP 提示词","chat.prompts":"提示词","chat.fileCommands":"命令文件","chat.skills":"技能","chat.dormant":"休眠","chat.commandCompact":"压缩上下文,可选附加说明","chat.commandReload":"重新加载扩展、技能、提示词和工具","chat.commandName":"设置会话显示名称","chat.commandSession":"显示会话消息、Token 和费用统计","chat.commandCopy":"复制最后一条助手消息","chat.goalLabel":"目标","chat.goalPaused":"已暂停","chat.goalBudgetLeft":"剩余 {left}","chat.goalTokensUsed":"已用 {used}","chat.jumpToBottom":"回到底部","chat.compacted":"已压缩","chat.tokensSaved":"节省 {saved}","i18n.close":"关闭","i18n.copy":"复制","i18n.copied":"已复制","i18n.cancel":"取消","i18n.save":"保存","i18n.saving":"保存中…","i18n.saved":"已保存","i18n.remove":"移除","i18n.removing":"移除中…","i18n.delete":"删除","i18n.loading":"加载中...","i18n.search":"搜索","i18n.refresh":"刷新","i18n.update":"更新","i18n.updating":"更新中...","restart.title":"CUELO 正在重启","restart.body":"服务器恢复后页面会自动刷新。","restart.slow":"重启已超过两分钟。请在服务器电脑的 %USERPROFILE%\\.omp\\restart-ompweb.log 中查看 READY 或 FAILED。服务器恢复后本页仍会自动刷新。","restart.returnedTitle":"CUELO 已重启","restart.returnedBody":"服务器已恢复,此标签页已重新连接到同一对话。","restart.returnedDismiss":"关闭重启通知","i18n.check":"检查","i18n.checking":"检查中...","i18n.install":"安装","i18n.installing":"安装中...","i18n.noResults":"没有结果","i18n.searchProviders":"搜索 Provider…","i18n.noProviders":"没有匹配的 Provider","i18n.newModel":"新模型","i18n.addProvider":"添加 Provider","i18n.selectProviderModel":"选择 Provider 或模型","i18n.visibleInPrompt":"在模型提示词中可见,点击以禁用","i18n.hiddenFromPrompt":"在模型提示词中隐藏,点击以启用","i18n.dormant":"休眠","i18n.hiddenButInvocable":"对模型隐藏,仍可手动调用","i18n.skillSearchPlaceholder":"例如 react、testing、deploy","i18n.searching":"搜索中…","i18n.noSkills":"未找到技能","i18n.checkUpdates":"检查更新","i18n.updates":"项更新","i18n.noResolvedResources":"没有已解析资源","i18n.enablePackage":"启用包","i18n.disablePackage":"禁用包","i18n.filtered":"已筛选","i18n.openSessionToReload":"打开会话后才能重新加载","i18n.notFound":"未找到","i18n.noPlugins":"未配置插件","trust.resourcesNotLoaded":"受限模式","trust.trustProject":"信任项目","trust.trusting":"正在信任...","trust.cancel":"取消","trust.dialogTitle":"信任此项目?","trust.dialogBody":"项目资源可以运行本地代码。请仅信任你了解其内容的项目。","trust.skillsNotLoaded":"此项目尚未受信任,项目技能未加载。","trust.pluginsNotLoaded":"此项目尚未受信任,项目插件未加载。","trust.projectScopeUnavailable":"项目资源未加载时,无法安装到项目范围。","i18n.creatingSession":"正在创建新会话…","i18n.creating":"创建中…","i18n.subscription":"订阅","i18n.subscriptions":"订阅服务","i18n.customEndpoint":"自定义端点格式","i18n.noChanges":"没有更改","i18n.branches":"分支","i18n.noActiveSession":"没有活动会话","i18n.noBranches":"此会话没有分支","i18n.source":"源代码","i18n.preview":"预览","i18n.diff":"Diff","i18n.downloadFile":"下载文件","i18n.liveSync":"实时同步已启用","i18n.notWatching":"未监视","i18n.fileViewMode":"文件视图模式","i18n.compareHead":"比较工作区与 HEAD","i18n.mentionSelectedLines":"提及所选行","i18n.disableWrap":"禁用自动换行","i18n.enableWrap":"启用自动换行","i18n.htmlPreview":"HTML 预览","i18n.previewFile":"预览 {file}","i18n.invalidMermaid":"Mermaid 图表无效","i18n.renderingMermaid":"正在渲染 Mermaid 图表","i18n.previewAfterStreaming":"流式输出完成后可预览","i18n.showMermaidSource":"显示 Mermaid 源码","i18n.previewMermaid":"预览 Mermaid 图表","i18n.openMermaidViewer":"打开图表查看器","i18n.mermaidViewer":"Mermaid 图表查看器","i18n.mermaidDiagram":"Mermaid 图表","i18n.zoomOut":"缩小","i18n.zoomIn":"放大","i18n.fitToWidth":"适应宽度","models.discoveryFetching":"正在导入模型…","models.discoveryFetch":"导入模型…","models.discoveryFilterPlaceholder":"筛选 {count} 个模型…","models.discoveryFilter":"筛选上游模型","models.discoverySelectShown":"选择当前结果","models.discoveryNoMatches":"没有匹配的模型。","models.discoveryAdded":"已添加","models.discoveryShowing":"显示前 {shown} 个,共 {total} 个","models.discoveryFetched":"已获取 {count} 个模型","models.discoveryAddSelected":"添加所选模型","models.discoveryAddSelectedCount":"添加所选模型({count})","models.catalogSource":"来源:models.dev ↗","models.catalogFilling":"正在填入模型信息…","models.catalogFill":"填入模型信息","models.catalogFilled":"已填入 {count} 个字段","models.catalogNoEmptyFields":"没有需要填入的空字段","models.catalogNoExactMatch":"models.dev 中没有精确匹配","models.catalogPriceProvider":"价格已匹配 Provider {provider}","models.catalogPriceBaseUrl":"价格已按 Base URL 匹配 {provider}","models.catalogPriceConsensus":"价格得到 {support}/{total} 条记录支持","models.catalogPriceUnreliable":"未找到可靠价格","models.catalogUndo":"撤销","i18n.testingModel":"正在测试模型连接...","i18n.connected":"已连接","i18n.failed":"失败","i18n.test":"测试","i18n.testConnection":"测试模型连接","i18n.provider":"Provider","i18n.model":"模型","i18n.providerName":"Provider 名称","i18n.rename":"重命名","i18n.default":"默认","i18n.disabled":"已禁用","i18n.noResources":"没有资源","i18n.unknown":"未知","i18n.installedVersion":"已安装 {version}","i18n.configuredVersion":"已配置 {version}","i18n.extensions":"扩展","i18n.prompts":"提示词","i18n.themes":"主题","i18n.resourceCount":"{count}{label}","i18n.extensionShort":"扩展","i18n.skillShort":"技能","i18n.promptShort":"提示词","i18n.themeShort":"主题","i18n.custom":"自定义","i18n.clearAll":"清除全部","i18n.connectedSuccessfully":"连接成功。","i18n.notConnected":"未连接","i18n.configured":"已配置","i18n.notConfigured":"未配置","i18n.openingBrowser":"正在打开浏览器…","i18n.submit":"提交","i18n.login":"登录","i18n.relogin":"重新登录","i18n.disconnect":"断开连接","i18n.networkError":"网络错误","i18n.continuing":"继续中…","i18n.skills":"技能","i18n.plugins":"插件","i18n.addSkill":"添加技能","i18n.addPlugin":"添加插件","i18n.selectSkill":"选择技能","i18n.selectPackage":"选择包","i18n.updateAvailable":"有可用更新","i18n.upToDate":"已是最新","i18n.automaticChecksUnavailable":"自动检查不可用","i18n.checkFailed":"检查失败","i18n.installed":"已安装","i18n.status":"状态","i18n.version":"版本","i18n.package":"包","i18n.resources":"资源","i18n.installedPath":"安装路径","i18n.cwd":"CWD","i18n.resolvedResources":"已解析资源","i18n.reloadSession":"重新加载会话","i18n.reloading":"重新加载中...","i18n.packageRemoved":"包已移除。","i18n.packageInstalled":"包已安装。","i18n.packageUpdated":"包已更新。","i18n.packageDisabled":"包已禁用。","i18n.packageEnabled":"包已启用。","i18n.sessionReloaded":"会话已重新加载。","i18n.thinking":"思考","i18n.largeMessageReveal":"消息内容过大({size})。点击以纯文本查看 — 已禁用 markdown 渲染以避免页面卡顿。","i18n.loadingThinking":"正在加载思考内容...","i18n.copyMessage":"复制消息","i18n.editFromHere":"从此处编辑","i18n.editFromHereTitle":"从此处编辑,此会话内创建分支","i18n.newSession":"新会话","i18n.newSessionTitle":"新会话,从此处创建独立副本","i18n.estimatedTokens":"流式输出期间的估算 Token 数","i18n.messageUsage":"用量","i18n.messageUsageTitle":"查看该消息的 Token 与费用","i18n.noOutput":"(无输出)","i18n.noSummary":"(无摘要)","i18n.conversationCompacted":"会话已压缩","i18n.compactionDescription":"此处之前的会话历史已压缩为以下摘要:","i18n.fileContext":"文件上下文:{details}","i18n.readFiles":"读取的文件","i18n.modifiedFiles":"修改的文件","i18n.hiddenExtensionMessage":"隐藏的扩展消息","i18n.noMessage":"(无消息)","i18n.showExtensionMessage":"显示扩展消息","i18n.collapse":"收起","i18n.expand":"展开","i18n.hideDetails":"隐藏详情","i18n.showDetails":"显示详情","i18n.thinkingUnavailable":"思考内容不可用","i18n.before":"之前","i18n.after":"之后","i18n.sessionComplete":"任务完成","i18n.taskFinished":"任务已完成。","i18n.attentionNeeded":"Pi 需要你的操作","i18n.extensionInputNeeded":"扩展正在等待你的输入。","navigator.toolbar":"导航视图","navigator.priority":"优先级","navigator.view":"{label}导航","gpt6.boundBadge":"6PRO {handle}","gpt6.boundBadgeHint":"该会话已绑定到 6 Pro 连接编号 {handle}。","usage.none":"用量 —","usage.open":"查看用量详情:{rows}","usage.openMore":",另有 {count} 项","usage.showMore":"查看其余 {count} 项","usage.showLess":"收起","usage.accountBlocked":"自动拦截","usage.accountSpent":"账户额度用尽","usage.limitSpent":"额度用尽","usage.bai":"B.AI 累计 Token","usage.baiEmpty":"无记录","usage.baiRange":"统计 {from}~{to}","usage.baiUnmeasured":"未测量","efficiency.title":"效率","efficiency.governor":"运行管控","efficiency.lab":"配置比较","efficiency.refresh":"刷新","efficiency.refreshing":"正在加载…","efficiency.noSession":"选择会话后查看其运行记录。","efficiency.loadingRuns":"正在加载运行记录…","efficiency.runsEmpty":"该会话暂无运行记录。","efficiency.runsError":"无法加载运行记录。","efficiency.selectRun":"选择一条运行,查看角色、瓶颈与未测量空白。","efficiency.loadingDetail":"正在加载运行详情…","efficiency.detailError":"无法加载运行详情。","efficiency.noTitle":"无标题请求","efficiency.elapsed":"耗时","efficiency.busyTotal":"生成时间合计","efficiency.noSumNote":"耗时与生成时间合计并列显示,绝不相加。","efficiency.summarySection":"摘要","efficiency.rolesSection":"角色","efficiency.rolesEmpty":"本次运行中没有角色处理请求。","efficiency.bottlenecksSection":"瓶颈","efficiency.bottlenecksEmpty":"没有测量到瓶颈。","efficiency.toolsSection":"工具调用","efficiency.unmeasuredGap":"原因未测量空白","efficiency.elapsedValue":"耗时 {value}","efficiency.estimatedCostValue":"预估 {value}","efficiency.estimatedCost":"预估费用","efficiency.untimedLowerBound":"有 {value} 个请求没有记录耗时 — 生成时间为下限。","efficiency.bottleneckOrderNote":"按观测到的时长从大到小排列。条形长度相对于第一项,而非经过时间。","efficiency.untimedRuns":"缺少耗时的 run","efficiency.untimedMedianLowerBound":"有 {value} 个 run 含未记录耗时的请求 — 生成时间中位数为下限。","efficiency.unpricedLowerBound":"包含未计价记录 — 下限","efficiency.unmeasuredShort":"未测量","efficiency.effortLabel":"effort {value}","efficiency.requestsValue":"{value} 次请求","efficiency.toolCallsValue":"{value} 次工具调用","efficiency.busyTime":"生成时间","efficiency.tokens":"Token","efficiency.unpricedRequests":"未计价请求","efficiency.toolErrorsValue":"{value} 次错误","efficiency.unmeasuredGapValue":"原因未测量空白 {value}","efficiency.roleMain":"Main","efficiency.roleMaker":"Maker","efficiency.roleChecker":"Checker","efficiency.roleAdvisor":"Advisor","efficiency.roleUnattributed":"未归属","efficiency.purposePrimary":"Primary","efficiency.purposeRework":"Rework","efficiency.purposeReview":"Review","efficiency.outcomeCompleted":"已完成","efficiency.outcomeError":"错误","efficiency.outcomeAborted":"已中止","efficiency.outcomeInterrupted":"被下一请求打断","efficiency.outcomeRunning":"运行中","efficiency.folder":"文件夹","efficiency.folderAll":"全部文件夹","efficiency.folderPlaceholder":"按文件夹过滤,回车应用","efficiency.loadingExperiments":"正在加载配置比较…","efficiency.experimentsEmpty":"没有可比较的配置记录。","efficiency.experimentsError":"无法加载配置比较。","efficiency.difficultyNote":"任务难度未归一化。","efficiency.runsValue":"{value} 次运行","efficiency.medianElapsed":"耗时中位数","efficiency.medianBusy":"生成时间中位数","efficiency.medianTokens":"Token 中位数","efficiency.medianEstimatedCost":"预估费用中位数","efficiency.totalEstimatedCost":"预估费用合计","efficiency.reworkRate":"返工率","efficiency.errorRate":"错误率","efficiency.unpricedRuns":"未计价运行","efficiency.scopeAttributed":"仅当前角色体系","efficiency.scopeAll":"全部记录","efficiency.scopeSessions":"纳入会话","efficiency.scopeRuns":"纳入 run","efficiency.scopeExcludedRuns":"已排除 run"}}),l({id:"ko",label:"한국어",messages:s});let c="pi-locale",u=(0,i.createContext)(null);function p({children:e}){let[t,n]=(0,i.useState)("en"),[s,l]=(0,i.useState)(!1),h=(0,i.useMemo)(()=>d().map(e=>o.get(e)).filter(e=>!!e),[]),m=(0,i.useMemo)(()=>Object.fromEntries(d().flatMap(e=>{let t=o.get(e);return t?[[e,t.messages]]:[]})),[]);(0,i.useEffect)(()=>{let e=function(){var e;let t=null;try{t=window.localStorage.getItem(c)}catch{}let n=window.navigator.languages.length?window.navigator.languages:[window.navigator.language];return"string"==typeof(e=t)&&a.includes(e)?e:function(e){for(let t of e){let e=t.toLowerCase();if("en"===e||e.startsWith("en-"))return"en";if("ko"===e||e.startsWith("ko-"))break;if("zh"===e||e.startsWith("zh-"))return"zh-CN"}return"ko"}(n)}();n(e),document.documentElement.lang=e,l(!0)},[]);let f=(0,i.useCallback)(e=>{if(o.get(e)){n(e),document.documentElement.lang=e;try{window.localStorage.setItem(c,e)}catch{}}},[]),g=(0,i.useCallback)((e,n)=>(function(e,t,n,r={}){let i=n[e]?.[t]??n.en?.[t];return void 0===i?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,n)=>{let r=t[n];return void 0===r?e:String(r)})}(i,r)})(t,e,m,n),[t,m]),x=(0,i.useMemo)(()=>({locale:s?t:"en",setLocale:f,t:g,supportedLocales:h}),[s,t,f,g,h]);return(0,r.jsx)(u.Provider,{value:x,children:e})}function h(){let e=(0,i.useContext)(u);if(!e)throw Error("useI18n must be used inside I18nProvider");return e}},98795:e=>{e.exports={root:"SearchableSelect_root__FMhaH",trigger:"SearchableSelect_trigger__eqMdt",value:"SearchableSelect_value__eJ2RU",placeholder:"SearchableSelect_placeholder__Hkg33",chevron:"SearchableSelect_chevron__DSTnM",popover:"SearchableSelect_popover__5VxMd",searchWrap:"SearchableSelect_searchWrap__IoKKk",searchIcon:"SearchableSelect_searchIcon__A6f0C",search:"SearchableSelect_search__W_1al",options:"SearchableSelect_options__tjHyi",option:"SearchableSelect_option__LRRH9",optionCopy:"SearchableSelect_optionCopy__W87H8",optionLabel:"SearchableSelect_optionLabel__G7jIg",optionDescription:"SearchableSelect_optionDescription__cE_cC",check:"SearchableSelect_check__1Likw",empty:"SearchableSelect_empty__vZzXQ"}}},e=>{e.O(0,[6026,2100,7330,2545,6379,8441,3794,7358],()=>e(e.s=69575)),_N_E=e.O()}]);