farming-code 2.2.29 → 2.2.32

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 (385) hide show
  1. package/README.md +25 -66
  2. package/README.zh_cn.md +15 -66
  3. package/THIRD_PARTY_NOTICES.md +7 -0
  4. package/backend/acp/{client-services.js → client-services.cjs} +132 -134
  5. package/backend/acp/packaged-claude-acp.cjs +37 -0
  6. package/backend/acp/packaged-codex-acp.cjs +37 -0
  7. package/backend/acp/patch-decisions.cjs +182 -0
  8. package/backend/acp/permission-security.cjs +131 -0
  9. package/backend/{acp-checkpoint-store.js → acp-checkpoint-store.cjs} +90 -59
  10. package/backend/{acp-runtime.js → acp-runtime.cjs} +1219 -1125
  11. package/backend/acp-session-state.cjs +622 -0
  12. package/backend/acp-transcript.cjs +525 -0
  13. package/backend/agent-env.cjs +257 -0
  14. package/backend/agent-extension-discovery.cjs +452 -0
  15. package/backend/agent-extension-inventory.cjs +116 -0
  16. package/backend/agent-json-stream.cjs +283 -0
  17. package/backend/agent-lifecycle-journal.cjs +185 -0
  18. package/backend/{agent-manager.js → agent-manager.cjs} +3116 -4275
  19. package/backend/agent-order-transaction.cjs +85 -0
  20. package/backend/agent-order.cjs +159 -0
  21. package/backend/agent-provider-session.cjs +98 -0
  22. package/backend/agent-runtime-binding.cjs +179 -0
  23. package/backend/agent-session-history.cjs +1022 -0
  24. package/backend/agent-session-inventory.cjs +291 -0
  25. package/backend/async-cache.cjs +104 -0
  26. package/backend/atomic-json-store.cjs +67 -0
  27. package/backend/auth.cjs +261 -0
  28. package/backend/authoritative-inventory-cache.cjs +383 -0
  29. package/backend/business-health.cjs +68 -0
  30. package/backend/chat-runtime.cjs +50 -0
  31. package/backend/claude-settings.cjs +132 -0
  32. package/backend/cli-agents.cjs +435 -0
  33. package/backend/codex-context-window.cjs +196 -0
  34. package/backend/codex-models.cjs +228 -0
  35. package/backend/codex-session-archive.cjs +82 -0
  36. package/backend/codex-session-history.cjs +590 -0
  37. package/backend/{codex-terminal-profile.js → codex-terminal-profile.cjs} +149 -155
  38. package/backend/codex-transcript-sanitizer.cjs +130 -0
  39. package/backend/codex-transcript.cjs +2107 -0
  40. package/backend/command-runner-child.cjs +105 -0
  41. package/backend/config-manager.cjs +1263 -0
  42. package/backend/control-api.cjs +439 -0
  43. package/backend/data/LICENSE.cua +21 -0
  44. package/backend/executable-discovery.cjs +204 -0
  45. package/backend/farming-agent-bootstrap.cjs +81 -0
  46. package/backend/farming-agent-bootstrap.zh_cn.md +6 -2
  47. package/backend/{farming-app-cli.js → farming-app-cli.cjs} +441 -493
  48. package/backend/farming-cli.cjs +414 -0
  49. package/backend/farming-net-pass.cjs +319 -0
  50. package/backend/farming-net-registry.cjs +123 -0
  51. package/backend/farming-net-server.cjs +309 -0
  52. package/backend/farming-session-store.cjs +651 -0
  53. package/backend/git-worktree-info.cjs +181 -0
  54. package/backend/haiku-token.cjs +828 -0
  55. package/backend/index-html.cjs +96 -0
  56. package/backend/input-parts.cjs +68 -0
  57. package/backend/input-routing.cjs +40 -0
  58. package/backend/{local-session-engine.js → local-session-engine.cjs} +276 -282
  59. package/backend/main-agent-skills.cjs +309 -0
  60. package/backend/main-page-session.cjs +132 -0
  61. package/backend/native-pty-controller-generation.cjs +139 -0
  62. package/backend/{native-pty-host-client.js → native-pty-host-client.cjs} +338 -346
  63. package/backend/native-pty-host-identity.cjs +125 -0
  64. package/backend/native-pty-host-path.cjs +68 -0
  65. package/backend/{native-pty-host.js → native-pty-host.cjs} +480 -569
  66. package/backend/native-session-engine.cjs +296 -0
  67. package/backend/network.cjs +57 -0
  68. package/backend/npm-update-helper.cjs +399 -0
  69. package/backend/packaged-node-pty.cjs +120 -0
  70. package/backend/preview-session-manager.cjs +89 -0
  71. package/backend/provider-adapters.cjs +492 -0
  72. package/backend/provider-home-configuration.cjs +211 -0
  73. package/backend/provider-session-id.cjs +79 -0
  74. package/backend/provider-session-service.cjs +333 -0
  75. package/backend/qr-share-tickets.cjs +119 -0
  76. package/backend/resource-broadcast-protocol.cjs +50 -0
  77. package/backend/review-diff-router.cjs +202 -0
  78. package/backend/review-diff-service.cjs +1267 -0
  79. package/backend/review-session-router.cjs +93 -0
  80. package/backend/review-session-service.cjs +470 -0
  81. package/backend/review-session-store.cjs +161 -0
  82. package/backend/review-state-router.cjs +132 -0
  83. package/backend/review-state-store.cjs +299 -0
  84. package/backend/run-history-store.cjs +97 -0
  85. package/backend/runtime-dependency-manager.cjs +893 -0
  86. package/backend/runtime-executable-invocation.cjs +37 -0
  87. package/backend/runtime-observation.cjs +96 -0
  88. package/backend/server-process-identity.cjs +70 -0
  89. package/backend/server.cjs +3356 -0
  90. package/backend/session-engine-bridge.cjs +144 -0
  91. package/backend/session-engine-router.cjs +105 -0
  92. package/backend/session-engine.cjs +64 -0
  93. package/backend/session-stream-protocol.cjs +181 -0
  94. package/backend/shell-busy-integration.cjs +442 -0
  95. package/backend/slash-command-discovery.cjs +423 -0
  96. package/backend/storage-layout.cjs +263 -0
  97. package/backend/system-monitor.cjs +96 -0
  98. package/backend/terminal-attach-checkpoint.cjs +73 -0
  99. package/backend/terminal-exit-quiescence.cjs +57 -0
  100. package/backend/{terminal-reducer-flow-control.js → terminal-reducer-flow-control.cjs} +45 -22
  101. package/backend/terminal-runtime-cleanup.cjs +99 -0
  102. package/backend/{terminal-screen-state.js → terminal-screen-state.cjs} +100 -108
  103. package/backend/{terminal-screen-worker-pool.js → terminal-screen-worker-pool.cjs} +89 -79
  104. package/backend/{terminal-screen-worker-thread.js → terminal-screen-worker-thread.cjs} +64 -65
  105. package/backend/terminal-screen-worker.cjs +352 -0
  106. package/backend/terminal-state-serialization.cjs +147 -0
  107. package/backend/{terminal-status.js → terminal-status.cjs} +137 -187
  108. package/backend/theme-manager.cjs +185 -0
  109. package/backend/update-service.cjs +675 -0
  110. package/backend/usage-forecast.cjs +95 -0
  111. package/backend/{usage-history-client.js → usage-history-client.cjs} +144 -94
  112. package/backend/usage-history-smoke.cjs +85 -0
  113. package/backend/usage-history-worker.cjs +60 -0
  114. package/backend/{usage-monitor.js → usage-monitor.cjs} +363 -390
  115. package/backend/workspace-directory.cjs +239 -0
  116. package/backend/workspace-discovery.cjs +271 -0
  117. package/backend/{workspace-file-router.js → workspace-file-router.cjs} +213 -282
  118. package/backend/{workspace-file-service.js → workspace-file-service.cjs} +1139 -1318
  119. package/backend/workspace-root-registry.cjs +192 -0
  120. package/bin/farming +1 -1
  121. package/config/farming.deploy.env.example +1 -1
  122. package/config/farming.install.env.example +1 -1
  123. package/dist/acp/codex-acp-1.1.4.mjs +405 -8
  124. package/dist/assets/App-BCkdpWB6.css +1 -0
  125. package/dist/assets/App-CRjKpaGp.js +697 -0
  126. package/dist/assets/CodeSelect-Ci8sKZPU.js +1 -0
  127. package/dist/assets/CodeSelect-T2eNzrOc.css +1 -0
  128. package/dist/assets/{FileEditorMarkdownPreview-Cs9cLv8a.js → FileEditorMarkdownPreview-V06QHlAg.js} +55 -55
  129. package/dist/assets/FileEditorPane-BX-Wjg9U.js +2 -0
  130. package/dist/assets/IconGlyphs-YhV7tqd4.js +1 -0
  131. package/dist/assets/ProjectFilesSection-BDT2_r0o.js +12 -0
  132. package/dist/assets/ReviewPage-BqAs5sG1.js +3 -0
  133. package/dist/assets/code-dark-B7eM_9G9.css +1 -0
  134. package/dist/assets/{cssMode-Bdg5RpcJ.js → cssMode-ADdAlxTO.js} +1 -1
  135. package/dist/assets/{editor.api2-D74ufkbr.js → editor.api2-BFLAr0YF.js} +162 -162
  136. package/dist/assets/file-icons-BpeqWkIB.js +1 -0
  137. package/dist/assets/{freemarker2-DfMDJfnE.js → freemarker2-C90q5jrp.js} +1 -1
  138. package/dist/assets/{handlebars-BEdPtzMT.js → handlebars-BwUQcEDq.js} +1 -1
  139. package/dist/assets/{html-B1fPb1QD.js → html-1s3uPKfh.js} +1 -1
  140. package/dist/assets/{htmlMode-CY2ZjHxH.js → htmlMode-xtKD99de.js} +1 -1
  141. package/dist/assets/{index-CQNaZc3l.js → index-C8MchCem.js} +3 -3
  142. package/dist/assets/{javascript-BV2OsWA0.js → javascript-Ph7ijyny.js} +1 -1
  143. package/dist/assets/{jsonMode-zd07aeuX.js → jsonMode-D-jGAnFH.js} +1 -1
  144. package/dist/assets/linkComputer-CbGyI_qx.js +1 -0
  145. package/dist/assets/{liquid-BParI24X.js → liquid-0IamE_cI.js} +1 -1
  146. package/dist/assets/{lspLanguageFeatures-BzredkoV.js → lspLanguageFeatures-BxnQunWF.js} +1 -1
  147. package/dist/assets/main-CLKXa6hf.css +1 -0
  148. package/dist/assets/{mdx-vGzUJN98.js → mdx-DdNmfivn.js} +1 -1
  149. package/dist/assets/{monaco.contribution-BmaeBQEc.js → monaco.contribution-B43jsUs1.js} +2 -2
  150. package/dist/assets/{python-CUwdLgsI.js → python-IAt4X5TS.js} +1 -1
  151. package/dist/assets/{razor-BScebUxU.js → razor-DRkFYW0S.js} +1 -1
  152. package/dist/assets/review-C8-oPKXk.css +1 -0
  153. package/dist/assets/{tsMode-DzUAibXK.js → tsMode-_d_4U2gf.js} +1 -1
  154. package/dist/assets/{typescript-D9EOeM7N.js → typescript-C7zcMq9l.js} +1 -1
  155. package/dist/assets/{workers-DAiomYZM.js → workers-D0nOyJzf.js} +1 -1
  156. package/dist/assets/workspace-editor-model-DND_Y-Bj.js +1 -0
  157. package/dist/assets/workspace-editor-monaco-BPWhgcIB.js +4 -0
  158. package/dist/assets/workspace-editor-monaco-N641qPjX.js +1 -0
  159. package/dist/assets/workspace-view-state-k1bTlJ_Z.js +13 -0
  160. package/dist/assets/{xml-wWl1dhkQ.js → xml-BR-HvxT8.js} +1 -1
  161. package/dist/assets/{yaml-Dc2WDaOZ.js → yaml-YtFQwh4q.js} +1 -1
  162. package/dist/index.html +2 -1
  163. package/extensions/browser/backend/agent-browser-runtime.cjs +1040 -0
  164. package/extensions/browser/backend/agent-capability.cjs +85 -0
  165. package/extensions/browser/backend/browser-mcp-server.cjs +655 -0
  166. package/extensions/browser/backend/browser-resource-manager.cjs +1486 -0
  167. package/extensions/browser/backend/browser-resource-store.cjs +228 -0
  168. package/extensions/browser/backend/browser-router.cjs +203 -0
  169. package/extensions/browser/backend/executable-discovery.cjs +248 -0
  170. package/extensions/browser/backend/farming-browser-client.cjs +116 -0
  171. package/extensions/browser/backend/index.cjs +32 -0
  172. package/extensions/browser/backend/managed-chromium-installer.cjs +833 -0
  173. package/extensions/browser/bin/farming-browser +16 -7
  174. package/extensions/computer/backend/agent-capability.cjs +72 -0
  175. package/extensions/computer/backend/computer-constants.cjs +59 -0
  176. package/extensions/computer/backend/computer-mcp-server.cjs +182 -0
  177. package/extensions/computer/backend/computer-resource-manager.cjs +1219 -0
  178. package/extensions/computer/backend/computer-resource-store.cjs +190 -0
  179. package/extensions/computer/backend/computer-router.cjs +257 -0
  180. package/extensions/computer/backend/cua-tools.json +3067 -0
  181. package/extensions/computer/backend/farming-computer-client.cjs +84 -0
  182. package/extensions/computer/backend/index.cjs +35 -0
  183. package/extensions/computer/backend/isolated-browser-provider.cjs +157 -0
  184. package/extensions/computer/bin/farming-computer +131 -0
  185. package/frontend/farming-net/app.js +255 -262
  186. package/frontend/ghostty-loader.js +24 -20
  187. package/frontend/reading-anchor.js +210 -193
  188. package/frontend/runtime-paths.js +24 -26
  189. package/frontend/session-bridge.js +90 -111
  190. package/frontend/session-modal-bridge.js +184 -302
  191. package/frontend/skin-bridge.js +20 -23
  192. package/frontend/skins/crt/app.js +7686 -7901
  193. package/frontend/skins/crt/effects.js +7 -6
  194. package/frontend/skins/crt/index.html +6 -6
  195. package/frontend/skins/crt/styles/markdown.css +4 -4
  196. package/frontend/terminal-bridge.js +174 -181
  197. package/frontend/terminal-replay.js +320 -345
  198. package/frontend/theme-loader.js +55 -71
  199. package/index.html +1 -0
  200. package/package.json +64 -37
  201. package/shared/backend-connection-status.js +38 -69
  202. package/shared/browser-protocol.js +235 -110
  203. package/shared/websocket-liveness.js +40 -0
  204. package/backend/acp/packaged-claude-acp.js +0 -13
  205. package/backend/acp/packaged-codex-acp.js +0 -13
  206. package/backend/acp/patch-decisions.js +0 -153
  207. package/backend/acp/permission-security.js +0 -108
  208. package/backend/acp-session-state.js +0 -644
  209. package/backend/acp-transcript.js +0 -512
  210. package/backend/agent-env.js +0 -250
  211. package/backend/agent-json-stream.js +0 -268
  212. package/backend/agent-lifecycle-journal.js +0 -133
  213. package/backend/agent-memory-report.js +0 -583
  214. package/backend/agent-order.js +0 -166
  215. package/backend/agent-provider-session.js +0 -76
  216. package/backend/agent-runtime-binding.js +0 -174
  217. package/backend/agent-session-history.js +0 -953
  218. package/backend/async-cache.js +0 -94
  219. package/backend/atomic-json-store.js +0 -37
  220. package/backend/auth.js +0 -251
  221. package/backend/bundle-update-helper.js +0 -113
  222. package/backend/chat-runtime.js +0 -28
  223. package/backend/claude-settings.js +0 -121
  224. package/backend/cli-agents.js +0 -486
  225. package/backend/codex-context-window.js +0 -189
  226. package/backend/codex-models.js +0 -226
  227. package/backend/codex-rollout-follower.js +0 -326
  228. package/backend/codex-session-archive.js +0 -65
  229. package/backend/codex-session-history.js +0 -647
  230. package/backend/codex-transcript-sanitizer.js +0 -115
  231. package/backend/codex-transcript.js +0 -2564
  232. package/backend/command-runner-child.js +0 -67
  233. package/backend/config-manager.js +0 -1133
  234. package/backend/control-api.js +0 -455
  235. package/backend/executable-discovery.js +0 -216
  236. package/backend/farming-agent-bootstrap.js +0 -49
  237. package/backend/farming-cli.js +0 -457
  238. package/backend/farming-net-pass.js +0 -285
  239. package/backend/farming-net-registry.js +0 -112
  240. package/backend/farming-net-server.js +0 -298
  241. package/backend/farming-session-store.js +0 -677
  242. package/backend/git-worktree-info.js +0 -181
  243. package/backend/haiku-token.js +0 -772
  244. package/backend/index-html.js +0 -62
  245. package/backend/input-parts.js +0 -54
  246. package/backend/input-routing.js +0 -24
  247. package/backend/json-cli-runtime.js +0 -275
  248. package/backend/main-agent-skills.js +0 -305
  249. package/backend/main-page-session.js +0 -122
  250. package/backend/native-pty-controller-generation.js +0 -106
  251. package/backend/native-pty-host-identity.js +0 -86
  252. package/backend/native-pty-host-path.js +0 -42
  253. package/backend/native-session-engine.js +0 -268
  254. package/backend/network.js +0 -23
  255. package/backend/npm-update-helper.js +0 -374
  256. package/backend/packaged-node-pty.js +0 -99
  257. package/backend/preview-session-manager.js +0 -68
  258. package/backend/provider-adapters.js +0 -399
  259. package/backend/provider-session-id.js +0 -47
  260. package/backend/provider-session-service.js +0 -345
  261. package/backend/qr-share-tickets.js +0 -100
  262. package/backend/review-diff-router.js +0 -180
  263. package/backend/review-diff-service.js +0 -1270
  264. package/backend/review-session-router.js +0 -74
  265. package/backend/review-session-service.js +0 -446
  266. package/backend/review-session-store.js +0 -151
  267. package/backend/review-state-router.js +0 -116
  268. package/backend/review-state-store.js +0 -286
  269. package/backend/run-history-store.js +0 -67
  270. package/backend/runtime-dependency-manager.js +0 -759
  271. package/backend/runtime-executable-invocation.js +0 -20
  272. package/backend/runtime-observation.js +0 -81
  273. package/backend/server-process-identity.js +0 -47
  274. package/backend/server.js +0 -3267
  275. package/backend/session-engine-bridge.js +0 -129
  276. package/backend/session-engine-router.js +0 -66
  277. package/backend/session-engine.js +0 -39
  278. package/backend/session-stream-protocol.js +0 -185
  279. package/backend/shell-busy-integration.js +0 -472
  280. package/backend/slash-command-discovery.js +0 -433
  281. package/backend/storage-layout.js +0 -190
  282. package/backend/system-monitor.js +0 -77
  283. package/backend/terminal-attach-checkpoint.js +0 -74
  284. package/backend/terminal-exit-quiescence.js +0 -39
  285. package/backend/terminal-runtime-cleanup.js +0 -80
  286. package/backend/terminal-screen-worker.js +0 -337
  287. package/backend/terminal-state-serialization.js +0 -127
  288. package/backend/theme-manager.js +0 -163
  289. package/backend/update-service.js +0 -1545
  290. package/backend/usage-forecast.js +0 -86
  291. package/backend/usage-history-scanner.ts +0 -2718
  292. package/backend/usage-history-smoke.js +0 -64
  293. package/backend/usage-history-worker.js +0 -34
  294. package/backend/workspace-directory.js +0 -232
  295. package/backend/workspace-discovery.js +0 -311
  296. package/backend/workspace-root-registry.js +0 -166
  297. package/dist/assets/App-BKNUILuL.css +0 -1
  298. package/dist/assets/App-Ex2oVVXO.js +0 -693
  299. package/dist/assets/FileEditorPane-CNtuGjQ3.js +0 -2
  300. package/dist/assets/IconGlyphs-BClgag6E.js +0 -1
  301. package/dist/assets/ProjectFilesSection-Cf2BEcAN.js +0 -12
  302. package/dist/assets/ReviewPage-BRuxFaH5.js +0 -3
  303. package/dist/assets/code-dark-BEZTQwYZ.css +0 -1
  304. package/dist/assets/file-icons-BOlcJ0ZF.js +0 -1
  305. package/dist/assets/main-DK9Sy7-c.css +0 -1
  306. package/dist/assets/review-BcnwQtJv.css +0 -1
  307. package/dist/assets/workspace-editor-model-CSGCl21x.js +0 -1
  308. package/dist/assets/workspace-editor-monaco-CJNwbpCy.js +0 -4
  309. package/dist/assets/workspace-editor-monaco-CO9w8YV0.js +0 -1
  310. package/dist/assets/workspace-view-state-BjKPYp0E.js +0 -7
  311. package/extensions/browser/backend/agent-browser-runtime.js +0 -1041
  312. package/extensions/browser/backend/agent-capability.js +0 -55
  313. package/extensions/browser/backend/browser-mcp-server.js +0 -621
  314. package/extensions/browser/backend/browser-resource-manager.js +0 -1309
  315. package/extensions/browser/backend/browser-resource-store.js +0 -190
  316. package/extensions/browser/backend/browser-router.js +0 -133
  317. package/extensions/browser/backend/executable-discovery.js +0 -224
  318. package/extensions/browser/backend/farming-browser-client.js +0 -83
  319. package/extensions/browser/backend/index.js +0 -7
  320. package/extensions/browser/frontend/BrowserSidebarPortals.tsx +0 -360
  321. package/extensions/browser/frontend/BrowserViewer.tsx +0 -500
  322. package/extensions/browser/frontend/browser-resource-state.ts +0 -60
  323. package/extensions/browser/frontend/browser.css +0 -567
  324. package/extensions/browser/frontend/types.ts +0 -31
  325. package/extensions/browser/frontend/useBrowserResources.ts +0 -158
  326. package/frontend/vendor/ghostty-web/index.d.ts +0 -1842
  327. package/shared/backend-connection-status.d.ts +0 -37
  328. package/shared/browser-protocol.d.ts +0 -5
  329. /package/dist/assets/{api-w2x5QfxB.js → api-ByCV9MEr.js} +0 -0
  330. /package/dist/assets/{core-vPkV8P_m.js → core-Czwdx12k.js} +0 -0
  331. /package/dist/assets/{fsharp-DNZNZyEE.js → fsharp-BjPpkoJe.js} +0 -0
  332. /package/dist/assets/{go-_kPJjNc_.js → go-BkIDmSUP.js} +0 -0
  333. /package/dist/assets/{graphql-4HCNVt5g.js → graphql-CCJTpqi1.js} +0 -0
  334. /package/dist/assets/{hcl-C87ymY0o.js → hcl-s4z8lUFg.js} +0 -0
  335. /package/dist/assets/{ini-BYrrGNTc.js → ini-CyUW1I7Z.js} +0 -0
  336. /package/dist/assets/{java-B211rJbk.js → java-CFCcGRiM.js} +0 -0
  337. /package/dist/assets/{julia-DVPsRtBm.js → julia-DQyH_EYb.js} +0 -0
  338. /package/dist/assets/{kotlin-BYyNerjp.js → kotlin-B8hA5O51.js} +0 -0
  339. /package/dist/assets/{less-EC9UblGE.js → less-DaVdaas0.js} +0 -0
  340. /package/dist/assets/{lexon-B1yuUdqW.js → lexon-DLBhPd3y.js} +0 -0
  341. /package/dist/assets/{lua-Bo6GFzxT.js → lua-gB1c_cif.js} +0 -0
  342. /package/dist/assets/{m3-C-Y9cBVI.js → m3-C2T3z3gB.js} +0 -0
  343. /package/dist/assets/{markdown-BHu-wLbe.js → markdown-CKq-Euj1.js} +0 -0
  344. /package/dist/assets/{mips-Dkds26rX.js → mips-Bcs5qIDX.js} +0 -0
  345. /package/dist/assets/{msdax-PU4g-8_g.js → msdax-CBP48FHF.js} +0 -0
  346. /package/dist/assets/{mysql-fPpuGpS7.js → mysql-c7tiPcFj.js} +0 -0
  347. /package/dist/assets/{objective-c-Wy1e5JUf.js → objective-c-D4BZkeEV.js} +0 -0
  348. /package/dist/assets/{pascal-BIXwvrqU.js → pascal-CJDZg0MN.js} +0 -0
  349. /package/dist/assets/{pascaligo-DwR0AtL_.js → pascaligo-Bygi8Ynl.js} +0 -0
  350. /package/dist/assets/{perl-CGHAl8my.js → perl-aS8bkf7E.js} +0 -0
  351. /package/dist/assets/{pgsql-B91M73E2.js → pgsql-CzNAYFYl.js} +0 -0
  352. /package/dist/assets/{php-C70ttrCx.js → php-DOtoEFTT.js} +0 -0
  353. /package/dist/assets/{pla-BNrXaRh0.js → pla-DugRnao1.js} +0 -0
  354. /package/dist/assets/{postiats-Dv2IAZR9.js → postiats-DsXwusKh.js} +0 -0
  355. /package/dist/assets/{powerquery-CkY5Wq7J.js → powerquery-DL3o72oD.js} +0 -0
  356. /package/dist/assets/{powershell-uGIYLU3C.js → powershell-C1qHekys.js} +0 -0
  357. /package/dist/assets/{protobuf-CavfmJu-.js → protobuf-DHgsc-cH.js} +0 -0
  358. /package/dist/assets/{pug-Drqnyitx.js → pug-FZXlE_Iu.js} +0 -0
  359. /package/dist/assets/{qrcode-7uGsTEmi.js → qrcode-DJDTdjL7.js} +0 -0
  360. /package/dist/assets/{qsharp-C7yF-Dti.js → qsharp-bLyhI3DT.js} +0 -0
  361. /package/dist/assets/{r-HXLGP0_-.js → r-DjFGXbAa.js} +0 -0
  362. /package/dist/assets/{redis-C4y6mf2p.js → redis-DSoZ_V6u.js} +0 -0
  363. /package/dist/assets/{redshift-DdQrFPrv.js → redshift-CzkdCsrg.js} +0 -0
  364. /package/dist/assets/{restructuredtext-CBrf2PNj.js → restructuredtext-B_XPrGCQ.js} +0 -0
  365. /package/dist/assets/{ruby-CVtMoX2B.js → ruby-Cry2RneJ.js} +0 -0
  366. /package/dist/assets/{rust-Ckq4sbMP.js → rust-CWzdbFq1.js} +0 -0
  367. /package/dist/assets/{sb-er66OpE3.js → sb-DmofU59h.js} +0 -0
  368. /package/dist/assets/{scala-BdWZz-hH.js → scala-BUC2l-vN.js} +0 -0
  369. /package/dist/assets/{scheme-kTV_s2kP.js → scheme-CNIB_72f.js} +0 -0
  370. /package/dist/assets/{scss-Bymy2VJQ.js → scss-DcL4-NbX.js} +0 -0
  371. /package/dist/assets/{shell-bwEP1LQ1.js → shell-CgAGvSSA.js} +0 -0
  372. /package/dist/assets/{solidity-DCddeBgL.js → solidity-DSkt6O_P.js} +0 -0
  373. /package/dist/assets/{sophia-BMN3AQig.js → sophia--5ytcjDN.js} +0 -0
  374. /package/dist/assets/{sparql-CSXOLjzi.js → sparql-C1Srr7cD.js} +0 -0
  375. /package/dist/assets/{sql-COg8ewmK.js → sql-2k_O5fj7.js} +0 -0
  376. /package/dist/assets/{st-CIaZtBS_.js → st-DCCCPqfz.js} +0 -0
  377. /package/dist/assets/{swift-DXiOhUHu.js → swift-Dd8mAfOt.js} +0 -0
  378. /package/dist/assets/{systemverilog-BTDE6Dr2.js → systemverilog-B0-aZYXu.js} +0 -0
  379. /package/dist/assets/{tcl-B0zy9NvV.js → tcl-CZAZwPVX.js} +0 -0
  380. /package/dist/assets/{twig-D594l4Z1.js → twig-D-Ag0tdS.js} +0 -0
  381. /package/dist/assets/{typespec-XKVjaPqo.js → typespec-B7kTFp0Z.js} +0 -0
  382. /package/dist/assets/{useWorkspaceMenuKeyboard-Bpy_s69Z.js → useWorkspaceMenuKeyboard-uYZpDxhU.js} +0 -0
  383. /package/dist/assets/{vb-B2wYoKRV.js → vb-20w1JPum.js} +0 -0
  384. /package/dist/assets/{wgsl-D0Yf2LbK.js → wgsl-CLJfqFt0.js} +0 -0
  385. /package/dist/assets/{workspace-working-copy-C3FSR3N6.js → workspace-working-copy-Cfz07cOd.js} +0 -0
@@ -0,0 +1,697 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FileEditorPane-BX-Wjg9U.js","assets/chunk-DECur_0Z.js","assets/FileEditorMarkdownPreview-V06QHlAg.js","assets/preload-helper-mJowh_hw.js","assets/core-Czwdx12k.js","assets/file-icons-BpeqWkIB.js","assets/jsx-runtime-BthL93pI.js","assets/workspace-working-copy-Cfz07cOd.js","assets/workspace-editor-model-DND_Y-Bj.js","assets/FileEditorMarkdownPreview-DRDNQ8mX.css","assets/workspace-editor-monaco-BPWhgcIB.js","assets/editor.api2-BFLAr0YF.js","assets/linkComputer-CbGyI_qx.js","assets/editor-CtbFZlk0.css","assets/workers-D0nOyJzf.js","assets/monaco.contribution-B43jsUs1.js","assets/IconGlyphs-YhV7tqd4.js","assets/useWorkspaceMenuKeyboard-uYZpDxhU.js","assets/workspace-editor-monaco-N641qPjX.js","assets/html2canvas-DsczWxBa.js","assets/ProjectFilesSection-BDT2_r0o.js","assets/react-dom-gtU6X-Hj.js","assets/workspace-view-state-k1bTlJ_Z.js","assets/CodeSelect-Ci8sKZPU.js","assets/CodeSelect-T2eNzrOc.css"])))=>i.map(i=>d[i]);
2
+ import{r as e,t}from"./chunk-DECur_0Z.js";import{i as n,n as r,r as i,t as a}from"./jsx-runtime-BthL93pI.js";import{t as o}from"./react-dom-gtU6X-Hj.js";import{t as s}from"./preload-helper-mJowh_hw.js";import{t as c}from"./linkComputer-CbGyI_qx.js";import{C as l,D as u,E as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,l as C,m as w,n as T,o as E,p as D,s as O,u as k,v as A,w as j,x as M,y as N}from"./workspace-view-state-k1bTlJ_Z.js";import{A as P,B as F,C as ee,D as I,E as L,H as te,J as R,L as ne,M as re,P as z,R as ie,St as ae,T as B,U as oe,V,W as se,Y as ce,_ as le,_t as ue,bt as de,f as fe,h as pe,k as me,n as he,nt as ge,q as H,rt as _e,tt as ve,vt as ye,x as be,xt as xe,yt as Se,z as U}from"./file-icons-BpeqWkIB.js";import{A as Ce,B as we,C as Te,F as Ee,G as De,H as Oe,I as ke,J as Ae,K as je,L as Me,M as Ne,N as Pe,O as Fe,P as Ie,R as Le,S as Re,T as ze,U as Be,V as Ve,W as He,X as Ue,Y as We,_ as Ge,a as Ke,b as qe,c as Je,d as Ye,f as Xe,g as Ze,h as Qe,i as $e,j as et,k as tt,l as nt,m as W,n as rt,o as it,p as at,q as ot,r as st,s as ct,t as lt,u as ut,v as dt,w as ft,x as pt,y as mt,z as ht}from"./IconGlyphs-YhV7tqd4.js";import{t as gt}from"./CodeSelect-Ci8sKZPU.js";import{a as _t,c as vt,d as yt,f as bt,h as xt,i as St,l as Ct,m as wt,n as Tt,o as Et,p as Dt,r as Ot,s as kt,u as At}from"./FileEditorMarkdownPreview-V06QHlAg.js";import{B as jt,F as Mt,R as Nt,a as Pt,o as Ft,s as It,z as Lt}from"./workspace-editor-model-DND_Y-Bj.js";import{c as Rt,o as zt}from"./api-ByCV9MEr.js";var G=e(n()),Bt=null;function Vt(e){Bt=e}function Ht(e){return Bt?.(e)===!0}var Ut=new Map,Wt=new Map,Gt=new Set([`terminalInputReceived`,`terminalBusy`,`shellCwd`,`shellLastExitCode`,`shellLastEvent`,`shellCommand`,`shellLastCommand`,`shellCommandStartedAt`,`shellLastCommandStartedAt`,`shellLastCommandFinishedAt`,`shellLastCommandDurationMs`,`terminalStatus`,`runtimeObservation`,`codexTerminalProfile`]),Kt=new Set([`terminalStatus`,`runtimeObservation`,`codexTerminalProfile`]);function qt(e){return{lastActivity:e.lastActivity,activityLevel:e.activityLevel,attentionScore:e.attentionScore,isZombie:e.isZombie,usageRate:e.usageRate,previewText:e.previewText,previewCols:e.previewCols,previewRows:e.previewRows,previewSnapshot:e.previewSnapshot,terminalStatus:e.terminalStatus,runtimeObservation:e.runtimeObservation,codexTerminalProfile:e.codexTerminalProfile,terminalInputReceived:e.terminalInputReceived,terminalBusy:e.terminalBusy,shellCommand:e.shellCommand,shellLastCommand:e.shellLastCommand,shellCommandStartedAt:e.shellCommandStartedAt,shellLastCommandStartedAt:e.shellLastCommandStartedAt,shellLastCommandFinishedAt:e.shellLastCommandFinishedAt,shellLastCommandDurationMs:e.shellLastCommandDurationMs}}function Jt(e,t){let n=Wt.get(e);n?.all.forEach(e=>e()),t&&n?.runtime.forEach(e=>e())}function Yt(e,t){let n=JSON.stringify(t),r=Ut.get(e);(r?.signature??(r?JSON.stringify(r.value):``))!==n&&(Ut.set(e,{value:t,signature:n}),Jt(e,!0))}function Xt(e,t){let n=Ut.get(e);if(!n)return;let r=Object.entries(t).filter(([e,t])=>{let r=e,i=n.value[r];return Object.is(i,t)?!1:Kt.has(r)&&i&&t?JSON.stringify(i)!==JSON.stringify(t):!0}).map(([e])=>e);r.length!==0&&(Ut.set(e,{value:{...n.value,...t},signature:null}),Jt(e,r.some(e=>Gt.has(e))))}function Zt(e){let{agentId:t,...n}=e;Xt(t,n)}function Qt(e){Xt(e.agentId,{previewText:e.previewText,previewCols:e.cols,previewRows:e.rows,previewSnapshot:e.previewSnapshot??null,...e.terminalStatus?{terminalStatus:e.terminalStatus}:{},...e.runtimeObservation?{runtimeObservation:e.runtimeObservation}:{},...e.codexTerminalProfile?{codexTerminalProfile:e.codexTerminalProfile}:{}})}function $t(e){let t=new Set;e.forEach(e=>{t.add(e.id),Yt(e.id,qt(e))});for(let e of Ut.keys())t.has(e)||(Ut.delete(e),Jt(e,!0))}function en(){let e=[...Ut.keys()];Ut.clear(),e.forEach(e=>Jt(e,!0))}function tn(e,t,n){let r=Wt.get(e)??{all:new Set,runtime:new Set};return r[t].add(n),Wt.set(e,r),()=>{r[t].delete(n),r.all.size===0&&r.runtime.size===0&&Wt.delete(e)}}function nn(e){return Ut.get(e)?.value??null}function rn(e){let t=nn(e.id);return t?{...e,...t}:e}function an(e,t){let n=e?.id??``,r=(0,G.useCallback)(e=>n?tn(n,t,e):()=>{},[n,t]),i=(0,G.useCallback)(()=>n?nn(n):null,[n]),a=(0,G.useSyncExternalStore)(r,i,i);return(0,G.useMemo)(()=>a&&e?{...e,...a}:e??null,[e,a])}function on(e){return an(e,`all`)}function sn(e){return an(e,`runtime`)}typeof window<`u`&&window.__FARMING_E2E__&&(window.__farmingAgentActivityTest={update(e,t){Xt(e,t)}});var cn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MIN_PROTOCOL_VERSION=e.PROTOCOL_VERSION=void 0,e.sanitizeAgentUpdatePatch=d,e.validateClientMessage=f,e.validateServerMessage=p,e.protocolCompatible=m,e.PROTOCOL_VERSION=4,e.MIN_PROTOCOL_VERSION=4;var t=new Set([`protocol-hello`,`business-health-probe`,`start-agent`,`input`,`composer-input`,`acp-permission-response`,`interrupt-agent`,`focus-agent`,`resize-agent`,`clear-terminal`,`watch-workspace-files`,`unwatch-workspace-files`,`kill-agent`,`restart-main-agent`]),n=new Set([`protocol-hello`,`protocol-error`,`business-health-result`,`command-ack`,`state`,`error`,`composer-input-result`,`agent-started`,`session-output`,`session-preview`,`system-stats`,`agent-activity`,`agent-update`,`acp-session-revision`,`agent-read`,`workspace-file-watch`,`workspace-file-event`,`browser-resource-snapshot`,`browser-resource-updated`,`browser-resource-deleted`,`computer-resource-snapshot`,`computer-resource-updated`,`computer-resource-deleted`]);function r(e){return!!(e&&typeof e==`object`&&!Array.isArray(e))}function i(e,t,n=!1){return n&&e[t]===void 0?!0:typeof e[t]==`string`}function a(e,t){return typeof e[t]==`number`&&Number.isFinite(e[t])}function o(e,t){return Number.isInteger(e[t])&&typeof e[t]==`number`&&e[t]>=0}function s(e){return r(e)&&o(e,`collectionRevision`)&&Array.isArray(e.resources)&&e.resources.every(c)}function c(e){return r(e)&&typeof e.id==`string`&&e.id.length>0&&o(e,`revision`)&&o(e,`collectionRevision`)}function l(e){return r(e)&&typeof e.id==`string`&&e.id.length>0&&o(e,`collectionRevision`)}var u={terminalInputReceived:e=>typeof e==`boolean`,terminalBusy:e=>e===null||typeof e==`boolean`,shellCwd:e=>typeof e==`string`,shellLastExitCode:e=>e===null||typeof e==`number`&&Number.isFinite(e),shellLastEvent:e=>typeof e==`string`,shellCommand:e=>typeof e==`string`,shellLastCommand:e=>typeof e==`string`,shellCommandStartedAt:e=>e===null||typeof e==`number`&&Number.isFinite(e),shellLastCommandStartedAt:e=>e===null||typeof e==`number`&&Number.isFinite(e),shellLastCommandFinishedAt:e=>e===null||typeof e==`number`&&Number.isFinite(e),shellLastCommandDurationMs:e=>e===null||typeof e==`number`&&Number.isFinite(e),terminalStatus:e=>e===null||r(e),runtimeObservation:r};function d(e){if(!r(e))return null;let t=Object.entries(e);return t.length===0||t.some(([e,t])=>{let n=u[e];return!n||!n(t)})?null:Object.fromEntries(t)}function f(e){if(!r(e)||typeof e.type!=`string`)return{ok:!1,error:`message must be an object with a type`};if(!t.has(e.type))return{ok:!1,error:`unsupported client message: ${e.type}`};let n=!0;switch(e.type){case`protocol-hello`:n=Number.isInteger(e.protocolVersion);break;case`business-health-probe`:n=i(e,`requestId`);break;case`start-agent`:n=i(e,`command`);break;case`input`:n=i(e,`agentId`,!0)&&(typeof e.input==`string`||Array.isArray(e.inputParts));break;case`composer-input`:n=i(e,`message`)&&i(e,`agentId`,!0)&&i(e,`requestId`,!0)&&(!Object.prototype.hasOwnProperty.call(e,`delivery`)||e.delivery===`prompt`||e.delivery===`steer`);break;case`acp-permission-response`:n=i(e,`agentId`)&&i(e,`requestId`)&&i(e,`optionId`)&&(!Object.prototype.hasOwnProperty.call(e,`cancelled`)||typeof e.cancelled==`boolean`);break;case`focus-agent`:n=e.agentId===null||i(e,`agentId`);break;case`resize-agent`:n=i(e,`agentId`)&&a(e,`cols`)&&a(e,`rows`);break;case`unwatch-workspace-files`:n=i(e,`agentId`,!0);break;case`restart-main-agent`:n=i(e,`command`);break;default:n=i(e,`agentId`);break}return n?{ok:!0,value:e}:{ok:!1,error:`invalid ${e.type} message`}}function p(e){if(!r(e)||typeof e.type!=`string`)return{ok:!1,error:`message must be an object with a type`};if(!n.has(e.type))return{ok:!1,error:`unsupported server message: ${e.type}`};let t=!0;switch(e.type){case`protocol-hello`:t=Number.isInteger(e.protocolVersion)&&Number.isInteger(e.minProtocolVersion);break;case`business-health-result`:t=i(e,`requestId`)&&i(e,`serverEpoch`)&&Number.isInteger(e.protocolVersion)&&(e.status===`ready`||e.status===`recovering`||e.status===`failed`||e.status===`stopping`)&&Number.isInteger(e.agentCount)&&typeof e.agentCount==`number`&&e.agentCount>=0&&(e.mainAgentId===null||i(e,`mainAgentId`));break;case`protocol-error`:case`error`:t=i(e,`message`);break;case`command-ack`:t=i(e,`requestId`)&&i(e,`command`);break;case`state`:t=r(e.state)&&Array.isArray(e.state.agents);break;case`composer-input-result`:t=i(e,`requestId`)&&i(e,`agentId`)&&typeof e.accepted==`boolean`&&i(e,`message`,!0)&&(!Object.prototype.hasOwnProperty.call(e,`uncertain`)||typeof e.uncertain==`boolean`);break;case`agent-started`:t=i(e,`agentId`);break;case`session-output`:t=r(e.stream)&&i(e.stream,`agentId`);break;case`session-preview`:t=r(e.preview)&&i(e.preview,`agentId`);break;case`system-stats`:t=r(e.stats);break;case`agent-activity`:t=r(e.activity)&&i(e.activity,`agentId`);break;case`agent-update`:t=r(e.update)&&i(e.update,`agentId`)&&d(e.update.patch)!==null;break;case`acp-session-revision`:t=r(e.session)&&i(e.session,`agentId`)&&Number.isInteger(e.session.revision)&&typeof e.session.revision==`number`&&e.session.revision>=0&&i(e.session,`updatedAt`);break;case`agent-read`:t=r(e.read)&&i(e.read,`agentId`);break;case`workspace-file-watch`:t=i(e,`agentId`)&&typeof e.watching==`boolean`;break;case`workspace-file-event`:t=r(e.event)&&i(e.event,`agentId`);break;case`browser-resource-snapshot`:t=s(e.snapshot);break;case`browser-resource-updated`:t=c(e.resource);break;case`browser-resource-deleted`:t=l(e.deletion);break;case`computer-resource-snapshot`:t=s(e.snapshot);break;case`computer-resource-updated`:t=c(e.resource);break;case`computer-resource-deleted`:t=l(e.deletion);break}return t?{ok:!0,value:e}:{ok:!1,error:`invalid ${e.type} message`}}function m(t){return Number.isInteger(t)&&typeof t==`number`&&t>=e.MIN_PROTOCOL_VERSION&&t<=e.PROTOCOL_VERSION}}))();function ln(){return{collectionRevision:0,snapshotRevision:0,deletedRevisions:new Map,resources:[]}}function un(e,t,n){if((e.get(t)??-1)>=n)return e;let r=new Map(e);return r.set(t,n),r}function dn(e,t){let n=e.findIndex(e=>e.id===t.id);if(n<0)return[...e,t].sort((e,t)=>e.createdAt-t.createdAt);let r=e[n];if(!r||t.revision<r.revision||t.revision===r.revision&&t.collectionRevision<=r.collectionRevision)return e;let i=[...e];return i[n]=t,i}function fn(e,t){if(t.collectionRevision<=e.snapshotRevision||(e.deletedRevisions.get(t.id)??-1)>=t.collectionRevision)return e;let n=dn(e.resources,t);if(n===e.resources)return e;let r=Math.max(e.collectionRevision,t.collectionRevision);return{...e,collectionRevision:r,resources:n}}function pn(e,t){return t.collectionRevision<e.collectionRevision?e:{collectionRevision:t.collectionRevision,snapshotRevision:t.collectionRevision,deletedRevisions:new Map,resources:[...t.resources].sort((e,t)=>e.createdAt-t.createdAt)}}function mn(e,t){if(t.collectionRevision<=e.snapshotRevision)return e;let n=e.resources.find(e=>e.id===t.id),r=n&&n.collectionRevision>t.collectionRevision?e.resources:e.resources.filter(e=>e.id!==t.id),i=Math.max(e.collectionRevision,t.collectionRevision),a=un(e.deletedRevisions,t.id,t.collectionRevision);return r===e.resources&&i===e.collectionRevision&&a===e.deletedRevisions?e:{...e,collectionRevision:i,deletedRevisions:a,resources:r}}function hn(){return{collectionRevision:0,snapshotRevision:0,deletedRevisions:new Map,resources:[]}}function gn(e,t,n){if((e.get(t)??-1)>=n)return e;let r=new Map(e);return r.set(t,n),r}function _n(e,t){if(t.collectionRevision<=e.snapshotRevision||(e.deletedRevisions.get(t.id)??-1)>=t.collectionRevision)return e;let n=e.resources.find(e=>e.id===t.id);if(n&&(t.revision<n.revision||t.revision===n.revision&&t.collectionRevision<=n.collectionRevision))return e;let r=n?e.resources.map(e=>e.id===t.id?t:e):[...e.resources,t].sort((e,t)=>e.createdAt-t.createdAt);return{...e,collectionRevision:Math.max(e.collectionRevision,t.collectionRevision),resources:r}}function vn(e,t){return t.collectionRevision<e.collectionRevision?e:{collectionRevision:t.collectionRevision,snapshotRevision:t.collectionRevision,deletedRevisions:new Map,resources:[...t.resources].sort((e,t)=>e.createdAt-t.createdAt)}}function yn(e,t){if(t.collectionRevision<=e.snapshotRevision)return e;let n=e.resources.find(e=>e.id===t.id),r=n&&n.collectionRevision>t.collectionRevision?e.resources:e.resources.filter(e=>e.id!==t.id),i=Math.max(e.collectionRevision,t.collectionRevision),a=gn(e.deletedRevisions,t.id,t.collectionRevision);return r===e.resources&&i===e.collectionRevision&&a===e.deletedRevisions?e:{...e,collectionRevision:i,deletedRevisions:a,resources:r}}var bn=1e3,xn=1e4,Sn=8e3,Cn=2e3;function wn(e,t){return t?!1:/(^|[/\\])\.farming[/\\]?$/.test(e||``)}function Tn(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function En(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Dn(){let e=(0,G.useRef)(null),t=(0,G.useRef)(new Map),n=(0,G.useRef)(0),r=(0,G.useRef)(new Map),a=(0,G.useRef)(new Map),o=(0,G.useRef)(new Map),s=(0,G.useRef)(new Set),[c,u]=(0,G.useState)({agents:[],taskHistory:[],mainPageSessionKeys:[],mainAgentId:null,connected:!1,error:null,errorKind:`error`,errorId:0,lastStartedAgentId:null,projectWorkspaces:null,pinnedProjectWorkspaces:null,browserResources:null,computerResources:null}),d=(0,G.useCallback)(e=>{u(t=>{let n=t.browserResources;if(!n)return t;let r=fn(n,e);return r===n?t:{...t,browserResources:r}})},[]),f=(0,G.useCallback)(e=>{u(t=>{let n=t.browserResources;if(!n)return t;let r=mn(n,e);return r===n?t:{...t,browserResources:r}})},[]),p=(0,G.useCallback)(e=>{u(t=>{let n=t.computerResources;if(!n)return t;let r=_n(n,e);return r===n?t:{...t,computerResources:r}})},[]),m=(0,G.useCallback)(e=>{u(t=>{let n=t.computerResources;if(!n)return t;let r=yn(n,e);return r===n?t:{...t,computerResources:r}})},[]),h=(0,G.useRef)(new Map),g=(0,G.useRef)(new Map),_=(0,G.useCallback)(t=>{let n=e.current;return n&&n.readyState===WebSocket.OPEN?(n.send(JSON.stringify(t)),!0):(u(e=>({...e,error:`Farming backend is not connected`,errorKind:`recoverable`,errorId:e.errorId+1})),!1)},[]),v=(0,G.useCallback)((e,t,n=``,i=!0,c=`error`)=>{let l=r.current.get(e),d=o.current.get(e);if(!l&&t&&d){s.current.add(e);return}i&&(d&&a.current.get(d)===e&&a.current.delete(d),o.current.delete(e),s.current.delete(e)),l&&(r.current.delete(e),window.clearTimeout(l.timeout),!t&&n&&u(e=>({...e,error:n,errorKind:c,errorId:e.errorId+1})),l.resolve(t))},[]),y=(0,G.useCallback)((e,t,n,r)=>{let i={type:`start-agent`,requestId:globalThis.crypto?.randomUUID?.(),command:e,workspace:t,asMain:n};return r?.task!==void 0&&(i.task=r.task),r?.workflowTemplate!==void 0&&(i.workflowTemplate=r.workflowTemplate),r?.customTitle!==void 0&&(i.customTitle=r.customTitle),r?.projectWorkspace!==void 0&&(i.projectWorkspace=r.projectWorkspace),r?.codexApprovalMode!==void 0&&(i.codexApprovalMode=r.codexApprovalMode),r?.agentRuntimeMode!==void 0&&(i.agentRuntimeMode=r.agentRuntimeMode),r?.dangerouslySkipPermissions!==void 0&&(i.dangerouslySkipPermissions=r.dangerouslySkipPermissions),r?.providerHomeId!==void 0&&(i.providerHomeId=r.providerHomeId),r?.additionalDirectories!==void 0&&(i.additionalDirectories=r.additionalDirectories),r?.mcpServers!==void 0&&(i.mcpServers=r.mcpServers),_(i)},[_]),b=(0,G.useCallback)((e,t,i=[],c)=>{let l=String(c?.requestId||``).trim(),u=l?`request:${l}`:JSON.stringify({agentId:t||``,message:e,delivery:c?.delivery||``,attachments:i.map(e=>({kind:e.kind,path:e.path,type:e.type}))}),d=l||a.current.get(u)||globalThis.crypto?.randomUUID?.()||`composer-${Date.now().toString(36)}-${++n.current}`;if(a.current.set(u,d),o.current.set(d,u),s.current.delete(d))return a.current.delete(u),o.current.delete(d),Promise.resolve(!0);let f=r.current.get(d);if(f)return f.promise;let p={type:`composer-input`,requestId:d,message:e,agentId:t,...c?.delivery?{delivery:c.delivery}:{},...i.length>0?{attachments:i}:{}},m=()=>{},h=new Promise(e=>{m=e}),g=window.setTimeout(()=>{v(d,!1,`Chat submission has an uncertain outcome. Your draft is still available; retrying will reconcile the same request.`,!1)},15e3);return r.current.set(d,{resolve:m,timeout:g,promise:h}),_(p)||v(d,!1,`Farming backend is not connected. Your draft is still available.`,!0,`recoverable`),h},[_,v]),x=(0,G.useCallback)(e=>_({type:`focus-agent`,agentId:e}),[_]),S=(0,G.useCallback)((e,t={})=>_({type:`kill-agent`,agentId:e,...t.acknowledgeUnprovenAcpExit===!0?{acknowledgeUnprovenAcpExit:!0}:{}}),[_]),C=(0,G.useCallback)(e=>_({type:`interrupt-agent`,agentId:e}),[_]),w=(0,G.useCallback)(e=>_({type:`restart-main-agent`,command:e}),[_]),T=(0,G.useCallback)((e,t)=>(h.current.set(e,t),()=>{h.current.delete(e)}),[]),E=(0,G.useCallback)((e,t)=>{let n=g.current.get(e);return n||(n=new Set,g.current.set(e,n),_({type:`watch-workspace-files`,agentId:e})),n.add(t),()=>{let n=g.current.get(e);n&&(n.delete(t),n.size===0&&(g.current.delete(e),_({type:`unwatch-workspace-files`,agentId:e})))}},[_]);return(0,G.useEffect)(()=>(Vt(e=>_(e)),()=>Vt(null)),[_]),(0,G.useEffect)(()=>{M(),en();let n,a=!1,o=null,s=0,c=null,_=null,y=``,b=0;function x(e=Date.now()){e-s<bn||(s=e,l({lastMessageAt:e}))}function S(){c&&clearTimeout(c),_&&clearTimeout(_),c=null,_=null}function C(e,t){c&&clearTimeout(c),c=setTimeout(()=>{c=null,w(e)},t)}function w(t){if(a||e.current!==t||t.readyState!==WebSocket.OPEN||document.visibilityState===`hidden`)return;_&&clearTimeout(_);let n=globalThis.crypto?.randomUUID?.()||`health-${Date.now().toString(36)}-${++b}`;y=n,t.send(JSON.stringify({type:`business-health-probe`,requestId:n})),_=setTimeout(()=>{y!==n||e.current!==t||(y=``,_=null,l({businessStatus:`unresponsive`,businessCheckedAt:Date.now()}),C(t,Cn))},Sn)}function T(){S(),y=``,l({businessStatus:`checking`,businessCheckedAt:null,businessServerEpoch:``})}function E(){let e=o;T(),document.visibilityState!==`hidden`&&e?.readyState===WebSocket.OPEN&&w(e)}document.addEventListener(`visibilitychange`,E);function D(){if(a)return;let c=i(),b=new URLSearchParams(location.search).get(`token`),S=document.cookie.match(/(?:^|;\s*)farming_token=([^;]+)/),E=b||S?.[1]||``;E&&(c+=`?token=${E}`);let O=new WebSocket(c);o=O,e.current=O,O.onopen=()=>{a||e.current!==O||(s=Date.now(),u(e=>({...e,connected:!0,error:null})),l({connected:!0,everConnected:!0,lastMessageAt:s,disconnectedAt:null,businessStatus:`checking`,businessCheckedAt:null,businessServerEpoch:``}),O.send(JSON.stringify({type:`protocol-hello`,protocolVersion:cn.PROTOCOL_VERSION})),w(O),window.dispatchEvent(new Event(`farming:backend-connected`)),g.current.forEach((e,t)=>{e.size>0&&O.send(JSON.stringify({type:`watch-workspace-files`,agentId:t}))}))},O.onmessage=n=>{if(!(a||e.current!==O)){x();try{let e=JSON.parse(n.data),r=(0,cn.validateServerMessage)(e);if(!r.ok)throw Error(r.error);let i=e;switch(i.type){case`protocol-hello`:(0,cn.protocolCompatible)(i.protocolVersion)||O.close(4002,`Unsupported Farming protocol version ${i.protocolVersion}`);break;case`protocol-error`:u(e=>({...e,error:i.message,errorKind:`error`,errorId:e.errorId+1}));break;case`business-health-result`:if(i.requestId!==y)break;y=``,_&&clearTimeout(_),_=null,l({businessStatus:i.status,businessCheckedAt:Date.now(),businessServerEpoch:i.serverEpoch}),C(O,i.status===`ready`?xn:Cn);break;case`command-ack`:break;case`state`:i.state.systemStats!==void 0&&j(i.state.systemStats??null),$t(i.state.agents),u(e=>{let n=new Map(e.agents.map(e=>[e.id,e])),r=e.agents.length!==i.state.agents.length,a=new Map,o=i.state.agents.map((o,s)=>{let c=n.get(o.id),l=JSON.stringify(o);a.set(o.id,l);let u=o.isMain||o.id===i.state.mainAgentId||wn(o.cwd,o.parentAgentId);if(c&&c.id===e.agents[s]?.id&&c.isMain===u&&t.current.get(o.id)===l)return c;let d={...o,isMain:u};return r=!0,c?.previewSnapshot?{...d,previewSnapshot:c.previewSnapshot}:d});t.current=a;let s=r?o:e.agents,c=i.state.taskHistory??e.taskHistory,l=Array.isArray(i.state.mainPageSessionKeys)?i.state.mainPageSessionKeys:e.mainPageSessionKeys,u=Array.isArray(i.state.projectWorkspaces)?i.state.projectWorkspaces:e.projectWorkspaces,d=Array.isArray(i.state.pinnedProjectWorkspaces)?i.state.pinnedProjectWorkspaces:e.pinnedProjectWorkspaces,f=c!==e.taskHistory&&!En(c,e.taskHistory),p=l!==e.mainPageSessionKeys&&!Tn(l,e.mainPageSessionKeys),m=u!==e.projectWorkspaces&&(e.projectWorkspaces===null||!Tn(u??[],e.projectWorkspaces)),h=d!==e.pinnedProjectWorkspaces&&(e.pinnedProjectWorkspaces===null||!Tn(d??[],e.pinnedProjectWorkspaces));return s===e.agents&&!f&&!p&&!m&&!h&&i.state.mainAgentId===e.mainAgentId?e:{...e,agents:s,taskHistory:f?c:e.taskHistory,mainPageSessionKeys:p?l:e.mainPageSessionKeys,projectWorkspaces:m?u:e.projectWorkspaces,pinnedProjectWorkspaces:h?d:e.pinnedProjectWorkspaces,mainAgentId:i.state.mainAgentId}});break;case`error`:u(e=>({...e,error:i.message,errorKind:`error`,errorId:e.errorId+1}));break;case`composer-input-result`:v(i.requestId,i.accepted,i.message||``,i.uncertain!==!0);break;case`agent-started`:u(e=>({...e,lastStartedAgentId:i.agentId}));break;case`agent-update`:Xt(i.update.agentId,i.update.patch);break;case`acp-session-revision`:u(e=>{let t=!1,n=e.agents.map(e=>e.id!==i.session.agentId||e.runtimeBinding?.kind!==`acp`||i.session.revision<=e.runtimeBinding.sessionRevision?e:(t=!0,{...e,runtimeBinding:{...e.runtimeBinding,sessionRevision:i.session.revision,sessionUpdatedAt:i.session.updatedAt}}));return t?{...e,agents:n}:e});break;case`session-preview`:Qt(i.preview);break;case`session-output`:{let e=h.current.get(i.stream.agentId);e&&i.stream.replace===!0&&e(i.stream.data,!0,i.stream.outputSeq,i.stream.runtimeEpoch,i.stream.stateRevision,i.stream.cols,i.stream.rows),e&&Array.isArray(i.stream.chunks)?i.stream.chunks.forEach(t=>{e(t.data,!1,t.outputSeq,t.runtimeEpoch,t.stateRevision,t.cols,t.rows,t.kind)}):e&&i.stream.replace!==!0&&e(i.stream.data,i.stream.replace,i.stream.outputSeq,i.stream.runtimeEpoch,i.stream.stateRevision,i.stream.cols,i.stream.rows,i.stream.kind);break}case`agent-activity`:Zt(i.activity);break;case`agent-read`:u(e=>({...e,agents:e.agents.map(e=>e.id===i.read.agentId?{...e,...i.read,id:e.id}:e)}));break;case`workspace-file-watch`:break;case`workspace-file-event`:g.current.get(i.event.agentId)?.forEach(e=>e(i.event));break;case`browser-resource-snapshot`:u(e=>{let t=e.browserResources??ln(),n=pn(t,i.snapshot);return n===t&&e.browserResources!==null?e:{...e,browserResources:n}});break;case`browser-resource-updated`:d(i.resource);break;case`browser-resource-deleted`:f(i.deletion);break;case`computer-resource-snapshot`:u(e=>{let t=e.computerResources??hn(),n=vn(t,i.snapshot);return n===t&&e.computerResources!==null?e:{...e,computerResources:n}});break;case`computer-resource-updated`:p(i.resource);break;case`computer-resource-deleted`:m(i.deletion);break;case`system-stats`:j(i.stats??null);break}}catch(e){let t=e instanceof Error?e.message:`Invalid Farming backend message`;u(e=>({...e,error:t,errorKind:`error`,errorId:e.errorId+1}))}}},O.onclose=t=>{a||e.current!==O||(T(),e.current=null,r.current.forEach(({resolve:e,timeout:t})=>{window.clearTimeout(t),e(!1)}),r.current.clear(),u(e=>({...e,connected:!1,error:t.code===4001?`Farming token expired or is invalid`:e.error,errorKind:t.code===4001?`error`:e.errorKind,errorId:t.code===4001?e.errorId+1:e.errorId,browserResources:null,computerResources:null})),l({connected:!1,disconnectedAt:Date.now()}),window.dispatchEvent(new CustomEvent(`farming:backend-disconnected`,{detail:{code:t.code,reason:t.reason}})),n=setTimeout(D,1e3))},O.onerror=()=>{O.close()}}return D(),()=>{a=!0,clearTimeout(n),document.removeEventListener(`visibilitychange`,E),S(),e.current===o&&(e.current=null),l({connected:!1,disconnectedAt:Date.now()}),o?.close()}},[]),{...c,startAgent:y,sendComposerInput:b,focusAgent:x,killAgent:S,interruptAgent:C,restartMainAgent:w,onSessionOutput:T,watchWorkspaceFiles:E,mergeBrowserResource:d,deleteBrowserResource:f,mergeComputerResource:p,deleteComputerResource:m}}var On=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BACKEND_INITIAL_CONNECT_GRACE_MS=void 0,e.classifyBackendConnection=t,e.reducePageVisibilitySnapshot=n,e.BACKEND_INITIAL_CONNECT_GRACE_MS=8e3;function t({connected:t,lastMessageAt:n,disconnectedAt:r,visibleSince:i,now:a,businessStatus:o}){return t?o===`recovering`?`business-recovering`:o===`failed`||o===`stopping`||o===`unresponsive`?`business-unavailable`:null:Math.max(0,a-Math.max(typeof r==`number`&&Number.isFinite(r)?r:n,i))>=e.BACKEND_INITIAL_CONNECT_GRACE_MS?`lost`:`connecting`}function n(e,{eventType:t,documentVisible:n,changedAt:r}){let i=t===`pagehide`?!1:n;return i===e.visible?!i||t!==`pageshow`?e:{visible:!0,visibleSince:r}:{visible:i,visibleSince:i?r:e.visibleSince}}}))();function kn(){return typeof document>`u`?!0:document.visibilityState!==`hidden`}function An(){let[e,t]=(0,G.useState)(()=>{let e=kn();return{visible:e,visibleSince:e?Date.now():0}});return(0,G.useEffect)(()=>{let e=e=>{let n=Date.now();t(t=>(0,On.reducePageVisibilitySnapshot)(t,{eventType:e.type,documentVisible:kn(),changedAt:n}))};return document.addEventListener(`visibilitychange`,e),window.addEventListener(`pagehide`,e),window.addEventListener(`pageshow`,e),()=>{document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`pagehide`,e),window.removeEventListener(`pageshow`,e)}},[]),e}function jn(){return An().visible}function Mn(e,t){let n=(0,G.useMemo)(()=>e.find(e=>e.id===t)??null,[e,t]),r=(0,G.useMemo)(()=>e.filter(e=>e.id!==t&&!e.isMain&&!e.archived&&e.status!==`dead`&&e.status!==`stopped`),[e,t]);return{mainAgent:n,otherAgents:r,activeCount:(0,G.useMemo)(()=>e.filter(e=>e.status===`running`).length,[e]),keyMap:(0,G.useMemo)(()=>{let e=new Map;return r.forEach((t,n)=>{n<9&&e.set(String(n+1),t.id)}),e},[r])}}function Nn(e){return e instanceof HTMLElement?!!e.closest(`.terminal-session-host, .code-terminal-container`):!1}function Pn(e){return e instanceof HTMLElement?e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable||!!e.closest(`.code-file-editor, .monaco-editor`):!1}function Fn(e){return e instanceof HTMLElement?!!e.closest(`[role="dialog"]`):!1}function In(e){return e instanceof HTMLElement?!!e.closest(`[role="menu"]`):!1}function Ln(e){return Fn(e)||In(e)}function Rn(){return!!document.querySelector(`[role="dialog"], [role="menu"], .code-context-menu, .code-file-context-menu`)}function zn(e,t=!0){(0,G.useEffect)(()=>{if(!t)return;let n=t=>{t.key===`Escape`&&e()};return document.addEventListener(`keydown`,n),()=>document.removeEventListener(`keydown`,n)},[t,e])}function Bn(e,t=!0){(0,G.useEffect)(()=>{if(!t)return;function n(t){let n=t.target,r=Pn(n),i=Nn(n),a=Ln(n)||Rn();for(let n of e){if(a&&!n.allowInOverlay||r&&!n.allowInInput||i&&!n.allowInTerminal)continue;let e=t.key.toLowerCase()===n.key.toLowerCase(),o=n.meta?t.metaKey&&!t.ctrlKey:n.ctrl?t.ctrlKey||t.metaKey:!(t.ctrlKey||t.metaKey),s=n.shift?t.shiftKey:!t.shiftKey,c=!t.altKey;if(e&&o&&s&&c){t.preventDefault(),n.handler(t);return}}}return window.addEventListener(`keydown`,n,!0),()=>window.removeEventListener(`keydown`,n,!0)},[e,t])}var Vn=[`codex`,`claude`,`opencode`,`qoder`,`qwen`,`bash`,`zsh`],Hn=new Set(Vn);function Un(e){let t=Vn.indexOf(e);return t===-1?Vn.length:t}function Wn(e){let t=new Set;return e.filter(e=>e&&Hn.has(e.name)&&e.supported!==!1&&e.interactive!==!1).filter(e=>t.has(e.name)?!1:(t.add(e.name),!0)).sort((e,t)=>{let n=Un(e.name),r=Un(t.name);return n===r?e.name.localeCompare(t.name):n-r})}function Gn(e){let t=typeof e==`string`?e.trim():``;return!t||t===`/`||t===`~`?t:t.replace(/[\\/]+$/,``)}function Kn(e){let t=Gn(e);return t===`~/.farming`||/(^|[/\\])\.farming$/.test(t)}function qn(e){let t=Gn(e);return t===`/tmp`||t.startsWith(`/tmp/`)||t===`/private/tmp`||t.startsWith(`/private/tmp/`)||t===`/var/tmp`||t.startsWith(`/var/tmp/`)||t===`/private/var/tmp`||t.startsWith(`/private/var/tmp/`)||t===`/var/folders`||t.startsWith(`/var/folders/`)||t===`/private/var/folders`||t.startsWith(`/private/var/folders/`)}function Jn(e){let t=Gn(e);return!!t&&!qn(t)&&!Kn(t)}function Yn(e,t=[]){let n=[e,...t].map(Gn).filter(e=>Jn(e)),r=[],i=new Set;return n.forEach(e=>{i.has(e)||(i.add(e),r.push(e))}),r.slice(0,5)}function Xn(e=[],t=[]){let n=[],r=new Set;return[...e,...t].map(Gn).filter(e=>Jn(e)).forEach(e=>{r.has(e)||(r.add(e),n.push(e))}),n.slice(0,5)}function Zn(e){let t=Gn(e);return t?Kn(t)?`~/.farming`:t:``}function Qn(e){let t=Gn(e?.lastMainWorkspace);if(t)return Zn(t);let n=Gn(e?.workspace);return n?Zn(n):`~/.farming`}function $n(e,t,n=`~/.farming`){return Gn(e)||(t?Gn(n)||`~/.farming`:null)}function er(e){let t=Gn(e);if(!t||Kn(t))return`~/.farming`;if(t.startsWith(`/Users/`)){let e=t.split(`/`);if(e.length>3)return`~/${e.slice(3).join(`/`)}`}return t}var K=a();async function tr(e,t){let n=Gn(e)||`~`,i=new URLSearchParams({path:n,limit:`500`}),a=await fetch(r(`/api/workspaces/browse?${i.toString()}`),{cache:`no-store`,signal:t}),o=await a.json().catch(()=>null);if(!a.ok||o?.status!==`ready`||!o.workspace)throw Error(`workspace directory browse failed`);return{workspace:o.workspace,parent:o.parent||null,directories:Array.isArray(o.directories)?o.directories:[],truncated:o.truncated===!0}}function nr({copy:e,parentPath:t,depth:n,selectedPath:r,directoryStates:i,expandedPaths:a,onToggle:o}){let s=i[t];return s?(0,K.jsx)(K.Fragment,{children:s.directories.map(s=>{let c=a.has(s.path),l=i[s.path],u={"--workspace-directory-depth":`${n*16}px`},d={"--workspace-directory-depth":`${(n+1)*16}px`};return(0,K.jsxs)(`div`,{className:`workspace-directory-browser-node`,role:`none`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`workspace-directory-browser-row ${r===s.path?`selected`:``}`,"data-testid":`workspace-directory-browser-row`,"data-directory-path":s.path,role:`treeitem`,"aria-expanded":c,"aria-selected":r===s.path,"aria-level":n+1,title:s.path,style:u,onClick:()=>o(s,t),children:[c?(0,K.jsx)(Ge,{}):(0,K.jsx)(mt,{}),(0,K.jsx)(et,{}),(0,K.jsx)(`span`,{children:s.name})]}),c&&(0,K.jsx)(`div`,{className:`workspace-directory-browser-group`,role:`group`,children:l?.loading?(0,K.jsx)(`div`,{className:`workspace-directory-browser-inline-status`,style:d,children:e.loading}):l?.error?(0,K.jsx)(`div`,{className:`workspace-directory-browser-inline-status error`,role:`alert`,style:d,children:e.workspaceDirectoryBrowserFailed}):l?(0,K.jsxs)(K.Fragment,{children:[l.directories.length===0?(0,K.jsx)(`div`,{className:`workspace-directory-browser-inline-status`,style:d,children:e.workspaceDirectoryBrowserEmpty}):(0,K.jsx)(nr,{copy:e,parentPath:s.path,depth:n+1,selectedPath:r,directoryStates:i,expandedPaths:a,onToggle:o}),l.truncated&&(0,K.jsx)(`div`,{className:`workspace-directory-browser-inline-status truncated`,style:d,children:e.workspaceDirectoryBrowserTruncated})]}):null})]},s.path)})}):null}function rr({copy:e,initialPath:t,onCancel:n,onSelect:r}){let[i,a]=(0,G.useState)(Gn(t)||`~`),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(``),[u,d]=(0,G.useState)(null),[f,p]=(0,G.useState)({}),[m,h]=(0,G.useState)(()=>new Set),[g,_]=(0,G.useState)(!1),[v,y]=(0,G.useState)(!1),b=(0,G.useRef)(0),x=(0,G.useRef)(null),S=(0,G.useRef)(new Map),C=(0,G.useRef)(null),w=(0,G.useCallback)(async e=>{let t=Gn(e)||`~`,n=b.current+=1;x.current?.abort();let r=new AbortController;x.current=r,S.current.forEach(e=>e.abort()),S.current.clear(),_(!0),y(!1);try{let e=await tr(t,r.signal);if(n!==b.current)return;s(e.workspace),l(e.workspace),d(e.parent),p({[e.workspace]:{parent:e.parent,directories:e.directories,loading:!1,error:!1,truncated:e.truncated}}),h(new Set),a(e.workspace)}catch{n===b.current&&!r.signal.aborted&&y(!0)}finally{n===b.current&&_(!1)}},[]),T=(0,G.useCallback)((e,t)=>{if(l(e.path),d(t),a(e.path),y(!1),m.has(e.path)){h(t=>{let n=new Set(t);return n.delete(e.path),n});return}h(t=>new Set(t).add(e.path));let n=f[e.path];if(n&&!n.error)return;S.current.get(e.path)?.abort();let r=new AbortController;S.current.set(e.path,r),p(r=>({...r,[e.path]:{parent:t,directories:n?.directories??[],loading:!0,error:!1,truncated:!1}})),tr(e.path,r.signal).then(t=>{r.signal.aborted||p(n=>({...n,[e.path]:{parent:t.parent,directories:t.directories,loading:!1,error:!1,truncated:t.truncated}}))}).catch(()=>{r.signal.aborted||p(n=>({...n,[e.path]:{parent:t,directories:[],loading:!1,error:!0,truncated:!1}}))}).finally(()=>{S.current.get(e.path)===r&&S.current.delete(e.path)})},[f,m]);(0,G.useEffect)(()=>{w(t);let e=requestAnimationFrame(()=>{C.current?.focus(),C.current?.select()});return()=>{cancelAnimationFrame(e),b.current+=1,x.current?.abort(),S.current.forEach(e=>e.abort()),S.current.clear()}},[w,t]);let E=e=>{e.preventDefault(),w(i)},D=Gn(i)===c,O=f[o];return(0,K.jsxs)(`div`,{className:`workspace-directory-browser`,"data-testid":`workspace-directory-browser`,children:[(0,K.jsxs)(`div`,{className:`workspace-directory-browser-heading`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h4`,{children:e.chooseWorkspaceDirectory}),(0,K.jsx)(`p`,{children:e.workspaceDirectoryBrowserHostHint})]}),(0,K.jsx)(`button`,{type:`button`,className:`workspace-directory-browser-close`,"aria-label":e.back,onClick:n,children:(0,K.jsx)(nt,{})})]}),(0,K.jsxs)(`form`,{className:`workspace-directory-browser-location`,onSubmit:E,children:[(0,K.jsx)(`button`,{type:`button`,className:`workspace-directory-browser-parent`,"data-testid":`workspace-directory-browser-parent`,"aria-label":e.workspaceDirectoryBrowserParent,title:e.workspaceDirectoryBrowserParent,disabled:!u||g,onClick:()=>{if(!u)return;if(c===o){w(u);return}let e=u,t=f[e];l(e),d(t?.parent??null),a(e),y(!1)},children:(0,K.jsx)(Ye,{})}),(0,K.jsx)(`input`,{ref:C,"data-testid":`workspace-directory-browser-path`,value:i,"aria-label":e.workspace,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,onChange:e=>{a(e.target.value),y(!1)}}),(0,K.jsx)(`button`,{type:`submit`,className:`workspace-directory-browser-go`,"aria-label":e.workspaceDirectoryBrowserGo,title:e.workspaceDirectoryBrowserGo,disabled:g,children:(0,K.jsx)(ut,{})})]}),(0,K.jsx)(`div`,{className:`workspace-directory-browser-list`,"data-testid":`workspace-directory-browser-list`,"aria-busy":g,role:`tree`,"aria-label":e.chooseWorkspaceDirectory,children:g?(0,K.jsx)(`div`,{className:`workspace-directory-browser-status`,children:e.loading}):v?(0,K.jsx)(`div`,{className:`workspace-directory-browser-status error`,role:`alert`,children:e.workspaceDirectoryBrowserFailed}):!O||O.directories.length===0?(0,K.jsx)(`div`,{className:`workspace-directory-browser-status`,children:e.workspaceDirectoryBrowserEmpty}):(0,K.jsx)(nr,{copy:e,parentPath:o,depth:0,selectedPath:c,directoryStates:f,expandedPaths:m,onToggle:T})}),O?.truncated&&(0,K.jsx)(`p`,{className:`workspace-directory-browser-truncated`,role:`status`,children:e.workspaceDirectoryBrowserTruncated}),(0,K.jsxs)(`div`,{className:`workspace-directory-browser-actions`,children:[(0,K.jsx)(`span`,{title:c,children:er(c)}),(0,K.jsx)(`button`,{type:`button`,className:`secondary`,"data-testid":`workspace-directory-browser-cancel`,onClick:n,children:e.back}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`workspace-directory-browser-select`,disabled:!c||!D||g||v,onClick:()=>r(c),children:e.workspaceDirectoryBrowserSelect})]})]})}var ir=[{id:``,label:`(none)`,prefix:``},{id:`ralph`,label:`Ralph loop`,prefix:`[Workflow: ralph loop]
3
+ `},{id:`developer`,label:`Developer loop`,prefix:`[Workflow: developer loop]
4
+ `},{id:`reviewer`,label:`Reviewer loop`,prefix:`[Workflow: reviewer loop]
5
+ `}];function ar(e,t){let n=ir.find(e=>e.id===t)?.prefix??``,r=e.trim();return{task:n?r?`${n}${r}`:n.trimEnd():r,workflowTemplate:t||``}}async function or(e,t=!1){let n=await fetch(r(`/api/workspaces/prepare`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspace:e,create:t})}),i=await n.json().catch(()=>null);if(i?.status&&typeof i.workspace==`string`)return i;throw Error(i?.message||`Failed to prepare workspace (${n.status})`)}function sr(e){return e===`opencode`?`opencode`:e===`qoder`?`qoder`:e===`qwen`?`qwen`:e===`bash`?`bash`:e===`zsh`?`zsh`:e===`claude`?`claude`:`codex`}function cr(e){return e===`codex`||e===`claude`||e===`qoder`||e===`qwen`}function lr(e){let t=Date.parse(e.updatedAt||``);return Number.isFinite(t)?t:0}function ur(e){return cr(e.provider)&&e.archived!==!0&&Array.isArray(e.capabilities)&&e.capabilities.includes(`resume`)&&(Kn(e.cwd)||Kn(e.workspace))}function dr(e,t){let n=e.providerName||b(e.provider),r=N(lr(e));return[e.title||t.sessionFallbackTitle(n),n,r].filter(Boolean).join(` · `)}function fr({open:e,mustStartMain:t,initialWorkspace:n,initialCommand:i,initialCustomTitle:a,showWorkflowTaskFields:o=!0,copy:s,onStart:c,onClose:l}){let[u,d]=(0,G.useState)(`agent-list`),[f,p]=(0,G.useState)([]),[m,h]=(0,G.useState)(!1),[g,_]=(0,G.useState)(!1),[v,y]=(0,G.useState)(null),[S,C]=(0,G.useState)(``),[w,T]=(0,G.useState)(``),[E,D]=(0,G.useState)(``),[O,k]=(0,G.useState)([]),[A,j]=(0,G.useState)({}),[M,N]=(0,G.useState)(`default`),[P,F]=(0,G.useState)(`terminal`),[ee,I]=(0,G.useState)(!1),[L,te]=(0,G.useState)([]),[R,ne]=(0,G.useState)([]),[re,z]=(0,G.useState)(-1),[ie,B]=(0,G.useState)(null),[oe,V]=(0,G.useState)(!0),[se,ce]=(0,G.useState)(`~/.farming`),[le,ue]=(0,G.useState)(`codex`),[de,fe]=(0,G.useState)(!1),[pe,me]=(0,G.useState)(-1),[he,ge]=(0,G.useState)(!1),[H,_e]=(0,G.useState)(null),[ve,ye]=(0,G.useState)(!1),[be,xe]=(0,G.useState)(``),Se=(0,G.useRef)(null),U=(0,G.useRef)(null),Ce=(0,G.useRef)(null),we=(0,G.useRef)(null),Te=(0,G.useRef)(null),Ee=(0,G.useRef)(null),De=(0,G.useRef)(!1),Oe=(0,G.useRef)(!1),ke=(0,G.useRef)(null),Ae=(0,G.useMemo)(()=>t?[]:Xn(O,L),[O,L,t]),je=(0,G.useMemo)(()=>ie&&f.some(e=>e.name===ie.provider)?ie:null,[f,ie]),Me=oe&&je?je.provider:le;(0,G.useLayoutEffect)(()=>{if(!e)return;let a=!1;return d(`agent-list`),y(null),C(t?``:Gn(n||``)),T(``),D(``),De.current=!1,Oe.current=!1,ge(!1),_e(null),ye(!1),xe(``),ke.current!==null&&(window.clearTimeout(ke.current),ke.current=null),te([]),ne([]),z(-1),B(null),V(!0),ue(`codex`),j({}),N(`default`),F(`terminal`),I(!1),me(-1),h(!1),_(!1),fe(!1),fetch(r(`/api/executables`),{cache:`no-store`}).then(e=>{if(!e.ok)throw Error(`Failed to load executables: ${e.status}`);return e.json()}).then(e=>{if(a)return;let n=Wn(Array.isArray(e)?e:e.agents??[]).map(e=>({...e,description:e.description??``,category:e.category??`coding`})),r=!t&&i?n.find(e=>e.name===i):null;p(n),_(!1);let o=t?null:r;o&&(y(o),d(`workspace`),ae()||setTimeout(()=>U.current?.focus(),50))}).catch(()=>{a||(p([]),_(!0))}).finally(()=>{a||h(!0)}),fetch(r(`/api/settings`)).then(e=>e.json()).then(e=>{if(a)return;let n=e.settings??{},r=Qn(n),i=Yn(null,n.workspaceHistory??[]);ce(r),ue(sr(n.defaultLaunchAgent)),k(i),j(n.agentHomes??{}),t&&!De.current&&C(r),fe(!0)}).catch(()=>{a||(k([]),ce(`~/.farming`),t&&!De.current&&C(`~/.farming`),fe(!0))}),()=>{a=!0}},[e,t,n,i]),(0,G.useEffect)(()=>{if(!e||!t)return;let n=!0;return B(null),V(!0),fetch(r(`/api/agent-sessions?limit=100&fresh=1`),{cache:`no-store`}).then(e=>e.json()).then(e=>{n&&B((e.sessions??[]).filter(ur).sort((e,t)=>lr(t)-lr(e))[0]??null)}).catch(()=>{n&&B(null)}),()=>{n=!1}},[e,t]),(0,G.useEffect)(()=>()=>{ke.current!==null&&(window.clearTimeout(ke.current),ke.current=null)},[]),(0,G.useLayoutEffect)(()=>{!H||H.kind===`creating`||Ee.current?.focus()},[H]),(0,G.useLayoutEffect)(()=>{if(!e||u!==`agent-list`||!m||g||t&&!de)return;let n=Se.current;if(!n)return;let r=document.activeElement;if(r instanceof HTMLElement&&n.contains(r)&&(r.matches(`.agent-item`)||r.matches(`input, textarea, select`)))return;let i=()=>{let e=Array.from(n.querySelectorAll(`.agent-item:not(:disabled)`));(e.find(e=>e.dataset.testid===`agent-option-${Me}`)??e[0])?.focus()};i();let a=requestAnimationFrame(i),o=window.setTimeout(i,0);return()=>{cancelAnimationFrame(a),window.clearTimeout(o)}},[g,m,Me,t,e,de,u]);let Ne=(0,G.useCallback)(()=>Oe.current?!1:(Oe.current=!0,ge(!0),ke.current=window.setTimeout(()=>{Oe.current=!1,ge(!1),ke.current=null},1200),!0),[]);(0,G.useEffect)(()=>{if(!e||t||!v)return;let n=!0;te([]);let i=new URLSearchParams({limit:`12`,agent:v.name});return fetch(r(`/api/workspaces/discovered?${i.toString()}`)).then(e=>e.json()).then(e=>{n&&te((e.workspaces??[]).map(e=>Gn(e.path)).filter(e=>Jn(e)))}).catch(()=>{n&&te([])}),()=>{n=!1}},[e,t,v]),(0,G.useEffect)(()=>{if(!e||u!==`workspace`){ne([]),z(-1);return}let t=S.trim();if(!t||!t.includes(`/`)&&!t.startsWith(`~`)){ne([]),z(-1);return}let n=new AbortController,i=window.setTimeout(()=>{let e=new URLSearchParams({path:t,limit:`50`});fetch(r(`/api/workspaces/complete?${e.toString()}`),{signal:n.signal}).then(e=>e.json()).then(e=>{let t=(e.suggestions??[]).filter(e=>typeof e.path==`string`&&e.path);ne(t),z(e=>t.length===0?-1:Math.min(e,t.length-1))}).catch(e=>{e?.name!==`AbortError`&&(ne([]),z(-1))})},120);return()=>{window.clearTimeout(i),n.abort()}},[e,u,S]),(0,G.useEffect)(()=>{if(re<0)return;let e=Te.current;e&&e.querySelector(`[aria-selected="true"]`)?.scrollIntoView({block:`nearest`})},[re,R.length]);let Pe=(0,G.useCallback)(e=>{if(!(!t||!oe||!je)&&e.name===je.provider)return{resumeSession:{provider:je.provider,id:je.id,providerHomeId:je.providerHomeId},providerHomeId:je.providerHomeId}},[t,je,oe]),Ie=(0,G.useCallback)(e=>{if(t){if(!de||!Ne())return;let t=$n(S,!0,se);t&&c(e.command||e.name,t,{...Pe(e)||{},providerHomeId:M});return}y(e);let r=A[e.name];N((Array.isArray(r)?r:[]).slice().sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1))[0]?.id||`default`),I(!1),De.current=!1,C(Gn(n||``)),te([]),me(-1),d(`workspace`),ae()||setTimeout(()=>U.current?.focus(),50)},[n,Ne,se,t,c,Pe,de,S]),Re=(0,G.useCallback)(async e=>{let t=Yn(e,O),n=await fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspaceHistory:t})}).catch(()=>{});n?.ok&&k(Yn(null,((await n.json().catch(()=>null))?.settings??{}).workspaceHistory??[]))},[O]),ze=(0,G.useCallback)(async e=>{if(!v)return;!t&&Jn(e)&&await Re(e);let n=Pe(v);if(n){c(v.command||v.name,e,{...n,providerHomeId:M});return}if(t){c(v.command||v.name,e,{providerHomeId:M});return}let r=o?ar(w,E):{task:``,workflowTemplate:``};c(v.command||v.name,e,{task:r.task,workflowTemplate:r.workflowTemplate,...a?{customTitle:a}:{},providerHomeId:M,...[`codex`,`claude`,`opencode`,`qoder`,`qwen`].includes(v.name)?{agentRuntimeMode:P}:{}})},[v,t,Re,Pe,c,M,o,w,E,a,P]),Be=(0,G.useCallback)(async()=>{if(!v||!Ne())return;let e=$n(Gn(U.current?.value??S),t,se);if(e){if(t){await ze(e);return}try{let t=await or(e);if(t.status===`ready`){await ze(t.workspace);return}_e({kind:t.status===`missing`?`confirm`:`error`,workspace:t.workspace||e,code:t.code})}catch{_e({kind:`error`,workspace:e})}}},[v,S,t,se,Ne,ze]),Ve=(0,G.useCallback)(async()=>{if(!H||H.kind===`creating`)return;let e=H.workspace;_e({kind:`creating`,workspace:e});try{let t=await or(e,!0);if(t.status===`created`||t.status===`ready`){await ze(t.workspace);return}_e({kind:`error`,workspace:t.workspace||e,code:t.code})}catch{_e({kind:`error`,workspace:e})}},[ze,H]),He=(0,G.useCallback)(e=>{let t=Gn(e);me(Ae.findIndex(e=>e===t))},[Ae]),Ue=(0,G.useCallback)(e=>{if(!Ae.length)return;let t=(e%Ae.length+Ae.length)%Ae.length,n=Ae[t]??``;De.current=!0,C(n),me(t),requestAnimationFrame(()=>{if(U.current){if(ae()){U.current.blur();return}U.current.focus(),U.current.setSelectionRange(n.length,n.length)}})},[Ae]),We=(0,G.useMemo)(()=>{if(!v)return[];let e=A[v.name],t=(Array.isArray(e)?e:[]).slice().sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1));return t.length>0?t:v.name===`codex`?[{id:`default`,path:`~/.codex`}]:v.name===`claude`?[{id:`default`,path:`~/.claude`}]:v.name===`opencode`?[{id:`default`,path:`~/.opencode`}]:v.name===`qoder`?[{id:`default`,path:`~/.qoder`}]:v.name===`qwen`?[{id:`default`,path:`~/.qwen`}]:[{id:`default`,path:`~/.${v.name}`}]},[A,v]),Ke=(0,G.useMemo)(()=>We.find(e=>e.id===M)??We[0],[We,M]);(0,G.useEffect)(()=>{let e=We||[];if(e.length===0){N(`default`);return}e.some(e=>e.id===M)||N(e[0]?.id||`default`)},[We,M]),(0,G.useEffect)(()=>{if(!ee)return;let e=e=>{Ce.current?.contains(e.target)||I(!1)};return window.addEventListener(`mousedown`,e),()=>{window.removeEventListener(`mousedown`,e)}},[ee]);let qe=(0,G.useCallback)(e=>{N(e),I(!1),requestAnimationFrame(()=>we.current?.focus())},[]),Xe=(0,G.useCallback)(e=>{let t=R[e];return t?(De.current=!0,C(t.path),me(-1),z(-1),requestAnimationFrame(()=>{if(U.current){if(ae()){U.current.blur();return}U.current.focus(),U.current.setSelectionRange(t.path.length,t.path.length)}}),!0):!1},[R]),Qe=(0,G.useCallback)(e=>R.length===0?!1:(z(((re===-1?e>0?0:R.length-1:re+e)%R.length+R.length)%R.length),me(-1),!0),[re,R]),$e=(0,G.useCallback)(e=>Ae.length?(Ue(pe===-1?e>0?0:Ae.length-1:pe+e),!0):!1,[Ae,pe,Ue]),tt=(0,G.useCallback)(e=>{let t=Se.current;if(!t)return;let n=Array.from(t.querySelectorAll(`.agent-item:not(:disabled)`)).filter(e=>e.offsetParent!==null);if(n.length===0)return;let r=n.indexOf(document.activeElement),i=n.length-1,a=r;if(e.key===`ArrowDown`)a=r===-1?0:(r+1)%n.length;else if(e.key===`ArrowUp`)a=r===-1?i:(r-1+n.length)%n.length;else if(e.key===`Home`)a=0;else if(e.key===`End`)a=i;else return;e.preventDefault(),n[a]?.focus()},[]),nt=(0,G.useCallback)(e=>{if(u===`agent-list`&&(tt(e),e.defaultPrevented)||e.key!==`Tab`)return;let t=Se.current;if(!t)return;let n=Array.from(t.querySelectorAll(`button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [href], [tabindex]:not([tabindex="-1"])`)).filter(e=>e.offsetParent!==null);if(n.length===0){e.preventDefault();return}let r=n[0],i=n[n.length-1],a=document.activeElement;if(e.shiftKey){(a===r||!t.contains(a))&&(e.preventDefault(),i?.focus());return}(a===i||!t.contains(a))&&(e.preventDefault(),r?.focus())},[tt,u]);if(Bn([...f.slice(0,10).map((e,t)=>({key:String(t<9?t+1:0),allowInOverlay:!0,handler:()=>Ie(e)})),{key:`Escape`,allowInOverlay:!0,handler:()=>!t&&l()}],e&&u===`agent-list`),Bn([{key:`Escape`,allowInOverlay:!0,handler:()=>{if(ve){ye(!1),requestAnimationFrame(()=>U.current?.focus());return}if(H){if(H.kind===`creating`)return;_e(null),requestAnimationFrame(()=>U.current?.focus());return}if(ee){I(!1),requestAnimationFrame(()=>we.current?.focus());return}d(`agent-list`)}}],e&&u===`workspace`),!e)return null;let W=f.filter(e=>e.category===`coding`),rt=f.filter(e=>e.category!==`coding`);return(0,K.jsx)(`div`,{className:`dialog-overlay`,"data-testid":`dialog-overlay`,children:(0,K.jsxs)(`div`,{className:`input-dialog fx-crt-panel`,"data-testid":`input-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`input-dialog-title`,ref:Se,onKeyDown:nt,children:[(0,K.jsxs)(`div`,{className:`dialog-header fx-crt-panel-compact`,children:[(0,K.jsx)(`div`,{className:`dialog-header-copy`,children:(0,K.jsx)(`h3`,{id:`input-dialog-title`,className:`dialog-header-title`,children:t?s.startMainAgent:s.startNewAgent})}),!t&&(0,K.jsx)(`button`,{type:`button`,className:`close-btn`,"data-testid":`input-dialog-close`,"aria-label":s.close,onClick:l,children:(0,K.jsx)(pt,{})})]}),ve&&(0,K.jsx)(rr,{copy:s,initialPath:be||S||Ae[0]||`~`,onCancel:()=>{ye(!1),requestAnimationFrame(()=>U.current?.focus())},onSelect:e=>{De.current=!0,C(e),me(-1),z(-1),ye(!1),requestAnimationFrame(()=>{U.current?.focus(),U.current?.setSelectionRange(e.length,e.length)})}}),!ve&&u===`agent-list`&&(0,K.jsxs)(`div`,{className:`agent-list`,children:[!m&&(0,K.jsxs)(`div`,{className:`agent-list-status fx-crt-panel`,"data-testid":`agent-list-status`,children:[(0,K.jsx)(`span`,{className:`agent-list-spinner`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:s.loadingAgents})]}),m&&g&&(0,K.jsx)(`div`,{className:`agent-list-status fx-crt-panel`,"data-testid":`agent-list-status`,children:s.agentListUnavailable}),m&&!g&&W.length===0&&rt.length===0&&(0,K.jsx)(`div`,{className:`agent-list-status fx-crt-panel`,"data-testid":`agent-list-status`,children:s.noSupportedAgentsFound}),t&&je&&(0,K.jsxs)(`label`,{className:`main-agent-resume-option fx-crt-panel`,"data-testid":`main-agent-resume-option`,children:[(0,K.jsx)(`input`,{type:`checkbox`,"data-testid":`main-agent-resume-toggle`,checked:oe,onChange:e=>V(e.target.checked)}),(0,K.jsxs)(`span`,{className:`main-agent-resume-copy`,children:[(0,K.jsx)(`span`,{className:`main-agent-resume-title`,children:s.resumePreviousMainAgent}),(0,K.jsx)(`span`,{className:`main-agent-resume-detail`,children:dr(je,s)})]})]}),W.length>0&&(0,K.jsxs)(`div`,{className:`agent-group`,children:[(0,K.jsx)(`div`,{className:`group-label`,children:s.codingAgents}),W.map((e,n)=>(0,K.jsxs)(`button`,{className:`agent-item fx-crt-panel`,"data-testid":`agent-option-${e.name}`,disabled:t&&(he||!de),onClick:()=>Ie(e),children:[(0,K.jsx)(x,{name:e.name}),(0,K.jsx)(`span`,{className:`key-hint-badge`,children:n<9?n+1:0}),(0,K.jsxs)(`span`,{className:`agent-item-copy`,children:[(0,K.jsx)(`span`,{className:`agent-item-name`,children:b(e.name)}),(0,K.jsx)(`span`,{className:`agent-item-desc`,children:e.description})]})]},e.name))]}),rt.length>0&&(0,K.jsxs)(`div`,{className:`agent-group`,children:[(0,K.jsx)(`div`,{className:`group-label`,children:s.otherAgents}),rt.map((e,n)=>{let r=W.length+n;return(0,K.jsxs)(`button`,{className:`agent-item fx-crt-panel`,"data-testid":`agent-option-${e.name}`,disabled:t&&(he||!de),onClick:()=>Ie(e),children:[(0,K.jsx)(x,{name:e.name}),(0,K.jsx)(`span`,{className:`key-hint-badge`,children:r<9?r+1:0}),(0,K.jsxs)(`span`,{className:`agent-item-copy`,children:[(0,K.jsx)(`span`,{className:`agent-item-name`,children:b(e.name)}),(0,K.jsx)(`span`,{className:`agent-item-desc`,children:e.description})]})]},e.name)})]})]}),!ve&&u===`workspace`&&v&&(0,K.jsxs)(`div`,{className:`workspace-input`,"data-testid":`workspace-step`,children:[(We?.length??0)>1&&(0,K.jsxs)(`div`,{className:`workspace-home-field`,ref:Ce,children:[(0,K.jsxs)(`p`,{className:`workspace-field-copy`,children:[b(v.name),` Home`]}),(0,K.jsxs)(`button`,{ref:we,type:`button`,className:`workspace-home-trigger`,"data-testid":`agent-home-select`,"aria-label":`${b(v.name)} home`,"aria-expanded":ee,"aria-controls":`agent-home-options`,onClick:()=>I(e=>!e),onKeyDown:e=>{if(e.key===`Escape`&&ee){e.preventDefault(),e.stopPropagation(),I(!1);return}e.key!==`ArrowDown`&&e.key!==`ArrowUp`||(e.preventDefault(),I(!0),requestAnimationFrame(()=>{let t=e.key===`ArrowDown`?`[data-home-option]:first-child`:`[data-home-option]:last-child`;Ce.current?.querySelector(t)?.focus()}))},children:[(0,K.jsxs)(`span`,{className:`workspace-home-trigger-copy`,children:[(0,K.jsx)(`strong`,{children:Ke?.id||`default`}),(0,K.jsx)(`span`,{children:er(Ke?.path||``)})]}),(0,K.jsx)(Ge,{})]}),ee&&(0,K.jsx)(`div`,{className:`workspace-home-menu`,id:`agent-home-options`,"data-testid":`agent-home-menu`,role:`listbox`,"aria-label":`${b(v.name)} home`,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),I(!1),requestAnimationFrame(()=>we.current?.focus()))},children:We.map(e=>{let t=e.id===M;return(0,K.jsxs)(`button`,{type:`button`,className:`workspace-home-option ${t?`selected`:``}`,"data-testid":`agent-home-option`,"data-home-option":!0,role:`option`,"aria-selected":t,onClick:()=>qe(e.id),children:[(0,K.jsx)(Ze,{className:`workspace-home-option-check`}),(0,K.jsxs)(`span`,{className:`workspace-home-option-copy`,children:[(0,K.jsx)(`strong`,{children:e.id}),(0,K.jsx)(`span`,{children:er(e.path)})]})]},e.id)})})]}),[`codex`,`claude`,`opencode`,`qoder`,`qwen`].includes(v.name)&&(0,K.jsxs)(`div`,{className:`workspace-runtime-field`,"data-testid":`agent-runtime-mode`,children:[(0,K.jsxs)(`p`,{className:`workspace-field-copy`,children:[b(v.name),` runtime`]}),(0,K.jsxs)(`div`,{className:`workspace-runtime-options`,role:`group`,"aria-label":`${b(v.name)} runtime`,children:[(0,K.jsx)(`button`,{type:`button`,className:P===`terminal`?`active`:``,"aria-pressed":P===`terminal`,onClick:()=>F(`terminal`),children:`Terminal`}),(0,K.jsx)(`button`,{type:`button`,className:P===`chat`?`active`:``,"aria-pressed":P===`chat`,onClick:()=>F(`chat`),children:`Chat`})]})]}),(0,K.jsx)(`p`,{className:`workspace-field-copy`,children:s.workspace}),(0,K.jsxs)(`div`,{className:`workspace-path-field`,children:[(0,K.jsx)(`input`,{ref:U,"data-testid":`workspace-input`,type:`text`,value:S,onFocus:()=>He(S),onChange:e=>{let t=e.target.value;De.current=!0,_e(null),C(t),He(t)},onKeyDown:e=>{if(e.key===`ArrowDown`){if(R.length>0&&Qe(1)){e.preventDefault();return}$e(1)&&e.preventDefault();return}if(e.key===`ArrowUp`){if(R.length>0&&Qe(-1)){e.preventDefault();return}$e(-1)&&e.preventDefault();return}if(e.key===`Tab`&&R.length>0){Xe(re===-1?0:re)&&e.preventDefault();return}if(e.key===`Enter`){if(e.preventDefault(),re!==-1&&Xe(re))return;Be()}e.key===`Escape`&&(e.preventDefault(),d(`agent-list`))},placeholder:s.workspacePathPlaceholder,name:`workspace-path`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`go`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,disabled:H!==null}),(0,K.jsx)(`button`,{type:`button`,className:`workspace-directory-picker`,"data-testid":`workspace-directory-picker`,"aria-label":s.chooseWorkspaceDirectory,title:s.chooseWorkspaceDirectory,disabled:H!==null,onClick:()=>{xe(Gn(U.current?.value||S||Ae[0]||`~`)),ye(!0)},children:(0,K.jsx)(et,{})})]}),H?(0,K.jsxs)(`div`,{className:`workspace-directory-prompt ${H.kind===`error`?`error`:``}`,"data-testid":`workspace-directory-prompt`,role:`alertdialog`,"aria-labelledby":`workspace-directory-prompt-title`,"aria-describedby":`workspace-directory-prompt-description`,children:[(0,K.jsx)(`div`,{className:`workspace-directory-prompt-icon`,"aria-hidden":`true`,children:H.kind===`error`?(0,K.jsx)(Fe,{}):(0,K.jsx)(Le,{})}),(0,K.jsxs)(`div`,{className:`workspace-directory-prompt-copy`,children:[(0,K.jsx)(`h4`,{id:`workspace-directory-prompt-title`,children:H.kind===`error`?s.workspaceCreateFailedTitle:s.workspaceMissingTitle}),(0,K.jsx)(`p`,{id:`workspace-directory-prompt-description`,children:H.kind===`error`?H.code===`workspace-create-forbidden`?s.workspaceCreateForbiddenDescription:s.workspaceCreateFailedDescription:s.workspaceMissingDescription}),(0,K.jsx)(`code`,{children:er(H.workspace)})]}),(0,K.jsx)(`div`,{className:`workspace-directory-prompt-actions`,children:H.kind===`error`?(0,K.jsx)(`button`,{ref:Ee,type:`button`,"data-testid":`workspace-directory-back`,onClick:()=>{_e(null),requestAnimationFrame(()=>U.current?.focus())},children:s.returnToWorkspace}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{ref:Ee,type:`button`,"data-testid":`workspace-directory-create`,disabled:H.kind===`creating`,onClick:()=>void Ve(),children:H.kind===`creating`?s.workspaceCreating:s.workspaceCreateAndStart}),(0,K.jsx)(`button`,{type:`button`,className:`secondary`,"data-testid":`workspace-directory-cancel`,disabled:H.kind===`creating`,onClick:()=>{_e(null),requestAnimationFrame(()=>U.current?.focus())},children:s.back})]})})]}):R.length>0&&(0,K.jsx)(`div`,{ref:Te,className:`workspace-path-suggestions fx-crt-panel`,"data-testid":`workspace-path-suggestions`,role:`listbox`,children:R.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`workspace-path-suggestion ${t===re?`active`:``}`,"data-testid":`workspace-path-suggestion`,role:`option`,"aria-selected":t===re,onMouseDown:e=>{e.preventDefault(),Xe(t)},children:[(0,K.jsx)(`span`,{className:`workspace-path-suggestion-name`,children:e.name}),(0,K.jsx)(`span`,{className:`workspace-path-suggestion-path`,children:er(e.path)})]},e.path))}),!t&&o&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`p`,{className:`workspace-field-copy`,children:`Workflow:`}),(0,K.jsx)(gt,{ariaLabel:`Workflow template`,className:`workflow-select`,triggerClassName:`fx-crt-panel`,testId:`workflow-template-select`,value:E,options:ir.map(e=>({value:e.id,label:e.label})),onChange:D}),(0,K.jsx)(`p`,{className:`workspace-field-copy`,children:`Task (optional):`}),(0,K.jsx)(`textarea`,{className:`task-input fx-crt-panel`,"data-testid":`task-input`,value:w,onChange:e=>T(e.target.value),placeholder:`Describe what this agent should focus on`,rows:4,name:`agent-task`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`})]}),!H&&Ae.length>0&&(0,K.jsxs)(`div`,{className:`workspace-history fx-crt-panel`,"data-testid":`workspace-history`,children:[(0,K.jsxs)(`div`,{className:`workspace-history-header`,children:[(0,K.jsx)(`span`,{children:s.recentWorkspacesLower}),(0,K.jsxs)(`span`,{className:`hint`,"aria-hidden":`true`,children:[(0,K.jsx)(Ye,{}),(0,K.jsx)(Je,{})]})]}),(0,K.jsx)(`div`,{className:`workspace-history-list`,children:Ae.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`workspace-history-item ${t===pe?`active`:``}`,"data-testid":`workspace-history-item`,onMouseDown:e=>{e.preventDefault(),Ue(t)},children:[(0,K.jsx)(`span`,{className:`workspace-history-index`,children:t+1}),(0,K.jsx)(`span`,{className:`workspace-history-path`,children:er(e)}),t===0&&e===O[0]&&(0,K.jsx)(`span`,{className:`workspace-history-badge`,children:s.latest})]},e))})]}),!H&&(0,K.jsxs)(`div`,{className:`workspace-actions`,children:[(0,K.jsx)(`button`,{type:`button`,"data-testid":`workspace-start`,"aria-label":s.start,disabled:he,onClick:()=>void Be(),children:s.start}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`workspace-back`,"aria-label":s.back,onClick:()=>d(`agent-list`),children:s.back})]})]})]})})}function pr({copy:e}){let t=p(),n=An(),[r,i]=(0,G.useState)(()=>Date.now());if((0,G.useEffect)(()=>{if(!n.visible||t.connected)return;i(Date.now());let e=window.setInterval(()=>{i(Date.now())},1e3);return()=>window.clearInterval(e)},[t.connected,t.disconnectedAt,n.visible]),!n.visible||!kn())return null;let a=(0,On.classifyBackendConnection)({connected:t.connected,lastMessageAt:t.lastMessageAt,disconnectedAt:t.disconnectedAt,visibleSince:n.visibleSince,now:r,businessStatus:t.businessStatus});if(!a)return null;let o=a===`business-recovering`?e.backendBusinessRecovering:a===`business-unavailable`?e.backendBusinessUnavailable:a===`lost`?e.backendConnectionLost:e.backendConnecting;return(0,K.jsxs)(`div`,{className:`connection-status ${a}`,"data-testid":`connection-status`,role:`status`,"aria-live":`polite`,children:[(0,K.jsx)(`span`,{className:`connection-status-dot`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:o})]})}function mr(e){return e?.runtimeBinding.kind===`acp`}function hr(e){return!!(e&&e.runtimeBinding.kind!==`terminal`)}function gr(e,t){return e===`terminal`?{kind:`terminal`}:e===`acp`?{kind:`acp`,state:`starting`,error:``,stopReason:``,supportsSteer:!1,pendingPermission:null,pendingPermissions:[],pendingElicitation:null,pendingElicitations:[],activeElicitations:[],sessionUpdatedAt:``,sessionRevision:0}:t}var _r={app:0,codeWorkspace:0};function vr(){typeof window>`u`||!window.__FARMING_E2E__||window.__farmingPerformanceTest||(window.__farmingPerformanceTest={reset(){_r.app=0,_r.codeWorkspace=0},snapshot(){return{..._r}}})}function yr(e){typeof window>`u`||!window.__FARMING_E2E__||(vr(),_r[e]+=1)}var br=new Set,xr=5e3,Sr=0;function Cr(){Sr=Math.max(Sr,Date.now()+xr),br.forEach(e=>e())}function wr(){return Date.now()<Sr}function Tr(e){return br.add(e),()=>{br.delete(e)}}var Er=`__farming_project__:`,Dr=new Map;function Or(e){let t=e.trim();return t===`/`?t:t.replace(/[\/]+$/,``)}function kr(e){if(e===`/`)return`wroot_global`;let t=new TextEncoder().encode(e),n=14695981039346656037n;for(let e of t)n^=BigInt(e),n=BigInt.asUintN(64,n*1099511628211n);return`wroot_${n.toString(16).padStart(16,`0`)}`}function Ar(e){let t=Or(e),n=kr(t);return Dr.set(n,t),n}function jr(e){let t=String(e||``);if(t===`wroot_global`)return`/`;let n=Dr.get(t);if(n)return n;if(!t.startsWith(Er))return``;try{return Or(decodeURIComponent(t.slice(20)))}catch{return``}}function Mr(e){if(!Array.isArray(e))return[];let t=new Set;return e.map(e=>Or(String(e||``))).filter(e=>!e||t.has(e)?!1:(t.add(e),!0))}function Nr(){return{entries:[],index:-1}}function Pr(e,t=Date.now()){return{kind:`agent`,agentId:e,reason:`agent`,ts:t}}function Fr(e,t=Date.now()){return{kind:`file`,agentId:e.agentId,filePath:e.filePath,view:e.view??`editor`,lineNumber:Math.max(1,e.lineNumber??1),column:Math.max(1,e.column??1),endColumn:e.endColumn,...e.sourceAgentId?{sourceAgentId:e.sourceAgentId}:{},reason:e.reason??`file`,ts:t}}function Ir(e,t){return e.kind===t.kind?e.kind===`agent`&&t.kind===`agent`?e.agentId===t.agentId:e.kind===`file`&&t.kind===`file`?e.agentId===t.agentId&&e.filePath===t.filePath&&e.view===t.view:!1:!1}function Lr(e,t){if(!e||!Ir(e,t))return!1;if(e.kind===`agent`&&t.kind===`agent`)return!0;if(e.kind!==`file`||t.kind!==`file`)return!1;let n=Math.abs(e.lineNumber-t.lineNumber);return e.lineNumber===t.lineNumber&&e.column===t.column&&e.endColumn===t.endColumn||t.reason===`cursor`&&(n<30||t.ts-e.ts<1e3)||n<=15}function Rr(e,t,n=50){let r=e.entries[e.index],i=Lr(r,t),a=e.entries,o=e.index;return i&&o>=0?(a=a.slice(),a[o]=t):(a=a.slice(0,o+1),a.push(t),a.length>n&&(a=a.slice(a.length-n)),o=a.length-1),{entries:a,index:o}}function zr(e,t=typeof navigator<`u`?navigator.platform:``){return!(e.key===`-`||e.key===`_`||e.code===`Minus`)||!e.ctrlKey||e.metaKey||e.altKey?null:e.shiftKey?1:-1}t(((e,t)=>{(function(e){let n=/^farming-runtime-v1:(\d{20}):/;function r(e){return typeof e==`number`&&Number.isFinite(e)}function i(e){let t=n.exec(String(e||``));if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)&&r>0?r:null}function a(e,t){if(e===t)return 0;let n=i(e),r=i(t);return n===null||r===null||n===r?null:n<r?-1:1}function o(t){let n=String(t||``);return typeof e.TextEncoder==`function`?new e.TextEncoder().encode(n).byteLength:encodeURIComponent(n).replace(/%[0-9A-F]{2}/gi,`x`).length}function s(e={}){return{runtimeEpoch:``,outputSeq:null,stateRevision:null,replayTargetEpoch:``,replayTargetRevision:null,recovering:!1,queuedTransitions:[],queuedBytes:0,retiredRuntimeEpochs:new Set,failureCount:0,invariantFailureSignature:``,invariantFailureCount:0,halted:!1,haltMessage:``,maxQueuedTransitions:e.maxQueuedTransitions||512,maxQueuedBytes:e.maxQueuedBytes||1048576,retryBaseMs:e.retryBaseMs||250,retryMaxMs:e.retryMaxMs||5e3,maxIdenticalInvariantFailures:e.maxIdenticalInvariantFailures||3}}function c(e){return e!=null&&!!e.runtimeEpoch&&r(e.outputSeq)&&r(e.stateRevision)&&(e.kind!==`resize`||r(e.cols)&&r(e.rows))}function l(e){return e!=null&&!!e.runtimeEpoch&&r(e.outputSeq)&&r(e.stateRevision)&&r(e.cols)&&r(e.rows)&&e.cols>0&&e.rows>0}function u(e,t){if(!(!t||!t.runtimeEpoch||!r(t.stateRevision))){if(!e.replayTargetEpoch){e.replayTargetEpoch=t.runtimeEpoch,e.replayTargetRevision=t.stateRevision;return}if(t.runtimeEpoch===e.replayTargetEpoch){e.replayTargetRevision=Math.max(e.replayTargetRevision||0,t.stateRevision);return}a(t.runtimeEpoch,e.replayTargetEpoch)===1&&(e.replayTargetEpoch=t.runtimeEpoch,e.replayTargetRevision=t.stateRevision)}}function d(e,t){e.recovering=!0,u(e,t)}function f(e){return!e.replayTargetEpoch||!r(e.replayTargetRevision)?!1:!e.runtimeEpoch||!r(e.stateRevision)?!0:e.runtimeEpoch===e.replayTargetEpoch?e.stateRevision<e.replayTargetRevision:a(e.runtimeEpoch,e.replayTargetEpoch)!==1}function p(e,t){if(!c(t))return d(e,t),{action:`recover`,reason:`invalid-transition`};if(e.retiredRuntimeEpochs.has(t.runtimeEpoch))return{action:`drop`,reason:`retired-epoch`};if(e.runtimeEpoch&&t.runtimeEpoch!==e.runtimeEpoch)return a(t.runtimeEpoch,e.runtimeEpoch)===-1?{action:`drop`,reason:`older-epoch`}:(d(e,t),{action:`recover`,reason:`epoch-change`});if(!e.runtimeEpoch||!r(e.outputSeq)||!r(e.stateRevision))return d(e,t),{action:`recover`,reason:`missing-cursor`};if(t.stateRevision<=e.stateRevision)return{action:`drop`,reason:`duplicate`};let n=+(t.kind===`output`);return t.stateRevision!==e.stateRevision+1||t.outputSeq!==e.outputSeq+n?(d(e,t),{action:`recover`,reason:`sequence-gap`}):{action:`apply`}}function m(e,t){if(!c(t))return d(e,t),{queued:!1,overflow:!1};u(e,t);let n=o(t.data);return e.queuedTransitions.length>=e.maxQueuedTransitions||e.queuedBytes+n>e.maxQueuedBytes?(e.queuedTransitions=[],e.queuedBytes=0,e.recovering=!0,{queued:!1,overflow:!0}):(e.queuedTransitions.push(t),e.queuedBytes+=n,{queued:!0,overflow:!1})}function h(e){let t=e.queuedTransitions.shift()||null;return t&&(e.queuedBytes=Math.max(0,e.queuedBytes-o(t.data))),t}function g(e){e.queuedTransitions=[],e.queuedBytes=0}function _(e,t){return{action:`reject`,signature:e,message:t}}function v(e,t){if(t.runtimeEpoch!==e.replayTargetEpoch||!r(e.replayTargetRevision))return!1;let n=t.outputSeq,i=t.stateRevision;for(let r of e.queuedTransitions){if(!c(r)||r.runtimeEpoch!==t.runtimeEpoch)return!1;if(r.stateRevision<=i)continue;let a=+(r.kind===`output`);if(r.stateRevision!==i+1||r.outputSeq!==n+a)return!1;if(n=r.outputSeq,i=r.stateRevision,i>=e.replayTargetRevision)return!0}return!1}function y(e,t){if(!l(t))return _(`invalid-checkpoint`,`Terminal replay returned an invalid screen state`);if(e.runtimeEpoch&&t.runtimeEpoch!==e.runtimeEpoch){if(a(t.runtimeEpoch,e.runtimeEpoch)===-1||e.retiredRuntimeEpochs.has(t.runtimeEpoch))return _(`older-epoch:${t.runtimeEpoch}:${e.runtimeEpoch}`,`Terminal replay returned an older runtime epoch`)}else if(t.runtimeEpoch===e.runtimeEpoch&&r(e.stateRevision)&&t.stateRevision<e.stateRevision)return _(`older-revision:${t.runtimeEpoch}:${t.stateRevision}:${e.stateRevision}`,`Terminal replay returned an older screen state`);if(e.replayTargetEpoch&&r(e.replayTargetRevision)){if(t.runtimeEpoch===e.replayTargetEpoch){if(t.stateRevision<e.replayTargetRevision&&!v(e,t))return _(`behind-target:${t.runtimeEpoch}:${t.stateRevision}:${e.replayTargetRevision}`,`Terminal replay did not reach the latest observed screen state`)}else if(a(t.runtimeEpoch,e.replayTargetEpoch)!==1)return _(`wrong-target-epoch:${t.runtimeEpoch}:${e.replayTargetEpoch}`,`Terminal replay returned a different runtime epoch`)}return{action:t.runtimeEpoch===e.runtimeEpoch&&t.outputSeq===e.outputSeq&&t.stateRevision===e.stateRevision?`current`:`install`}}function b(e,t){e.queuedTransitions=e.queuedTransitions.filter(n=>!c(n)||e.retiredRuntimeEpochs.has(n.runtimeEpoch)?!1:n.runtimeEpoch===t.runtimeEpoch?n.stateRevision>t.stateRevision:a(n.runtimeEpoch,t.runtimeEpoch)!==-1),e.queuedBytes=e.queuedTransitions.reduce((e,t)=>e+o(t.data),0)}function x(e){e.failureCount=0,e.invariantFailureSignature=``,e.invariantFailureCount=0,e.halted=!1,e.haltMessage=``}function S(e,t){if(e.runtimeEpoch&&e.runtimeEpoch!==t.runtimeEpoch)for(e.retiredRuntimeEpochs.add(e.runtimeEpoch);e.retiredRuntimeEpochs.size>4;){let t=e.retiredRuntimeEpochs.values().next().value;t!==void 0&&e.retiredRuntimeEpochs.delete(t)}return e.runtimeEpoch=t.runtimeEpoch,e.outputSeq=t.outputSeq,e.stateRevision=t.stateRevision,b(e,t),x(e),e.recovering=f(e),e.recovering&&v(e,t)&&(e.recovering=!1),e.recovering||(e.replayTargetEpoch=``,e.replayTargetRevision=null),!e.recovering}function C(e,t){if(!c(t)){d(e,t);return}e.runtimeEpoch=t.runtimeEpoch,e.outputSeq=t.outputSeq,e.stateRevision=t.stateRevision,f(e)||(e.replayTargetEpoch=``,e.replayTargetRevision=null,e.recovering=!1)}function w(e){let t=Math.max(0,e.failureCount-1);return Math.min(e.retryMaxMs,e.retryBaseMs*2**t)}function T(e){return e.failureCount+=1,e.recovering=!0,{halted:!1,delay:w(e),message:``}}function E(e,t,n){return e.failureCount+=1,e.recovering=!0,e.invariantFailureSignature===t?e.invariantFailureCount+=1:(e.invariantFailureSignature=t,e.invariantFailureCount=1),e.invariantFailureCount>=e.maxIdenticalInvariantFailures&&(e.halted=!0,e.haltMessage=n||`Terminal replay could not prove a current screen state`),{halted:e.halted,delay:e.halted?0:w(e),message:e.haltMessage}}function D(e,t={}){g(e),e.replayTargetEpoch=``,e.replayTargetRevision=null,e.recovering=!1,x(e),t.keepCursor===!1&&(e.runtimeEpoch=``,e.outputSeq=null,e.stateRevision=null,e.retiredRuntimeEpochs.clear())}let O={createState:s,compareRuntimeEpochs:a,beginRecovery:d,isReplayTargetPending:f,classifyTransition:p,queueTransition:m,takeQueuedTransition:h,clearQueuedTransitions:g,evaluateCheckpoint:y,commitCheckpoint:S,commitTransition:C,recordTransportFailure:T,recordInvariantFailure:E,resetRecovery:D};e.FarmingTerminalReplay=O,typeof t==`object`&&t?.exports&&(t.exports=O)})(globalThis)}))();var Br={background:`#ffffff`,foreground:`#24292f`,cursor:`#24292f`,cursorAccent:`#ffffff`,selectionBackground:`rgba(31, 35, 40, 0.18)`,black:`#24292f`,red:`#cf222e`,green:`#1a7f37`,yellow:`#9a6700`,blue:`#0969da`,magenta:`#8250df`,cyan:`#1b7c83`,white:`#57606a`,brightBlack:`#6e7781`,brightRed:`#a40e26`,brightGreen:`#2da44e`,brightYellow:`#bf8700`,brightBlue:`#218bff`,brightMagenta:`#a475f9`,brightCyan:`#3192aa`,brightWhite:`#24292f`},Vr=[`"JetBrains Mono"`,`"SF Mono"`,`Menlo`,`Monaco`,`"Cascadia Mono"`,`"Segoe UI Mono"`,`"Sarasa Mono SC"`,`"PingFang SC"`,`"Hiragino Sans GB"`,`"Noto Sans Mono CJK SC"`,`"Microsoft YaHei UI"`,`monospace`].join(`, `),Hr=null,Ur=null;async function Wr(){return Hr||Ur||(Ur=(async()=>{try{let e=r(`/vendor/ghostty-web`),t=`${e}/ghostty-web.js`,n=`${e}/ghostty-vt.wasm`,i=await s(()=>import(t),[]);return await i.init(n),Hr={Terminal:i.Terminal,FitAddon:i.FitAddon},Hr}catch(e){return console.error(`Failed to initialize Ghostty terminal:`,e),null}})(),Ur)}async function Gr(e){let t=await Wr();if(!t)return null;let n=e?.fontSize??12;return{terminal:new t.Terminal({theme:Br,fontSize:n,fontFamily:Vr,cursorBlink:!1,smoothScrollDuration:120,scrollback:5e3}),fitAddon:new t.FitAddon}}var Kr=Object.defineProperty,qr=Object.getOwnPropertyDescriptor,Jr=(e,t)=>{for(var n in t)Kr(e,n,{get:t[n],enumerable:!0})},Yr=(e,t,n,r)=>{for(var i=r>1?void 0:r?qr(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&Kr(t,n,i),i},q=(e,t)=>(n,r)=>t(n,r,e),Xr=`Terminal input`,Zr={get:()=>Xr,set:e=>Xr=e},Qr=`Too much output to announce, navigate to rows manually to read`,$r={get:()=>Qr,set:e=>Qr=e};function ei(e){return e.replace(/\r?\n/g,`\r`)}function ti(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function ni(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function ri(e,t,n,r){e.stopPropagation(),e.clipboardData&&ii(e.clipboardData.getData(`text/plain`),t,n,r)}function ii(e,t,n,r){e=ei(e),e=ti(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function ai(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function oi(e,t,n,r,i){ai(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function si(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function ci(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var li=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o);continue}i!==65279&&(t[r++]=i)}return r}},ui=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}else this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(c=(i&31)<<6|a&63,c<128){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},di=``,fi=` `,pi=class e{constructor(){this.fg=0,this.bg=0,this.extended=new mi}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return(this.fg&50331648)==0}isBgDefault(){return(this.bg&50331648)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},mi=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},hi=class e extends pi{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new mi,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?si(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},gi=`di$target`,_i=`di$dependencies`,vi=new Map;function J(e){return e[_i]||[]}function yi(e){if(vi.has(e))return vi.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);bi(t,e,r)};return t._id=e,vi.set(e,t),t}function bi(e,t,n){t[gi]===t?t[_i].push({id:e,index:n}):(t[_i]=[{id:e,index:n}],t[gi]=t)}var Y=yi(`BufferService`),xi=yi(`CoreMouseService`),Si=yi(`CoreService`),Ci=yi(`CharsetService`),wi=yi(`InstantiationService`),Ti=yi(`LogService`),Ei=yi(`OptionsService`),Di=yi(`OscLinkService`),Oi=yi(`UnicodeService`),ki=yi(`DecorationService`),Ai=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new hi,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(!(c===-1&&!n.hasContent(t))){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId)if(c===-1){c=t,s=a.extended.urlId;continue}else l=a.extended.urlId!==s;else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):ji(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};Ai=Yr([q(0,Y),q(1,Ei),q(2,Di)],Ai);function ji(e,t){if(confirm(`Do you want to navigate to ${t}?
6
+
7
+ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var Mi=yi(`CharSizeService`),Ni=yi(`CoreBrowserService`),Pi=yi(`MouseService`),Fi=yi(`RenderService`),Ii=yi(`SelectionService`),Li=yi(`CharacterJoinerService`),Ri=yi(`ThemeService`),zi=yi(`LinkProviderService`),Bi=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Ki.isErrorNoTelemetry(e)?new Ki(e.message+`
8
+
9
+ `+e.stack):Error(e.message+`
10
+
11
+ `+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function Vi(e){Ui(e)||Bi.onUnexpectedError(e)}var Hi=`Canceled`;function Ui(e){return e instanceof Wi?!0:e instanceof Error&&e.name===Hi&&e.message===Hi}var Wi=class extends Error{constructor(){super(Hi),this.name=this.message}};function Gi(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var Ki=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},qi=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function Ji(e,t,n=0,r=e.length){let i=n,a=r;for(;i<a;){let n=Math.floor((i+a)/2);t(e[n])?i=n+1:a=n}return i-1}var Yi=class e{constructor(e){this._array=e,this._findLastMonotonousLastIdx=0}findLastMonotonous(t){if(e.assertInvariants){if(this._prevFindLastPredicate){for(let e of this._array)if(this._prevFindLastPredicate(e)&&!t(e))throw Error(`MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.`)}this._prevFindLastPredicate=t}let n=Ji(this._array,t,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=n+1,n===-1?void 0:this._array[n]}};Yi.assertInvariants=!1;function Xi(e,t=0){return e[e.length-(1+t)]}var Zi;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Zi||={});function Qi(e,t){return(n,r)=>t(e(n),e(r))}var X=(e,t)=>e-t,$i=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>t(n)?e(n):!0))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>e(n)?(t=n,!1):!0),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||Zi.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};$i.empty=new $i(e=>{});function ea(e,t){let n=Object.create(null);for(let r of e){let e=t(r),i=n[e];i||=n[e]=[],i.push(r)}return n}var ta=class{constructor(){this.map=new Map}add(e,t){let n=this.map.get(e);n||(n=new Set,this.map.set(e,n)),n.add(t)}delete(e,t){let n=this.map.get(e);n&&(n.delete(t),n.size===0&&this.map.delete(e))}forEach(e,t){let n=this.map.get(e);n&&n.forEach(t)}get(e){return this.map.get(e)||new Set}};function na(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var ra;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(ra||={});var ia=!1,aa=null,oa=class e{constructor(){this.livingDisposables=new Map}getDisposableData(t){let n=this.livingDisposables.get(t);return n||(n={parent:null,source:null,isSingleton:!1,value:t,idx:e.idx++},this.livingDisposables.set(t,n)),n}trackDisposable(e){let t=this.getDisposableData(e);t.source||=Error().stack}setParent(e,t){let n=this.getDisposableData(e);n.parent=t}markAsDisposed(e){this.livingDisposables.delete(e)}markAsSingleton(e){this.getDisposableData(e).isSingleton=!0}getRootParent(e,t){let n=t.get(e);if(n)return n;let r=e.parent?this.getRootParent(this.getDisposableData(e.parent),t):e;return t.set(e,r),r}getTrackedDisposables(){let e=new Map;return[...this.livingDisposables.entries()].filter(([,t])=>t.source!==null&&!this.getRootParent(t,e).isSingleton).flatMap(([e])=>e)}computeLeakingDisposables(e=10,t){let n;if(t)n=t;else{let e=new Map,t=[...this.livingDisposables.values()].filter(t=>t.source!==null&&!this.getRootParent(t,e).isSingleton);if(t.length===0)return;let r=new Set(t.map(e=>e.value));if(n=t.filter(e=>!(e.parent&&r.has(e.parent))),n.length===0)throw Error(`There are cyclic diposable chains!`)}if(!n)return;function r(e){function t(e,t){for(;e.length>0&&t.some(t=>typeof t==`string`?t===e[0]:e[0].match(t));)e.shift()}let n=e.source.split(`
12
+ `).map(e=>e.trim().replace(`at `,``)).filter(e=>e!==``);return t(n,[`Error`,/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),n.reverse()}let i=new ta;for(let e of n){let t=r(e);for(let n=0;n<=t.length;n++)i.add(t.slice(0,n).join(`
13
+ `),e)}n.sort(Qi(e=>e.idx,X));let a=``,o=0;for(let t of n.slice(0,e)){o++;let e=r(t),s=[];for(let t=0;t<e.length;t++){let a=e[t];a=`(shared with ${i.get(e.slice(0,t+1).join(`
14
+ `)).size}/${n.length} leaks) at ${a}`;let o=ea([...i.get(e.slice(0,t).join(`
15
+ `))].map(e=>r(e)[t]),e=>e);delete o[e[t]];for(let[e,t]of Object.entries(o))s.unshift(` - stacktraces of ${t.length} other leaks continue with ${e}`);s.unshift(a)}a+=`
16
+
17
+
18
+ ==================== Leaking disposable ${o}/${n.length}: ${t.value.constructor.name} ====================
19
+ ${s.join(`
20
+ `)}
21
+ ============================================================
22
+
23
+ `}return n.length>e&&(a+=`
24
+
25
+
26
+ ... and ${n.length-e} more leaking disposables
27
+
28
+ `),{leaks:n,details:a}}};oa.idx=0;function sa(e){aa=e}if(ia){let e=`__is_disposable_tracked__`;sa(new class{trackDisposable(t){let n=Error(`Potentially leaked disposable`).stack;setTimeout(()=>{t[e]||console.log(n)},3e3)}setParent(t,n){if(t&&t!==va.None)try{t[e]=!0}catch{}}markAsDisposed(t){if(t&&t!==va.None)try{t[e]=!0}catch{}}markAsSingleton(e){}})}function ca(e){return aa?.trackDisposable(e),e}function la(e){aa?.markAsDisposed(e)}function ua(e,t){aa?.setParent(e,t)}function da(e,t){if(aa)for(let n of e)aa.setParent(n,t)}function fa(e){return aa?.markAsSingleton(e),e}function pa(e){if(ra.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function ma(...e){let t=ha(()=>pa(e));return da(e,t),t}function ha(e){let t=ca({dispose:na(()=>{la(t),e()})});return t}var ga=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,ca(this)}dispose(){this._isDisposed||(la(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{pa(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return ua(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),ua(e,null))}};ga.DISABLE_DISPOSED_WARNING=!1;var _a=ga,va=class{constructor(){this._store=new _a,ca(this),ua(this._store,this)}dispose(){la(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};va.None=Object.freeze({dispose(){}});var ya=class{constructor(){this._isDisposed=!1,ca(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&ua(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,la(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&ua(e,null),e}},ba=typeof window==`object`?window:globalThis,xa=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};xa.Undefined=new xa(void 0);var Sa=xa,Ca=class{constructor(){this._first=Sa.Undefined,this._last=Sa.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Sa.Undefined}clear(){let e=this._first;for(;e!==Sa.Undefined;){let t=e.next;e.prev=Sa.Undefined,e.next=Sa.Undefined,e=t}this._first=Sa.Undefined,this._last=Sa.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new Sa(e);if(this._first===Sa.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==Sa.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Sa.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Sa.Undefined&&e.next!==Sa.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Sa.Undefined&&e.next===Sa.Undefined?(this._first=Sa.Undefined,this._last=Sa.Undefined):e.next===Sa.Undefined?(this._last=this._last.prev,this._last.next=Sa.Undefined):e.prev===Sa.Undefined&&(this._first=this._first.next,this._first.prev=Sa.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==Sa.Undefined;)yield e.element,e=e.next}},wa=globalThis.performance&&typeof globalThis.performance.now==`function`,Ta=class e{static create(t){return new e(t)}constructor(e){this._now=wa&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},Ea=!1,Da=!1,Oa=!1,ka;(e=>{e.None=()=>va.None;function t(e){if(Oa){let{onDidAddListener:t}=e,n=Fa.create(),r=0;e.onDidAddListener=()=>{++r===2&&(console.warn(`snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here`),n.print()),t?.()}}}function n(e,t){return f(e,()=>{},0,void 0,!0,void 0,t)}e.defer=n;function r(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=r;function i(e,t,n){return u((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=i;function a(e,t,n){return u((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=a;function o(e,t,n){return u((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=o;function s(e){return e}e.signal=s;function c(...e){return(t,n=null,r)=>d(ma(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=c;function l(e,t,n,r){let a=n;return i(e,e=>(a=t(a,e),a),r)}e.reduce=l;function u(e,n){let r,i={onWillAddFirstListener(){r=e(a.fire,a)},onDidRemoveLastListener(){r?.dispose()}};n||t(i);let a=new Z(i);return n?.add(a),a.event}function d(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function f(e,n,r=100,i=!1,a=!1,o,s){let c,l,u,d=0,f,p={leakWarningThreshold:o,onWillAddFirstListener(){c=e(e=>{d++,l=n(l,e),i&&!u&&(m.fire(l),l=void 0),f=()=>{let e=l;l=void 0,u=void 0,(!i||d>1)&&m.fire(e),d=0},typeof r==`number`?(clearTimeout(u),u=setTimeout(f,r)):u===void 0&&(u=0,queueMicrotask(f))})},onWillRemoveListener(){a&&d>0&&f?.()},onDidRemoveLastListener(){f=void 0,c.dispose()}};s||t(p);let m=new Z(p);return s?.add(m),m.event}e.debounce=f;function p(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=p;function m(e,t=(e,t)=>e===t,n){let r=!0,i;return o(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=m;function h(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=h;function g(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new Z({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=g;function _(e,t){return(n,r,i)=>{let a=t(new y);return e(function(e){let t=a.evaluate(e);t!==v&&n.call(r,t)},void 0,i)}}e.chain=_;let v=Symbol(`HaltChainable`);class y{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:v),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:v}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===v)break;return e}}function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Z({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=b;function x(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Z({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=x;function S(e){return new Promise(t=>r(e)(t))}e.toPromise=S;function C(e){let t=new Z;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=C;function w(e,t){return e(e=>t.fire(e))}e.forward=w;function T(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=T;class E{constructor(e,n){this._observable=e,this._counter=0,this._hasChanged=!1;let r={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};n||t(r),this.emitter=new Z(r),n&&n.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function D(e,t){return new E(e,t).emitter.event}e.fromObservable=D;function O(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof _a?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=O})(ka||={});var Aa=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Ta,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Aa.all=new Set,Aa._idPool=0;var ja=Aa,Ma=-1,Na=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new Ia(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};Na._idPool=1;var Pa=Na,Fa=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
29
+ `).slice(2).join(`
30
+ `))}},Ia=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},La=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},Ra=0,za=class{constructor(e){this.value=e,this.id=Ra++}},Ba=2,Va=(e,t)=>{if(e instanceof za)t(e);else for(let n=0;n<e.length;n++){let r=e[n];r&&t(r)}},Ha;if(Ea){let e=[];setInterval(()=>{e.length!==0&&(console.warn(`[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:`),console.warn(e.join(`
31
+ `)),e.length=0)},3e3),Ha=new FinalizationRegistry(t=>{typeof t==`string`&&e.push(t)})}var Z=class{constructor(e){this._size=0,this._options=e,this._leakageMon=Ma>0||this._options?.leakWarningThreshold?new Pa(e?.onListenerError??Vi,this._options?.leakWarningThreshold??Ma):void 0,this._perfMon=this._options?._profName?new ja(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(Da){let e=this._listeners;queueMicrotask(()=>{Va(e,e=>e.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new La(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||Vi)(n),va.None}if(this._disposed)return va.None;t&&(e=e.bind(t));let r=new za(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Fa.create(),i=this._leakageMon.check(r.stack,this._size+1)),Da&&(r.stack=Fa.create()),this._listeners?this._listeners instanceof za?(this._deliveryQueue??=new Ua,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=ha(()=>{Ha?.unregister(a),i?.(),this._removeListener(r)});if(n instanceof _a?n.add(a):Array.isArray(n)&&n.push(a),Ha){let e=Error().stack.split(`
32
+ `).slice(2,3).join(`
33
+ `).trim(),t=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(e);Ha.register(a,t?.[2]??e,a)}return a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Ba<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||Vi;if(!n){e.value(t);return}try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof za)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}this._perfMon?.stop()}hasListeners(){return this._size>0}},Ua=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Wa=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Z,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Z,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};Wa.INSTANCE=new Wa;var Ga=Wa;function Ka(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}Ga.INSTANCE.onDidChangeZoomLevel;function qa(e){return Ga.INSTANCE.getZoomFactor(e)}Ga.INSTANCE.onDidChangeFullscreen;var Ja=typeof navigator==`object`?navigator.userAgent:``,Ya=Ja.indexOf(`Firefox`)>=0,Xa=Ja.indexOf(`AppleWebKit`)>=0,Za=Ja.indexOf(`Chrome`)>=0,Qa=!Za&&Ja.indexOf(`Safari`)>=0;Ja.indexOf(`Electron/`),Ja.indexOf(`Android`);var $a=!1;if(typeof ba.matchMedia==`function`){let e=ba.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=ba.matchMedia(`(display-mode: fullscreen)`);$a=e.matches,Ka(ba,e,({matches:e})=>{$a&&t.matches||($a=e)})}function eo(){return $a}var to=`en`,no=!1,ro=!1,io=!1,ao=!1,oo=!1,so=to,co,lo=globalThis,uo;typeof lo.vscode<`u`&&typeof lo.vscode.process<`u`?uo=lo.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(uo=process);var fo=typeof uo?.versions?.electron==`string`&&uo?.type===`renderer`;if(typeof uo==`object`){no=uo.platform===`win32`,ro=uo.platform===`darwin`,io=uo.platform===`linux`,io&&uo.env.SNAP&&uo.env.SNAP_REVISION,uo.env.CI||uo.env.BUILD_ARTIFACTSTAGINGDIRECTORY,so=to;let e=uo.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,so=t.resolvedLanguage||to,t.languagePack?.translationsConfigFile}catch{}ao=!0}else typeof navigator==`object`&&!fo?(co=navigator.userAgent,no=co.indexOf(`Windows`)>=0,ro=co.indexOf(`Macintosh`)>=0,(co.indexOf(`Macintosh`)>=0||co.indexOf(`iPad`)>=0||co.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,io=co.indexOf(`Linux`)>=0,co?.indexOf(`Mobi`),oo=!0,so=globalThis._VSCODE_NLS_LANGUAGE||to,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var po=no,mo=ro,ho=io,go=ao;oo&&typeof lo.importScripts==`function`&&lo.origin;var _o=co,vo=so,yo;(e=>{function t(){return vo}e.value=t;function n(){return vo.length===2?vo===`en`:vo.length>=3?vo[0]===`e`&&vo[1]===`n`&&vo[2]===`-`:!1}e.isDefaultVariant=n;function r(){return vo===`en`}e.isDefault=r})(yo||={});var bo=typeof lo.postMessage==`function`&&!lo.importScripts;(()=>{if(bo){let e=[];lo.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),lo.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var xo=!!(_o&&_o.indexOf(`Chrome`)>=0);_o&&_o.indexOf(`Firefox`),!xo&&_o&&_o.indexOf(`Safari`),_o&&_o.indexOf(`Edg/`),_o&&_o.indexOf(`Android`);var So=typeof navigator==`object`?navigator:{};go||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||So&&So.clipboard&&So.clipboard.writeText,go||So&&So.clipboard&&So.clipboard.readText,go||eo()||So.keyboard,`ontouchstart`in ba||So.maxTouchPoints,ba.PointerEvent&&(`ontouchstart`in ba||navigator.maxTouchPoints);var Co=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},wo=new Co,To=new Co,Eo=new Co,Do=Array(230),Oo;(e=>{function t(e){return wo.keyCodeToStr(e)}e.toString=t;function n(e){return wo.strToKeyCode(e)}e.fromString=n;function r(e){return To.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return Eo.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return To.strToKeyCode(e)||Eo.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return wo.keyCodeToStr(e)}e.toElectronAccelerator=o})(Oo||={});var ko=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Ao([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Ao=class{constructor(e){if(e.length===0)throw Gi(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=`;`),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function jo(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return Oo.fromString(t)}let t=e.keyCode;if(t===3)return 7;if(Ya)switch(t){case 59:return 85;case 60:if(ho)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(mo)return 57;break}else if(Xa&&(mo&&t===93||!mo&&t===92))return 57;return Do[t]||0}var Mo=mo?256:2048,No=512,Po=1024,Fo=mo?2048:256,Io=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=jo(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=Mo),this.altKey&&(t|=No),this.shiftKey&&(t|=Po),this.metaKey&&(t|=Fo),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new ko(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Lo=new WeakMap;function Ro(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}var zo=class{static getSameOriginWindowChain(e){let t=Lo.get(e);if(!t){t=[],Lo.set(e,t);let n=e,r;do r=Ro(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}},Bo=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=zo.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Vo=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(Za){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(typeof t.wheelDeltaY<`u`)r?this.deltaY=t.wheelDeltaY/(120*i):this.deltaY=t.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<`u`&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;t.deltaMode===t.DOM_DELTA_LINE?Ya&&!mo?this.deltaY=-e.deltaY/3:this.deltaY=-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof t.wheelDeltaX<`u`)Qa&&po?this.deltaX=-(t.wheelDeltaX/120):r?this.deltaX=t.wheelDeltaX/(120*i):this.deltaX=t.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<`u`&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;t.deltaMode===t.DOM_DELTA_LINE?Ya&&!mo?this.deltaX=-e.deltaX/3:this.deltaX=-e.deltaX:this.deltaX=-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(r?this.deltaY=e.wheelDelta/(120*i):this.deltaY=e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},Ho=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),Uo;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof Wo?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:ka.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Ho})})(Uo||={});var Wo=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Ho:(this._emitter||=new Z,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},Go=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new qi(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new qi(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Ko=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new qi(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=ha(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var qo;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(qo||={});var Jo=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new Z,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await ka.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};Jo.EMPTY=Jo.fromArray([]);function Yo(e){return 55296<=e&&e<=56319}function Xo(e){return 56320<=e&&e<=57343}function Zo(e,t){return(e-55296<<10)+(t-56320)+65536}function Qo(e){return $o(e,0)}function $o(e,t){switch(typeof e){case`object`:return e===null?es(349,t):Array.isArray(e)?rs(e,t):is(e,t);case`string`:return ns(e,t);case`boolean`:return ts(e,t);case`number`:return es(e,t);case`undefined`:return es(937,t);default:return es(617,t)}}function es(e,t){return(t<<5)-t+e|0}function ts(e,t){return es(e?433:863,t)}function ns(e,t){t=es(149417,t);for(let n=0,r=e.length;n<r;n++)t=es(e.charCodeAt(n),t);return t}function rs(e,t){return t=es(104579,t),e.reduce((e,t)=>$o(t,e),t)}function is(e,t){return t=es(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=ns(n,t),$o(e[n],t)),t)}function as(e,t,n=32){let r=n-t,i=~((1<<r)-1);return(e<<t|(i&e)>>>r)>>>0}function os(e,t=0,n=e.byteLength,r=0){for(let i=0;i<n;i++)e[t+i]=r}function ss(e,t,n=`0`){for(;e.length<t;)e=n+e;return e}function cs(e,t=32){return e instanceof ArrayBuffer?Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,`0`)).join(``):ss((e>>>0).toString(16),t/4)}var ls=class e{constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(e){let t=e.length;if(t===0)return;let n=this._buff,r=this._buffLen,i=this._leftoverHighSurrogate,a,o;for(i===0?(a=e.charCodeAt(0),o=0):(a=i,o=-1,i=0);;){let s=a;if(Yo(a))if(o+1<t){let t=e.charCodeAt(o+1);Xo(t)?(o++,s=Zo(a,t)):s=65533}else{i=a;break}else Xo(a)&&(s=65533);if(r=this._push(n,r,s),o++,o<t)a=e.charCodeAt(o);else break}this._buffLen=r,this._leftoverHighSurrogate=i}_push(e,t,n){return n<128?e[t++]=n:n<2048?(e[t++]=192|(n&1984)>>>6,e[t++]=128|(n&63)>>>0):n<65536?(e[t++]=224|(n&61440)>>>12,e[t++]=128|(n&4032)>>>6,e[t++]=128|(n&63)>>>0):(e[t++]=240|(n&1835008)>>>18,e[t++]=128|(n&258048)>>>12,e[t++]=128|(n&4032)>>>6,e[t++]=128|(n&63)>>>0),t>=64&&(this._step(),t-=64,this._totalLen+=64,e[0]=e[64],e[1]=e[65],e[2]=e[66]),t}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),cs(this._h0)+cs(this._h1)+cs(this._h2)+cs(this._h3)+cs(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,os(this._buff,this._buffLen),this._buffLen>56&&(this._step(),os(this._buff));let e=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(e/4294967296),!1),this._buffDV.setUint32(60,e%4294967296,!1),this._step()}_step(){let t=e._bigBlock32,n=this._buffDV;for(let e=0;e<64;e+=4)t.setUint32(e,n.getUint32(e,!1),!1);for(let e=64;e<320;e+=4)t.setUint32(e,as(t.getUint32(e-12,!1)^t.getUint32(e-32,!1)^t.getUint32(e-56,!1)^t.getUint32(e-64,!1),1),!1);let r=this._h0,i=this._h1,a=this._h2,o=this._h3,s=this._h4,c,l,u;for(let e=0;e<80;e++)e<20?(c=i&a|~i&o,l=1518500249):e<40?(c=i^a^o,l=1859775393):e<60?(c=i&a|i&o|a&o,l=2400959708):(c=i^a^o,l=3395469782),u=as(r,5)+c+s+l+t.getUint32(e*4,!1)&4294967295,s=o,o=a,a=as(i,30),i=r,r=u;this._h0=this._h0+r&4294967295,this._h1=this._h1+i&4294967295,this._h2=this._h2+a&4294967295,this._h3=this._h3+o&4294967295,this._h4=this._h4+s&4294967295}};ls._bigBlock32=new DataView(new ArrayBuffer(320));var{registerWindow:us,getWindow:ds,getDocument:fs,getWindows:ps,getWindowsCount:ms,getWindowId:hs,getWindowById:gs,hasWindow:_s,onDidRegisterWindow:vs,onWillUnregisterWindow:ys,onDidUnregisterWindow:bs}=function(){let e=new Map,t={window:ba,disposables:new _a};e.set(ba.vscodeWindowId,t);let n=new Z,r=new Z,i=new Z;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return va.None;let a=new _a,o={window:t,disposables:a.add(new _a)};return e.set(t.vscodeWindowId,o),a.add(ha(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(Ss(t,js.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:ba},getDocument(e){return ds(e).document}}}(),xs=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function Ss(e,t,n,r){return new xs(e,t,n,r)}function Cs(e,t){return function(n){return t(new Bo(e,n))}}function ws(e){return function(t){return e(new Io(t))}}var Ts=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=Cs(ds(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=ws(n)),Ss(e,t,i,r)},Es,Ds=class extends Ko{constructor(e){super(),this.defaultTarget=e&&ds(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},Os=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){Vi(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(Os.sort),a.shift().execute();r.set(i,!1)};Es=(t,r,a=0)=>{let o=hs(t),s=new Os(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var ks=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};ks.None=new ks(0,0);function As(e){let t=e.getBoundingClientRect(),n=ds(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=Qo(n),a=r.get(i);if(a)a.users+=1;else{let o=new Z,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(ha(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var js={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:Xa?`webkitAnimationStart`:`animationstart`,ANIMATION_END:Xa?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:Xa?`webkitAnimationIteration`:`animationiteration`},Ms=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;function Ns(e,t,n,...r){let i=Ms.exec(t);if(!i)throw Error(`Bad use of emmet`);let a=i[1]||`div`,o;return o=e===`http://www.w3.org/1999/xhtml`?document.createElement(a):document.createElementNS(e,a),i[3]&&(o.id=i[3]),i[4]&&(o.className=i[4].replace(/\./g,` `).trim()),n&&Object.entries(n).forEach(([e,t])=>{typeof t>`u`||(/^on\w+$/.test(e)?o[e]=t:e===`selected`?t&&o.setAttribute(e,`true`):o.setAttribute(e,t))}),o.append(...r),o}function Ps(e,t,...n){return Ns(`http://www.w3.org/1999/xhtml`,e,t,...n)}Ps.SVG=function(e,t,...n){return Ns(`http://www.w3.org/2000/svg`,e,t,...n)};var Fs=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=Is(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Is(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Is(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Is(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Is(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Is(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Is(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Is(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Is(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Is(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Is(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Is(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Is(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Is(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Is(e){return typeof e==`number`?`${e}px`:e}function Ls(e){return new Fs(e)}var Rs=class{constructor(){this._hooks=new _a,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(ha(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=ds(e)}this._hooks.add(Ss(a,js.POINTER_MOVE,e=>{if(e.buttons!==n){this.stopMonitoring(!0);return}e.preventDefault(),this._pointerMoveCallback(e)})),this._hooks.add(Ss(a,js.POINTER_UP,e=>this.stopMonitoring(!0)))}};function zs(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var Bs;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(Bs||={});var Vs=class e extends va{constructor(){super(),this.dispatched=!1,this.targets=new Ca,this.ignoreTargets=new Ca,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(ka.runAndSubscribe(vs,({window:e,disposables:t})=>{t.add(Ss(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(Ss(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(Ss(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:ba,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=fa(new e),ha(e.INSTANCE.targets.push(t))):va.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=fa(new e),ha(e.INSTANCE.ignoreTargets.push(t))):va.None}static isTouchDevice(){return`ontouchstart`in ba||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n<r;n++){let r=e.targetTouches.item(n);this.activeTouches[r.identifier]={id:r.identifier,initialTarget:r.target,initialTimeStamp:t,initialPageX:r.pageX,initialPageY:r.pageY,rollingTimestamps:[t],rollingPageX:[r.pageX],rollingPageY:[r.pageY]};let i=this.newGestureEvent(Bs.Start,r.target);i.pageX=r.pageX,i.pageY=r.pageY,this.dispatchEvent(i)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}onTouchEnd(t,n){let r=Date.now(),i=Object.keys(this.activeTouches).length;for(let a=0,o=n.changedTouches.length;a<o;a++){let o=n.changedTouches.item(a);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn(`move of an UNKNOWN touch`,o);continue}let s=this.activeTouches[o.identifier],c=Date.now()-s.initialTimeStamp;if(c<e.HOLD_DELAY&&Math.abs(s.initialPageX-Xi(s.rollingPageX))<30&&Math.abs(s.initialPageY-Xi(s.rollingPageY))<30){let e=this.newGestureEvent(Bs.Tap,s.initialTarget);e.pageX=Xi(s.rollingPageX),e.pageY=Xi(s.rollingPageY),this.dispatchEvent(e)}else if(c>=e.HOLD_DELAY&&Math.abs(s.initialPageX-Xi(s.rollingPageX))<30&&Math.abs(s.initialPageY-Xi(s.rollingPageY))<30){let e=this.newGestureEvent(Bs.Contextmenu,s.initialTarget);e.pageX=Xi(s.rollingPageX),e.pageY=Xi(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=Xi(s.rollingPageX),n=Xi(s.rollingPageY),i=Xi(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(Bs.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===Bs.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else (t.type===Bs.Change||t.type===Bs.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=Es(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(Bs.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(r.identifier))){console.warn(`end of an UNKNOWN touch`,r);continue}let i=this.activeTouches[r.identifier],a=this.newGestureEvent(Bs.Change,i.initialTarget);a.translationX=r.pageX-Xi(i.rollingPageX),a.translationY=r.pageY-Xi(i.rollingPageY),a.pageX=r.pageX,a.pageY=r.pageY,this.dispatchEvent(a),i.rollingPageX.length>3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};Vs.SCROLL_FRICTION=-.005,Vs.HOLD_DELAY=700,Vs.CLEAR_TAP_COUNT_TIME=400,Yr([zs],Vs,`isTouchDevice`,1);var Hs=Vs,Us=class extends va{onclick(e,t){this._register(Ss(e,js.CLICK,n=>t(new Bo(ds(e),n))))}onmousedown(e,t){this._register(Ss(e,js.MOUSE_DOWN,n=>t(new Bo(ds(e),n))))}onmouseover(e,t){this._register(Ss(e,js.MOUSE_OVER,n=>t(new Bo(ds(e),n))))}onmouseleave(e,t){this._register(Ss(e,js.MOUSE_LEAVE,n=>t(new Bo(ds(e),n))))}onkeydown(e,t){this._register(Ss(e,js.KEY_DOWN,e=>t(new Io(e))))}onkeyup(e,t){this._register(Ss(e,js.KEY_UP,e=>t(new Io(e))))}oninput(e,t){this._register(Ss(e,js.INPUT,t))}onblur(e,t){this._register(Ss(e,js.BLUR,t))}onfocus(e,t){this._register(Ss(e,js.FOCUS,t))}onchange(e,t){this._register(Ss(e,js.CHANGE,t))}ignoreGesture(e){return Hs.ignoreTarget(e)}},Ws=11,Gs=class extends Us{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=Ws+`px`,this.domNode.style.height=Ws+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new Rs),this._register(Ts(this.bgDomNode,js.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(Ts(this.domNode,js.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new Ds),this._pointerdownScheduleRepeatTimer=this._register(new Go)}_arrowPointerDown(e){!e.target||!(e.target instanceof Element)||(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,ds(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},Ks=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},qs=class extends va{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Ks(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new Zs(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=Zs.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},Js=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function Ys(e,t){let n=t-e;return function(t){return e+n*$s(t)}}function Xs(e,t,n){return function(r){return r<n?e(r/n):t((r-n)/(1-n))}}var Zs=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let r,i;return e<t?(r=e+.75*n,i=t-.75*n):(r=e-.75*n,i=t+.75*n),Xs(Ys(e,r),Ys(i,t),.33)}return Ys(e,t)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;return t<1?new Js(this.scrollLeft(t),this.scrollTop(t),!1):new Js(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,r){return e.start(t,n,r)}static start(t,n,r){return r+=10,new e(t,n,Date.now()-10,r)}};function Qs(e){return e**3}function $s(e){return 1-Qs(1-e)}var ec=class extends va{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Go)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3?!0:this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){if(!this._isNeeded){this._hide(!1);return}this._shouldBeVisible?this._reveal():this._hide(!0)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},tc=140,nc=class extends Us{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new ec(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Rs),this._shouldRender=!0,this.domNode=Ls(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(Ss(this.domNode.domNode,js.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new Gs(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=Ls(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Ss(this.slider.domNode,js.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=As(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(po&&a>tc){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},rc=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize===t?!1:(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize===t?!1:(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition===t?!1:(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},ic=class extends nc{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new rc(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,r.width,r.scrollWidth,i.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},ac=class extends nc{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new rc(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},oc=500,sc=50,cc=!0,lc=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},uc=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;do{let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}while(!0);return t<=.5}acceptStandardWheelEvent(e){if(Za){let t=qa(ds(e.browserEvent));this.accept(Date.now(),e.deltaX*t,e.deltaY*t)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new lc(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};uc.INSTANCE=new uc;var dc=uc,fc=class extends Us{constructor(e,t,n){super(),this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Z),this.onWillScroll=this._onWillScroll.event,this._options=mc(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new ac(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new ic(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Ls(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Ls(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Ls(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new Go),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=pa(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,mo&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Vo(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=pa(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(Ss(this._listenOnDomNode,js.MOUSE_WHEEL,e=>{this._onMouseWheel(new Vo(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=dc.INSTANCE;cc&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!mo&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=sc*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=sc*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(cc&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),oc)}},pc=class extends fc{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function mc(e){let t={lazyRender:typeof e.lazyRender<`u`?e.lazyRender:!1,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<`u`?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`?e.horizontalHasArrows:!1,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,mo&&(t.className+=` mac`),t}var hc=class extends va{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new Z),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new qs({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>Es(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new pc(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(ka.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ha(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(ha(()=>this._styleElement.remove())),this._register(ka.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(`
34
+ `)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};hc=Yr([q(2,Y),q(3,Ni),q(4,xi),q(5,Ri),q(6,Ei),q(7,Fi)],hc);var gc=class extends va{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(ha(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};gc=Yr([q(1,Y),q(2,Ni),q(3,ki),q(4,Fi)],gc);var _c=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},vc={full:0,left:0,center:0,right:0},yc={full:0,left:0,center:0,right:0},bc={full:0,left:0,center:0,right:0},xc=class extends va{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new _c,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(ha(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);yc.full=this._canvas.width,yc.left=e,yc.center=t,yc.right=e,this._refreshDrawHeightConstants(),bc.full=1,bc.left=1,bc.center=1+yc.left,bc.right=1+yc.left+yc.center}_refreshDrawHeightConstants(){vc.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);vc.left=t,vc.center=t,vc.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vc.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vc.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vc.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*vc.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(bc[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-vc[e.position||`full`]/2),yc[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+vc[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};xc=Yr([q(2,Y),q(3,ki),q(4,Fi),q(5,Ei),q(6,Ri),q(7,Ni)],xc);var Q;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
35
+ `,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))(Q||={});var Sc;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(Sc||={});var Cc;(e=>e.ST=`${Q.ESC}\\`)(Cc||={});var wc=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${Q.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};wc=Yr([q(2,Y),q(3,Ei),q(4,Si),q(5,Fi)],wc);var Tc=0,Ec=0,Dc=0,Oc=0,kc={css:`#00000000`,rgba:0},Ac;(e=>{function t(e,t,n,r){return r===void 0?`#${Fc(e)}${Fc(t)}${Fc(n)}`:`#${Fc(e)}${Fc(t)}${Fc(n)}${Fc(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(Ac||={});var jc;(e=>{function t(e,t){if(Oc=(t.rgba&255)/255,Oc===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return Tc=a+Math.round((n-a)*Oc),Ec=o+Math.round((r-o)*Oc),Dc=s+Math.round((i-s)*Oc),{css:Ac.toCss(Tc,Ec,Dc),rgba:Ac.toRgba(Tc,Ec,Dc)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=Pc.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return Ac.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[Tc,Ec,Dc]=Pc.toChannels(t),{css:Ac.toCss(Tc,Ec,Dc),rgba:t}}e.opaque=i;function a(e,t){return Oc=Math.round(t*255),[Tc,Ec,Dc]=Pc.toChannels(e.rgba),{css:Ac.toCss(Tc,Ec,Dc,Oc),rgba:Ac.toRgba(Tc,Ec,Dc,Oc)}}e.opacity=a;function o(e,t){return Oc=e.rgba&255,a(e,Oc*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(jc||={});var Mc;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return Tc=parseInt(e.slice(1,2).repeat(2),16),Ec=parseInt(e.slice(2,3).repeat(2),16),Dc=parseInt(e.slice(3,4).repeat(2),16),Ac.toColor(Tc,Ec,Dc);case 5:return Tc=parseInt(e.slice(1,2).repeat(2),16),Ec=parseInt(e.slice(2,3).repeat(2),16),Dc=parseInt(e.slice(3,4).repeat(2),16),Oc=parseInt(e.slice(4,5).repeat(2),16),Ac.toColor(Tc,Ec,Dc,Oc);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return Tc=parseInt(r[1]),Ec=parseInt(r[2]),Dc=parseInt(r[3]),Oc=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),Ac.toColor(Tc,Ec,Dc,Oc);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[Tc,Ec,Dc,Oc]=t.getImageData(0,0,1,1).data,Oc!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:Ac.toRgba(Tc,Ec,Dc,Oc),css:e}}e.toColor=r})(Mc||={});var Nc;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(Nc||={});var Pc;(e=>{function t(e,t){if(Oc=(t&255)/255,Oc===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return Tc=a+Math.round((n-a)*Oc),Ec=o+Math.round((r-o)*Oc),Dc=s+Math.round((i-s)*Oc),Ac.toRgba(Tc,Ec,Dc)}e.blend=t;function n(e,t,n){let a=Nc.relativeLuminance(e>>8),o=Nc.relativeLuminance(t>>8);if(Ic(a,o)<n){if(o<a){let o=r(e,t,n),s=Ic(a,Nc.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>Ic(a,Nc.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=Ic(a,Nc.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>Ic(a,Nc.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Ic(Nc.relativeLuminance2(o,s,c),Nc.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=Ic(Nc.relativeLuminance2(o,s,c),Nc.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Ic(Nc.relativeLuminance2(o,s,c),Nc.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=Ic(Nc.relativeLuminance2(o,s,c),Nc.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(Pc||={});function Fc(e){let t=e.toString(16);return t.length<2?`0`+t:t}function Ic(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var Lc=class extends pi{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Rc=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new hi}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||fi.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)Rc._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||fi.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};Rc=Yr([q(0,Y)],Rc);function zc(e){return 57508<=e&&e<=57558}function Bc(e){return 9472<=e&&e<=9631}function Vc(e){return zc(e)||Bc(e)}function Hc(){return{css:{canvas:Uc(),cell:Uc()},device:{canvas:Uc(),cell:Uc(),char:{width:0,height:0,left:0,top:0}}}}function Uc(){return{width:0,height:0}}var Wc=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new hi,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,y=0,b=0,x=0,S=!1,C=0,w=!1,T=0,E=0,D=[],O=l!==-1&&u!==-1;for(let k=0;k<m;k++){e.loadCell(k,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let A=!1,j=k>=E,M=k,N=this._workCell;if(f.length>0&&k===f[0][0]&&j){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)j&&=i===this._isCellInSelection(v,t);j&&=!n||a<r[0]||a>=r[1],j?(A=!0,N=new Lc(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),M=r[1]-1,m=N.getWidth()):E=r[1]}let P=this._isCellInSelection(k,t),F=n&&k===a,ee=O&&k>=l&&k<=u,I=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{I=!0});let L=N.getChars()||fi;if(L===` `&&(N.isUnderline()||N.isOverline())&&(L=`\xA0`),T=m*s-c.get(L,N.isBold(),N.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(P&&w||!P&&!w&&N.bg===y)&&(P&&w&&p.selectionForeground||N.fg===b)&&N.extended.ext===x&&ee===S&&T===C&&!F&&!A&&!I&&j){N.isInvisible()?_+=fi:_+=L,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=N.bg,b=N.fg,x=N.extended.ext,S=ee,C=T,w=P,A&&a>=k&&a<=M&&(a=k),!this._coreService.isCursorHidden&&F&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`);break;default:break}}if(N.isBold()&&D.push(`xterm-bold`),N.isItalic()&&D.push(`xterm-italic`),N.isDim()&&D.push(`xterm-dim`),_=N.isInvisible()?fi:N.getChars()||fi,N.isUnderline()&&(D.push(`xterm-underline-${N.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!N.isUnderlineColorDefault()))if(N.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${pi.toColorRGB(N.getUnderlineColor()).join(`,`)})`;else{let e=N.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&N.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}N.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),N.isStrikethrough()&&D.push(`xterm-strikethrough`),ee&&(h.style.textDecoration=`underline`);let te=N.getFgColor(),R=N.getFgColorMode(),ne=N.getBgColor(),re=N.getBgColorMode(),z=!!N.isInverse();if(z){let e=te;te=ne,ne=e;let t=R;R=re,re=t}let ie,ae,B=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&B||(e.backgroundColorRGB&&(re=50331648,ne=e.backgroundColorRGB.rgba>>8&16777215,ie=e.backgroundColorRGB),e.foregroundColorRGB&&(R=50331648,te=e.foregroundColorRGB.rgba>>8&16777215,ae=e.foregroundColorRGB),B=e.options.layer===`top`)}),!B&&P&&(ie=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,ne=ie.rgba>>8&16777215,re=50331648,B=!0,p.selectionForeground&&(R=50331648,te=p.selectionForeground.rgba>>8&16777215,ae=p.selectionForeground)),B&&D.push(`xterm-decoration-top`);let oe;switch(re){case 16777216:case 33554432:oe=p.ansi[ne],D.push(`xterm-bg-${ne}`);break;case 50331648:oe=Ac.toColor(ne>>16,ne>>8&255,ne&255),this._addStyle(h,`background-color:#${Gc((ne>>>0).toString(16),`0`,6)}`);break;default:z?(oe=p.foreground,D.push(`xterm-bg-257`)):oe=p.background}switch(ie||N.isDim()&&(ie=jc.multiplyOpacity(oe,.5)),R){case 16777216:case 33554432:N.isBold()&&te<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(te+=8),this._applyMinimumContrast(h,oe,p.ansi[te],N,ie,void 0)||D.push(`xterm-fg-${te}`);break;case 50331648:let e=Ac.toColor(te>>16&255,te>>8&255,te&255);this._applyMinimumContrast(h,oe,e,N,ie,ae)||this._addStyle(h,`color:#${Gc(te.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,oe,p.foreground,N,ie,ae)||z&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!F&&!A&&!I&&j?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=M}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||Vc(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=jc.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};Wc=Yr([q(1,Li),q(2,Ei),q(3,Ni),q(4,Si),q(5,ki),q(6,Ri)],Wc);function Gc(e,t,n){for(;e.length<n;)e=t+e;return e}var Kc=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.createElement(`div`),this._container.classList.add(`xterm-width-cache-measure-container`),this._container.setAttribute(`aria-hidden`,`true`),this._container.style.whiteSpace=`pre`,this._container.style.fontKerning=`none`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},qc=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);if(s>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function Jc(){return new qc}var Yc=`xterm-dom-renderer-owner-`,Xc=`xterm-rows`,Zc=`xterm-fg-`,Qc=`xterm-bg-`,$c=`xterm-focus`,el=`xterm-selection`,tl=1,nl=class extends va{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=tl++,this._rowElements=[],this._selectionRenderModel=Jc(),this.onRequestRedraw=this._register(new Z).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(Xc),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(el),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=Hc(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(Wc,document),this._element.classList.add(Yc+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(ha(()=>{this._element.classList.remove(Yc+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Kc(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Xc} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Xc} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Xc} .xterm-dim { color: ${jc.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Xc}.${$c} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${Xc}.${$c} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Xc}.${$c} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Xc} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Xc} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Xc} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Xc} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Xc} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${el} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${el} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${el} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${Zc}${n} { color: ${r.css}; }${this._terminalSelector} .${Zc}${n}.xterm-dim { color: ${jc.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${Qc}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${Zc}257 { color: ${jc.opaque(e.background).css}; }${this._terminalSelector} .${Zc}257.xterm-dim { color: ${jc.multiplyOpacity(jc.opaque(e.background),.5).css}; }${this._terminalSelector} .${Qc}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove($c),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add($c),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${Yc}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};nl=Yr([q(7,wi),q(8,Mi),q(9,Ei),q(10,Y),q(11,Si),q(12,Ni),q(13,Ri)],nl);var rl=class extends va{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Z),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new ol(this._optionsService))}catch{this._measureStrategy=this._register(new al(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};rl=Yr([q(2,Ei)],rl);var il=class extends va{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},al=class extends il{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},ol=class extends il{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},sl=class extends va{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new cl(this._window)),this._onDprChange=this._register(new Z),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Z),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(ka.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ss(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(Ss(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},cl=class extends va{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new ya),this._onDprChange=this._register(new Z),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ha(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ss(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},ll=class extends va{constructor(){super(),this.linkProviders=[],this._register(ha(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function ul(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function dl(e,t,n,r,i,a,o,s,c){if(!a)return;let l=ul(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var fl=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return dl(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=ul(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};fl=Yr([q(0,Fi),q(1,Mi)],fl);var pl=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},ml={};Jr(ml,{getSafariVersion:()=>xl,isChromeOS:()=>Dl,isFirefox:()=>vl,isIpad:()=>Cl,isIphone:()=>wl,isLegacyEdge:()=>yl,isLinux:()=>El,isMac:()=>Sl,isNode:()=>hl,isSafari:()=>bl,isWindows:()=>Tl});var hl=typeof process<`u`&&`title`in process,gl=hl?`node`:navigator.userAgent,_l=hl?`node`:navigator.platform,vl=gl.includes(`Firefox`),yl=gl.includes(`Edge`),bl=/^((?!chrome|android).)*safari/i.test(gl);function xl(){if(!bl)return 0;let e=gl.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Sl=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(_l),Cl=_l===`iPad`,wl=_l===`iPhone`,Tl=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(_l),El=_l.indexOf(`Linux`)>=0,Dl=/\bCrOS\b/.test(gl),Ol=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},kl=class extends Ol{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Al=class extends Ol{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},jl=!hl&&`requestIdleCallback`in window?Al:kl,Ml=class{constructor(){this._queue=new jl}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Nl=class extends va{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new ya),this._pausedResizeTask=new Ml,this._observerDisposable=this._register(new ya),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new Z),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Z),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Z),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Z),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new pl((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Pl(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ha(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=ha(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};Nl=Yr([q(2,Ei),q(3,Mi),q(4,Si),q(5,ki),q(6,Y),q(7,Ni),q(8,Ri)],Nl);var Pl=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Fl(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return Rl(i,a,e,t,n,r)+zl(a,t,n,r)+Bl(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,ql(Math.abs(i-e),Kl(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return ql(Ll(a>t?e:i,n)+(s-1)*n.cols+1+Il(a>t?i:e,n),Kl(o,r))}function Il(e,t){return e-1}function Ll(e,t){return t.cols-e}function Rl(e,t,n,r,i,a){return zl(t,r,i,a).length===0?``:ql(Gl(e,t,e,t-Hl(t,i),!1,i).length,Kl(`D`,a))}function zl(e,t,n,r){let i=e-Hl(e,n),a=t-Hl(t,n);return ql(Math.abs(i-a)-Vl(e,t,n),Kl(Wl(e,t),r))}function Bl(e,t,n,r,i,a){let o;o=zl(t,r,i,a).length>0?r-Hl(r,i):t;let s=r,c=Ul(e,t,n,r,i,a);return ql(Gl(e,o,n,s,c===`C`,i).length,Kl(c,a))}function Vl(e,t,n){let r=0,i=e-Hl(e,n),a=t-Hl(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=Wl(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function Hl(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function Ul(e,t,n,r,i,a){let o;return o=zl(n,r,i,a).length>0?r-Hl(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function Wl(e,t){return e>t?`A`:`B`}function Gl(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function Kl(e,t){let n=t?`O`:`[`;return Q.ESC+n+e}function ql(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var Jl=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Yl(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var Xl=50,Zl=15,Ql=50,$l=500,eu=RegExp(`\xA0`,`g`),tu=class extends va{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new hi,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Z),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Z),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Z),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Z),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new Jl(this._bufferService),this._activeSelectionMode=0,this._register(ha(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace(eu,` `)).join(Tl?`\r
36
+ `:`
37
+ `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),El&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=Yl(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=ul(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-Xl),Xl),t/=Xl,t/Math.abs(t)+Math.round(t*(Zl-1)))}shouldForceSelection(e){return Sl?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Ql)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Sl&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<$l&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=Fl(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!n){this._oldHasSelection&&this._fireOnSelectionChange(e,t,n);return}!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(!(!t&&o.slice(s,c).trim()===``)){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Yl(n,this._bufferService.cols)}};tu=Yr([q(3,Y),q(4,Si),q(5,Pi),q(6,Ei),q(7,Fi),q(8,Ni)],tu);var nu=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},ru=class{constructor(){this._color=new nu,this._css=new nu}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},iu=Object.freeze((()=>{let e=[Mc.toColor(`#2e3436`),Mc.toColor(`#cc0000`),Mc.toColor(`#4e9a06`),Mc.toColor(`#c4a000`),Mc.toColor(`#3465a4`),Mc.toColor(`#75507b`),Mc.toColor(`#06989a`),Mc.toColor(`#d3d7cf`),Mc.toColor(`#555753`),Mc.toColor(`#ef2929`),Mc.toColor(`#8ae234`),Mc.toColor(`#fce94f`),Mc.toColor(`#729fcf`),Mc.toColor(`#ad7fa8`),Mc.toColor(`#34e2e2`),Mc.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:Ac.toCss(r,i,a),rgba:Ac.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:Ac.toCss(n,n,n),rgba:Ac.toRgba(n,n,n)})}return e})()),au=Mc.toColor(`#ffffff`),ou=Mc.toColor(`#000000`),su=Mc.toColor(`#ffffff`),cu=ou,lu={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},uu=au,du=class extends va{constructor(e){super(),this._optionsService=e,this._contrastCache=new ru,this._halfContrastCache=new ru,this._onChangeColors=this._register(new Z),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:au,background:ou,cursor:su,cursorAccent:cu,selectionForeground:void 0,selectionBackgroundTransparent:lu,selectionBackgroundOpaque:jc.blend(ou,lu),selectionInactiveBackgroundTransparent:lu,selectionInactiveBackgroundOpaque:jc.blend(ou,lu),scrollbarSliderBackground:jc.opacity(au,.2),scrollbarSliderHoverBackground:jc.opacity(au,.4),scrollbarSliderActiveBackground:jc.opacity(au,.5),overviewRulerBorder:au,ansi:iu.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=fu(e.foreground,au),t.background=fu(e.background,ou),t.cursor=jc.blend(t.background,fu(e.cursor,su)),t.cursorAccent=jc.blend(t.background,fu(e.cursorAccent,cu)),t.selectionBackgroundTransparent=fu(e.selectionBackground,lu),t.selectionBackgroundOpaque=jc.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=fu(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=jc.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?fu(e.selectionForeground,kc):void 0,t.selectionForeground===kc&&(t.selectionForeground=void 0),jc.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=jc.opacity(t.selectionBackgroundTransparent,.3)),jc.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=jc.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=fu(e.scrollbarSliderBackground,jc.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=fu(e.scrollbarSliderHoverBackground,jc.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=fu(e.scrollbarSliderActiveBackground,jc.opacity(t.foreground,.5)),t.overviewRulerBorder=fu(e.overviewRulerBorder,uu),t.ansi=iu.slice(),t.ansi[0]=fu(e.black,iu[0]),t.ansi[1]=fu(e.red,iu[1]),t.ansi[2]=fu(e.green,iu[2]),t.ansi[3]=fu(e.yellow,iu[3]),t.ansi[4]=fu(e.blue,iu[4]),t.ansi[5]=fu(e.magenta,iu[5]),t.ansi[6]=fu(e.cyan,iu[6]),t.ansi[7]=fu(e.white,iu[7]),t.ansi[8]=fu(e.brightBlack,iu[8]),t.ansi[9]=fu(e.brightRed,iu[9]),t.ansi[10]=fu(e.brightGreen,iu[10]),t.ansi[11]=fu(e.brightYellow,iu[11]),t.ansi[12]=fu(e.brightBlue,iu[12]),t.ansi[13]=fu(e.brightMagenta,iu[13]),t.ansi[14]=fu(e.brightCyan,iu[14]),t.ansi[15]=fu(e.brightWhite,iu[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=fu(e.extendedAnsi[r],iu[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0){for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];return}switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};du=Yr([q(0,Ei)],du);function fu(e,t){if(e!==void 0)try{return Mc.toColor(e)}catch{}return t}var pu=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},mu=class{constructor(){this._services=new pu,this._services.set(wi,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=J(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},hu={trace:0,debug:1,info:2,warn:3,error:4,off:5},gu=`xterm.js: `,_u=class extends va{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),vu=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=hu[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:gu)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};_u=Yr([q(0,Ei)],_u);var vu,yu=class extends va{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new Z),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new Z),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new Z),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},bu=3,xu=Object.freeze(new pi),Su=0,Cu=2,wu=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*bu);let r=t||hi.fromCharData([0,di,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*bu+0],n=t&2097151;return[this._data[e*bu+1],t&2097152?this._combined[e]:n?si(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*bu+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*bu+0]=e|2097152|t[2]<<22):this._data[e*bu+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*bu+0]>>22}hasWidth(e){return this._data[e*bu+0]&12582912}getFg(e){return this._data[e*bu+1]}getBg(e){return this._data[e*bu+2]}hasContent(e){return this._data[e*bu+0]&4194303}getCodePoint(e){let t=this._data[e*bu+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*bu+0]&2097152}getString(e){let t=this._data[e*bu+0];return t&2097152?this._combined[e]:t&2097151?si(t&2097151):``}isProtected(e){return this._data[e*bu+2]&536870912}loadCell(e,t){return Su=e*bu,t.content=this._data[Su+0],t.fg=this._data[Su+1],t.bg=this._data[Su+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*bu+0]=t.content,this._data[e*bu+1]=t.fg,this._data[e*bu+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*bu+0]=t|n<<22,this._data[e*bu+1]=r.fg,this._data[e*bu+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*bu+0];r&2097152?this._combined[e]+=si(t):r&2097151?(this._combined[e]=si(r&2097151)+si(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*bu+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new hi;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new hi;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r){for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;return}for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*Cu<this._data.buffer.byteLength;let n=e*bu;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*Cu<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*Cu<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t){for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);return}this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*bu+0]&4194303)return e+(this._data[e*bu+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*bu+0]&4194303||this._data[e*bu+2]&50331648)return e+(this._data[e*bu+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<bu;e++)this._data[(n+i)*bu+e]=a[(t+i)*bu+e];a[(t+i)*bu+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<bu;e++)this._data[(n+i)*bu+e]=a[(t+i)*bu+e];a[(t+i)*bu+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*bu+0],n=e&2097151,a=e&2097152?this._combined[t]:n?si(n):fi;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function Tu(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=ku(u,d,t),p=1,m=0;for(;p<u.length;){let e=ku(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function Eu(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function Du(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function Ou(e,t,n){let r=[],i=e.map((n,r)=>ku(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=ku(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function ku(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var Au=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new Z),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),pa(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};Au._nextId=1;var ju=Au,Mu={},Nu=Mu.B;Mu[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:`␤`,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},Mu.A={"#":`£`},Mu.B=void 0,Mu[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},Mu.C=Mu[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Mu.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},Mu.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},Mu.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},Mu.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},Mu.E=Mu[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},Mu.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},Mu.H=Mu[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Mu[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var Pu=4294967295,Fu=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=xu.clone(),this.savedCharset=Nu,this.markers=[],this._nullCell=hi.fromCharData([0,di,1,0]),this._whitespaceCell=hi.fromCharData([0,fi,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new jl,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new yu(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new mi),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new mi),this._whitespaceCell}getBlankLine(e,t){return new wu(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>Pu?Pu:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=xu);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new yu(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(xu),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new wu(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new wu(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=Tu(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(xu),n);if(r.length>0){let n=Eu(this.lines,r);Du(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(xu),i=n;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new wu(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(xu),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=Ou(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(xu,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=ku(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new ju(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Iu=class extends va{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Z),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new Fu(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Fu(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Lu=2,Ru=1,zu=class extends va{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Z),this.onResize=this._onResize.event,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Lu),this.rows=Math.max(e.rawOptions.rows||0,Ru),this.buffers=this._register(new Iu(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};zu=Yr([q(0,Ei)],zu);var Bu={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Sl,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Vu=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],Hu=class extends va{constructor(e){super(),this._onOptionChange=this._register(new Z),this.onOptionChange=this._onOptionChange.event;let t={...Bu};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ha(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in Bu))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Bu))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=Bu[e],!Uu(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=Bu[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Vu.includes(t)?t:Bu[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={};break}return t}};function Uu(e){return e===`block`||e===`underline`||e===`bar`}function Wu(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&Wu(e[r],t-1);return n}var Gu=Object.freeze({insertMode:!1}),Ku=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),qu=class extends va{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Z),this.onData=this._onData.event,this._onUserInput=this._register(new Z),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Z),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Z),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Wu(Gu),this.decPrivateModes=Wu(Ku)}reset(){this.modes=Wu(Gu),this.decPrivateModes=Wu(Ku)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};qu=Yr([q(0,Y),q(1,Ti),q(2,Ei)],qu);var Ju={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function Yu(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var Xu=String.fromCharCode,Zu={DEFAULT:e=>{let t=[Yu(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${Xu(t[0])}${Xu(t[1])}${Xu(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Yu(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Yu(e,!0)};${e.x};${e.y}${t}`}},Qu=class extends va{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Z),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(Ju))this.addProtocol(e,Ju[e]);for(let e of Object.keys(Zu))this.addEncoding(e,Zu[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};Qu=Yr([q(0,Y),q(1,Si),q(2,Ei)],Qu);var $u=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],ed=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],td;function nd(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var rd=class{constructor(){if(this.version=`6`,!td){td=new Uint8Array(65536),td.fill(1),td[0]=0,td.fill(0,1,32),td.fill(0,127,160),td.fill(2,4352,4448),td[9001]=2,td[9002]=2,td.fill(2,11904,42192),td[12351]=1,td.fill(2,44032,55204),td.fill(2,63744,64256),td.fill(2,65040,65050),td.fill(2,65072,65136),td.fill(2,65280,65377),td.fill(2,65504,65511);for(let e=0;e<$u.length;++e)td.fill(0,$u[e][0],$u[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?td[e]:nd(e,ed)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=id.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return id.createPropertyValue(0,n,r)}},id=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new Z,this.onChange=this._onChange.event;let e=new rd;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return(e&1)!=0}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},ad=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function od(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var sd=2147483647,cd=256,ld=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>cd)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>sd?sd:e}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>sd?sd:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,sd):e}},ud=[],dd=class{constructor(){this._state=0,this._active=ud,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=ud}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=ud,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||ud,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,ci(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=ud,this._id=-1,this._state=0}}},fd=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=ci(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},pd=[],md=class{constructor(){this._handlers=Object.create(null),this._active=pd,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=pd}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=pd,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||pd,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,ci(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=pd,this._ident=0}},hd=new ld;hd.addParam(0);var gd=class{constructor(e){this._handler=e,this._data=``,this._params=hd,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():hd,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=ci(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=hd,this._data=``,this._hitLimit=!1,e));return this._params=hd,this._data=``,this._hitLimit=!1,t}},_d=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},vd=160,yd=function(){let e=new _d(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(vd,0,2,0),e.add(vd,8,5,8),e.add(vd,6,0,6),e.add(vd,11,0,11),e.add(vd,13,13,13),e}(),bd=class extends va{constructor(e=yd){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new ld,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(ha(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new dd),this._dcsParser=this._register(new md),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:vd)],i>>4){case 2:for(let i=n+1;;++i){if(i>=t||(r=e[i])<32||r>126&&r<vd){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<vd){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<vd){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<vd){this._printHandler(e,n,i),n=i-1;break}}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<vd){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<vd){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=i&15}}},xd=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,Sd=/^[\da-f]+$/;function Cd(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=xd.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),Sd.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function wd(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function Td(e,t=16){let[n,r,i]=e;return`rgb:${wd(n,t)}/${wd(r,t)}/${wd(i,t)}`}var Ed={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Dd=131072,Od=10;function kd(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Ad=5e3,jd=0,Md=class extends va{constructor(e,t,n,r,i,a,o,s,c=new bd){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new li,this._utf8Decoder=new ui,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=xu.clone(),this._eraseAttrDataInternal=xu.clone(),this._onRequestBell=this._register(new Z),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Z),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Z),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Z),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Z),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Z),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Z),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Z),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Z),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Z),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Z),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Z),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Nd(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler(Q.BEL,()=>this.bell()),this._parser.setExecuteHandler(Q.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(Q.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(Q.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(Q.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(Q.BS,()=>this.backspace()),this._parser.setExecuteHandler(Q.HT,()=>this.tab()),this._parser.setExecuteHandler(Q.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(Q.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Sc.IND,()=>this.index()),this._parser.setExecuteHandler(Sc.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Sc.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new fd(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new fd(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new fd(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new fd(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new fd(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new fd(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new fd(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new fd(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new fd(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new fd(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new fd(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new fd(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in Mu)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new gd((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),Ad))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${Ad} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Dd&&(a=this._parseStack.position+Dd)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<Dd&&(this._parseBuffer=new Uint32Array(Math.min(e.length,Dd))),o||this._dirtyRowTracker.clearRange(),e.length>Dd)for(let t=a;t<e.length;t+=Dd){let a=t+Dd<e.length?t+Dd:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=id.extractWidth(t);let n=id.extractShouldJoin(t),m=n?id.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(si(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof wu&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>kd(e.params[0],this._optionsService.rawOptions.windowOptions)?t(e):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new gd(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new fd(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(xu));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=id.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(Q.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(Q.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(Q.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(Q.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(Q.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0;break}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,Nu),this._charsetService.setgCharset(1,Nu),this._charsetService.setgCharset(2,Nu),this._charsetService.setgCharset(3,Nu);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0;break}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1;break}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0);break}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${Q.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=pi.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=xu.fg,e.bg=xu.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=xu.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=xu.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=xu.fg&16777215,r.bg&=-67108864,r.bg|=xu.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${Q.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${Q.ESC}[${e};${t}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${Q.ESC}[?${e};${t}R`);break;case 15:break;case 25:break;case 26:break;case 53:break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=xu.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`;break}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!kd(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${Q.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Od&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Od&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(Pd(n))if(r===`?`)t.push({type:0,index:n});else{let e=Cd(r);e&&t.push({type:1,index:n,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):n.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=Cd(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);Pd(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,Nu),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(Ed[e[0]],Mu[e[1]]||Nu),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=xu.clone(),this._eraseAttrDataInternal=xu.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new hi;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${Q.ESC}${e}${Q.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Nd=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(jd=e,e=t,t=jd),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Nd=Yr([q(0,Y)],Nd);function Pd(e){return 0<=e&&e<256}var Fd=5e7,Id=12,Ld=50,Rd=class extends va{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Z),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>Fd)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=Id?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=Id)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Ld&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},zd=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};zd=Yr([q(0,Y)],zd);var Bd=!1,Vd=class extends va{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new ya),this._onBinary=this._register(new Z),this.onBinary=this._onBinary.event,this._onData=this._register(new Z),this.onData=this._onData.event,this._onLineFeed=this._register(new Z),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Z),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Z),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Z),this._instantiationService=new mu,this.optionsService=this._register(new Hu(e)),this._instantiationService.setService(Ei,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(zu)),this._instantiationService.setService(Y,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(_u)),this._instantiationService.setService(Ti,this._logService),this.coreService=this._register(this._instantiationService.createInstance(qu)),this._instantiationService.setService(Si,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Qu)),this._instantiationService.setService(xi,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(id)),this._instantiationService.setService(Oi,this.unicodeService),this._charsetService=this._instantiationService.createInstance(ad),this._instantiationService.setService(Ci,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(zd),this._instantiationService.setService(Di,this._oscLinkService),this._inputHandler=this._register(new Md(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(ka.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(ka.forward(this._bufferService.onResize,this._onResize)),this._register(ka.forward(this.coreService.onData,this._onData)),this._register(ka.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new Rd((e,t)=>this._inputHandler.parse(e,t))),this._register(ka.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Z),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Bd&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),Bd=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Lu),t=Math.max(t,Ru),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(od.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(od(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ha(()=>{for(let t of e)t.dispose()})}}},Hd={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function Ud(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?t?i.key=Q.ESC+`OA`:i.key=Q.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?t?i.key=Q.ESC+`OD`:i.key=Q.ESC+`[D`:e.key===`UIKeyInputRightArrow`?t?i.key=Q.ESC+`OC`:i.key=Q.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(t?i.key=Q.ESC+`OB`:i.key=Q.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:Q.DEL,e.altKey&&(i.key=Q.ESC+i.key);break;case 9:if(e.shiftKey){i.key=Q.ESC+`[Z`;break}i.key=Q.HT,i.cancel=!0;break;case 13:i.key=e.altKey?Q.ESC+Q.CR:Q.CR,i.cancel=!0;break;case 27:i.key=Q.ESC,e.altKey&&(i.key=Q.ESC+Q.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;a?i.key=Q.ESC+`[1;`+(a+1)+`D`:t?i.key=Q.ESC+`OD`:i.key=Q.ESC+`[D`;break;case 39:if(e.metaKey)break;a?i.key=Q.ESC+`[1;`+(a+1)+`C`:t?i.key=Q.ESC+`OC`:i.key=Q.ESC+`[C`;break;case 38:if(e.metaKey)break;a?i.key=Q.ESC+`[1;`+(a+1)+`A`:t?i.key=Q.ESC+`OA`:i.key=Q.ESC+`[A`;break;case 40:if(e.metaKey)break;a?i.key=Q.ESC+`[1;`+(a+1)+`B`:t?i.key=Q.ESC+`OB`:i.key=Q.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=Q.ESC+`[2~`);break;case 46:a?i.key=Q.ESC+`[3;`+(a+1)+`~`:i.key=Q.ESC+`[3~`;break;case 36:a?i.key=Q.ESC+`[1;`+(a+1)+`H`:t?i.key=Q.ESC+`OH`:i.key=Q.ESC+`[H`;break;case 35:a?i.key=Q.ESC+`[1;`+(a+1)+`F`:t?i.key=Q.ESC+`OF`:i.key=Q.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:e.ctrlKey?i.key=Q.ESC+`[5;`+(a+1)+`~`:i.key=Q.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:e.ctrlKey?i.key=Q.ESC+`[6;`+(a+1)+`~`:i.key=Q.ESC+`[6~`;break;case 112:a?i.key=Q.ESC+`[1;`+(a+1)+`P`:i.key=Q.ESC+`OP`;break;case 113:a?i.key=Q.ESC+`[1;`+(a+1)+`Q`:i.key=Q.ESC+`OQ`;break;case 114:a?i.key=Q.ESC+`[1;`+(a+1)+`R`:i.key=Q.ESC+`OR`;break;case 115:a?i.key=Q.ESC+`[1;`+(a+1)+`S`:i.key=Q.ESC+`OS`;break;case 116:a?i.key=Q.ESC+`[15;`+(a+1)+`~`:i.key=Q.ESC+`[15~`;break;case 117:a?i.key=Q.ESC+`[17;`+(a+1)+`~`:i.key=Q.ESC+`[17~`;break;case 118:a?i.key=Q.ESC+`[18;`+(a+1)+`~`:i.key=Q.ESC+`[18~`;break;case 119:a?i.key=Q.ESC+`[19;`+(a+1)+`~`:i.key=Q.ESC+`[19~`;break;case 120:a?i.key=Q.ESC+`[20;`+(a+1)+`~`:i.key=Q.ESC+`[20~`;break;case 121:a?i.key=Q.ESC+`[21;`+(a+1)+`~`:i.key=Q.ESC+`[21~`;break;case 122:a?i.key=Q.ESC+`[23;`+(a+1)+`~`:i.key=Q.ESC+`[23~`;break;case 123:a?i.key=Q.ESC+`[24;`+(a+1)+`~`:i.key=Q.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=Q.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=Q.DEL:e.keyCode===219?i.key=Q.ESC:e.keyCode===220?i.key=Q.FS:e.keyCode===221&&(i.key=Q.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=Hd[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=Q.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=Q.ESC+n}else if(e.keyCode===32)i.key=Q.ESC+(e.ctrlKey?Q.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=Q.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=Q.US),e.key===`@`&&(i.key=Q.NUL));break}return i}var Wd=0,Gd=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new jl,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new jl,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Wd=this._search(t),Wd===-1)||this._getKey(this._array[Wd])!==t)return!1;do if(this._array[Wd]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Wd),!0;while(++Wd<this._array.length&&this._getKey(this._array[Wd])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Wd=this._search(e),!(Wd<0||Wd>=this._array.length)&&this._getKey(this._array[Wd])===e))do yield this._array[Wd];while(++Wd<this._array.length&&this._getKey(this._array[Wd])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Wd=this._search(e),!(Wd<0||Wd>=this._array.length)&&this._getKey(this._array[Wd])===e))do t(this._array[Wd]);while(++Wd<this._array.length&&this._getKey(this._array[Wd])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},Kd=0,qd=0,Jd=class extends va{constructor(){super(),this._decorations=new Gd(e=>e?.marker.line),this._onDecorationRegistered=this._register(new Z),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Z),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ha(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Yd(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{Kd=t.options.x??0,qd=Kd+(t.options.width??1),e>=Kd&&e<qd&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},Yd=class extends _a{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new Z),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new Z),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=Mc.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=Mc.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Xd=1e3,Zd=class{constructor(e,t=Xd){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Qd=20,$d=!1,ef=class extends va{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Zd(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);$d?(this._accessibilityContainer.classList.add(`debug`),this._rowContainer.classList.add(`debug`),this._debugRootContainer=i.createElement(`div`),this._debugRootContainer.classList.add(`xterm`),this._debugRootContainer.appendChild(i.createTextNode(`------start a11y------`)),this._debugRootContainer.appendChild(this._accessibilityContainer),this._debugRootContainer.appendChild(i.createTextNode(`------end a11y------`)),this._terminal.element.insertAdjacentElement(`afterend`,this._debugRootContainer)):this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
38
+ `))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Ss(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ha(()=>{$d?this._debugRootContainer.remove():this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<Qd+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
39
+ `&&(this._liveRegionLineCount++,this._liveRegionLineCount===Qd+1&&(this._liveRegion.textContent+=$r.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(!(!a||!o)){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};ef=Yr([q(1,wi),q(2,Ni),q(3,Fi)],ef);var tf=class extends va{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new Z),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new Z),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(ha(()=>{pa(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Ss(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ss(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(Ss(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(Ss(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized){this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&nf(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,pa(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};tf=Yr([q(1,Pi),q(2,Fi),q(3,Y),q(4,zi)],tf);function nf(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var rf=class extends Vd{constructor(e={}){super(e),this._linkifier=this._register(new ya),this.browser=ml,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new ya),this._onCursorMove=this._register(new Z),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Z),this.onKey=this._onKey.event,this._onRender=this._register(new Z),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Z),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Z),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Z),this.onBell=this._onBell.event,this._onFocus=this._register(new Z),this._onBlur=this._register(new Z),this._onA11yCharEmitter=this._register(new Z),this._onA11yTabEmitter=this._register(new Z),this._onWillOpen=this._register(new Z),this._setup(),this._decorationService=this._instantiationService.createInstance(Jd),this._instantiationService.setService(ki,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(ll),this._instantiationService.setService(zi,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Ai)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(ka.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(ka.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(ka.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(ka.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(ha(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=jc.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${Q.ESC}]${n};${Td(r)}${Cc.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=Ac.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=Ac.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(ef,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(Q.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(Q.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(Ss(this.element,`copy`,e=>{this.hasSelection()&&ni(e,this._selectionService)}));let e=e=>ri(e,this.textarea,this.coreService,this.optionsService);this._register(Ss(this.textarea,`paste`,e)),this._register(Ss(this.element,`paste`,e)),vl?this._register(Ss(this.element,`mousedown`,e=>{e.button===2&&oi(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ss(this.element,`contextmenu`,e=>{oi(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),El&&this._register(Ss(this.element,`auxclick`,e=>{e.button===1&&ai(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ss(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(Ss(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(Ss(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(Ss(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(Ss(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(Ss(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(Ss(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(Ss(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,Zr.get()),Dl||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(sl,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(Ni,this._coreBrowserService),this._register(Ss(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(Ss(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(rl,this._document,this._helperContainer),this._instantiationService.setService(Mi,this._charSizeService),this._themeService=this._instantiationService.createInstance(du),this._instantiationService.setService(Ri,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Rc),this._instantiationService.setService(Li,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Nl,this.rows,this.screenElement)),this._instantiationService.setService(Fi,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(wc,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(fl),this._instantiationService.setService(Pi,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(tf,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(hc,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(tu,this.element,this.screenElement,r)),this._instantiationService.setService(Ii,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(ka.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(gc,this.screenElement)),this._register(Ss(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(ef,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(xc,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(xc,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(nl,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Ss(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(e)))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(Ss(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=Q.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){ii(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=Ud(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===Q.ETX||n.key===Q.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(af(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(xu));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent(Q.ESC+`[I`):this.coreService.triggerDataEvent(Q.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${Q.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${Q.ESC}[6;${r};${n}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function af(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var of=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},sf=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new hi)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},cf=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new sf(t)}getNullCell(){return new hi}},lf=class extends va{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Z),this.onBufferChange=this._onBufferChange.event,this._normal=new cf(this._core.buffers.normal,`normal`),this._alternate=new cf(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},uf=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},df=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},ff=[`cols`,`rows`],pf=0,mf=class extends va{constructor(e){super(),this._core=this._register(new rf(e)),this._addonManager=this._register(new of),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(ff.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new uf(this._core),this._parser}get unicode(){return this._checkProposedApi(),new df(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new lf(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`;break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
40
+ `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Zr.get()},set promptLabel(e){Zr.set(e)},get tooMuchOutput(){return $r.get()},set tooMuchOutput(e){$r.set(e)}}}_verifyIntegers(...e){for(pf of e)if(pf===1/0||isNaN(pf)||pf%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(pf of e)if(pf&&(pf===1/0||isNaN(pf)||pf%1!=0||pf<0))throw Error(`This API only accepts positive integers`)}},hf=2,gf=1,_f=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(hf,Math.floor(u/e.css.cell.width)),rows:Math.max(gf,Math.floor(l/e.css.cell.height))}}},vf=`3.7.8`,yf=vf,bf=typeof Buffer==`function`,xf=typeof TextDecoder==`function`?new TextDecoder:void 0,Sf=typeof TextEncoder==`function`?new TextEncoder:void 0,Cf=Array.prototype.slice.call(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=`),wf=(e=>{let t={};return e.forEach((e,n)=>t[e]=n),t})(Cf),Tf=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Ef=String.fromCharCode.bind(String),Df=typeof Uint8Array.from==`function`?Uint8Array.from.bind(Uint8Array):e=>new Uint8Array(Array.prototype.slice.call(e,0)),Of=e=>e.replace(/=/g,``).replace(/[+\/]/g,e=>e==`+`?`-`:`_`),kf=e=>e.replace(/[^A-Za-z0-9\+\/]/g,``),Af=e=>{let t,n,r,i,a=``,o=e.length%3;for(let o=0;o<e.length;){if((n=e.charCodeAt(o++))>255||(r=e.charCodeAt(o++))>255||(i=e.charCodeAt(o++))>255)throw TypeError(`invalid character found`);t=n<<16|r<<8|i,a+=Cf[t>>18&63]+Cf[t>>12&63]+Cf[t>>6&63]+Cf[t&63]}return o?a.slice(0,o-3)+`===`.substring(o):a},jf=typeof btoa==`function`?e=>btoa(e):bf?e=>Buffer.from(e,`binary`).toString(`base64`):Af,Mf=bf?e=>Buffer.from(e).toString(`base64`):e=>{let t=[];for(let n=0,r=e.length;n<r;n+=4096)t.push(Ef.apply(null,e.subarray(n,n+4096)));return jf(t.join(``))},Nf=(e,t=!1)=>t?Of(Mf(e)):Mf(e),Pf=e=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Ef(192|t>>>6)+Ef(128|t&63):Ef(224|t>>>12&15)+Ef(128|t>>>6&63)+Ef(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Ef(240|t>>>18&7)+Ef(128|t>>>12&63)+Ef(128|t>>>6&63)+Ef(128|t&63)}},Ff=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,If=e=>e.replace(Ff,Pf),Lf=bf?e=>Buffer.from(e,`utf8`).toString(`base64`):Sf?e=>Mf(Sf.encode(e)):e=>jf(If(e)),Rf=(e,t=!1)=>t?Of(Lf(e)):Lf(e),zf=e=>Rf(e,!0),Bf=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,Vf=e=>{switch(e.length){case 4:var t=((7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3))-65536;return Ef((t>>>10)+55296)+Ef((t&1023)+56320);case 3:return Ef((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Ef((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},Hf=e=>e.replace(Bf,Vf),Uf=e=>{if(e=e.replace(/\s+/g,``),!Tf.test(e))throw TypeError(`malformed base64.`);e+=`==`.slice(2-(e.length&3));let t,n,r,i=[];for(let a=0;a<e.length;)t=wf[e.charAt(a++)]<<18|wf[e.charAt(a++)]<<12|(n=wf[e.charAt(a++)])<<6|(r=wf[e.charAt(a++)]),n===64?i.push(Ef(t>>16&255)):r===64?i.push(Ef(t>>16&255,t>>8&255)):i.push(Ef(t>>16&255,t>>8&255,t&255));return i.join(``)},Wf=typeof atob==`function`?e=>atob(kf(e)):bf?e=>Buffer.from(e,`base64`).toString(`binary`):Uf,Gf=bf?e=>Df(Buffer.from(e,`base64`)):e=>Df(Wf(e).split(``).map(e=>e.charCodeAt(0))),Kf=e=>Gf(Jf(e)),qf=bf?e=>Buffer.from(e,`base64`).toString(`utf8`):xf?e=>xf.decode(Gf(e)):e=>Hf(Wf(e)),Jf=e=>kf(e.replace(/[-_]/g,e=>e==`-`?`+`:`/`)),Yf=e=>qf(Jf(e)),Xf=e=>{if(typeof e!=`string`)return!1;let t=e.replace(/\s+/g,``).replace(/={0,2}$/,``);return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},Zf=e=>({value:e,enumerable:!1,writable:!0,configurable:!0}),Qf=function(){let e=(e,t)=>Object.defineProperty(String.prototype,e,Zf(t));e(`fromBase64`,function(){return Yf(this)}),e(`toBase64`,function(e){return Rf(this,e)}),e(`toBase64URI`,function(){return Rf(this,!0)}),e(`toBase64URL`,function(){return Rf(this,!0)}),e(`toUint8Array`,function(){return Kf(this)})},$f=function(){let e=(e,t)=>Object.defineProperty(Uint8Array.prototype,e,Zf(t));e(`toBase64`,function(e){return Nf(this,e)}),e(`toBase64URI`,function(){return Nf(this,!0)}),e(`toBase64URL`,function(){return Nf(this,!0)})},ep={version:vf,VERSION:yf,atob:Wf,atobPolyfill:Uf,btoa:jf,btoaPolyfill:Af,fromBase64:Yf,toBase64:Rf,encode:Rf,encodeURI:zf,encodeURL:zf,utob:If,btou:Hf,decode:Yf,isValid:Xf,fromUint8Array:Nf,toUint8Array:Kf,extendString:Qf,extendUint8Array:$f,extendBuiltins:()=>{Qf(),$f()}},tp=class{constructor(e=new rp,t=new np){this._base64=e,this._provider=t}activate(e){this._terminal=e,this._disposable=e.parser.registerOscHandler(52,e=>this._setOrReportClipboard(e))}dispose(){return this._disposable?.dispose()}_readText(e,t){let n=this._base64.encodeText(t);this._terminal?.input(`\x1B]52;${e};${n}\x07`,!1)}_setOrReportClipboard(e){let t=e.split(`;`);if(t.length<2)return!0;let n=t[0],r=t[1];if(r===`?`){let e=this._provider.readText(n);return e instanceof Promise?e.then(e=>(this._readText(n,e),!0)):(this._readText(n,e),!0)}let i=``;try{i=this._base64.decodeText(r)}catch{}let a=this._provider.writeText(n,i);return a instanceof Promise?a.then(()=>!0):!0}},np=class{async readText(e){return e===`c`?navigator.clipboard.readText():Promise.resolve(``)}async writeText(e,t){return e===`c`?navigator.clipboard.writeText(t):Promise.resolve()}},rp=class{encodeText(e){return ep.encode(e)}decodeText(e){let t=ep.decode(e);return!ep.isValid(e)||ep.encode(t)!==e?``:t}},ip=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?lp.isErrorNoTelemetry(e)?new lp(e.message+`
41
+
42
+ `+e.stack):Error(e.message+`
43
+
44
+ `+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function ap(e){sp(e)||ip.onUnexpectedError(e)}var op=`Canceled`;function sp(e){return e instanceof cp?!0:e instanceof Error&&e.name===op&&e.message===op}var cp=class extends Error{constructor(){super(op),this.name=this.message}},lp=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}};function up(e,t,n=0,r=e.length){let i=n,a=r;for(;i<a;){let n=Math.floor((i+a)/2);t(e[n])?i=n+1:a=n}return i-1}var dp=class e{constructor(e){this._array=e,this._findLastMonotonousLastIdx=0}findLastMonotonous(t){if(e.assertInvariants){if(this._prevFindLastPredicate){for(let e of this._array)if(this._prevFindLastPredicate(e)&&!t(e))throw Error(`MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.`)}this._prevFindLastPredicate=t}let n=up(this._array,t,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=n+1,n===-1?void 0:this._array[n]}};dp.assertInvariants=!1;var fp;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(fp||={});function pp(e,t){return(n,r)=>t(e(n),e(r))}var mp=(e,t)=>e-t,hp=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>t(n)?e(n):!0))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>e(n)?(t=n,!1):!0),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||fp.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};hp.empty=new hp(e=>{});function gp(e,t){let n=Object.create(null);for(let r of e){let e=t(r),i=n[e];i||=n[e]=[],i.push(r)}return n}var _p=class{constructor(){this.map=new Map}add(e,t){let n=this.map.get(e);n||(n=new Set,this.map.set(e,n)),n.add(t)}delete(e,t){let n=this.map.get(e);n&&(n.delete(t),n.size===0&&this.map.delete(e))}forEach(e,t){let n=this.map.get(e);n&&n.forEach(t)}get(e){return this.map.get(e)||new Set}};function vp(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var yp;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(yp||={});var bp=!1,xp=null,Sp=class e{constructor(){this.livingDisposables=new Map}getDisposableData(t){let n=this.livingDisposables.get(t);return n||(n={parent:null,source:null,isSingleton:!1,value:t,idx:e.idx++},this.livingDisposables.set(t,n)),n}trackDisposable(e){let t=this.getDisposableData(e);t.source||=Error().stack}setParent(e,t){let n=this.getDisposableData(e);n.parent=t}markAsDisposed(e){this.livingDisposables.delete(e)}markAsSingleton(e){this.getDisposableData(e).isSingleton=!0}getRootParent(e,t){let n=t.get(e);if(n)return n;let r=e.parent?this.getRootParent(this.getDisposableData(e.parent),t):e;return t.set(e,r),r}getTrackedDisposables(){let e=new Map;return[...this.livingDisposables.entries()].filter(([,t])=>t.source!==null&&!this.getRootParent(t,e).isSingleton).flatMap(([e])=>e)}computeLeakingDisposables(e=10,t){let n;if(t)n=t;else{let e=new Map,t=[...this.livingDisposables.values()].filter(t=>t.source!==null&&!this.getRootParent(t,e).isSingleton);if(t.length===0)return;let r=new Set(t.map(e=>e.value));if(n=t.filter(e=>!(e.parent&&r.has(e.parent))),n.length===0)throw Error(`There are cyclic diposable chains!`)}if(!n)return;function r(e){function t(e,t){for(;e.length>0&&t.some(t=>typeof t==`string`?t===e[0]:e[0].match(t));)e.shift()}let n=e.source.split(`
45
+ `).map(e=>e.trim().replace(`at `,``)).filter(e=>e!==``);return t(n,[`Error`,/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),n.reverse()}let i=new _p;for(let e of n){let t=r(e);for(let n=0;n<=t.length;n++)i.add(t.slice(0,n).join(`
46
+ `),e)}n.sort(pp(e=>e.idx,mp));let a=``,o=0;for(let t of n.slice(0,e)){o++;let e=r(t),s=[];for(let t=0;t<e.length;t++){let a=e[t];a=`(shared with ${i.get(e.slice(0,t+1).join(`
47
+ `)).size}/${n.length} leaks) at ${a}`;let o=gp([...i.get(e.slice(0,t).join(`
48
+ `))].map(e=>r(e)[t]),e=>e);delete o[e[t]];for(let[e,t]of Object.entries(o))s.unshift(` - stacktraces of ${t.length} other leaks continue with ${e}`);s.unshift(a)}a+=`
49
+
50
+
51
+ ==================== Leaking disposable ${o}/${n.length}: ${t.value.constructor.name} ====================
52
+ ${s.join(`
53
+ `)}
54
+ ============================================================
55
+
56
+ `}return n.length>e&&(a+=`
57
+
58
+
59
+ ... and ${n.length-e} more leaking disposables
60
+
61
+ `),{leaks:n,details:a}}};Sp.idx=0;function Cp(e){xp=e}if(bp){let e=`__is_disposable_tracked__`;Cp(new class{trackDisposable(t){let n=Error(`Potentially leaked disposable`).stack;setTimeout(()=>{t[e]||console.log(n)},3e3)}setParent(t,n){if(t&&t!==Np.None)try{t[e]=!0}catch{}}markAsDisposed(t){if(t&&t!==Np.None)try{t[e]=!0}catch{}}markAsSingleton(e){}})}function wp(e){return xp?.trackDisposable(e),e}function Tp(e){xp?.markAsDisposed(e)}function Ep(e,t){xp?.setParent(e,t)}function Dp(e,t){if(xp)for(let n of e)xp.setParent(n,t)}function Op(e){if(yp.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function kp(...e){let t=Ap(()=>Op(e));return Dp(e,t),t}function Ap(e){let t=wp({dispose:vp(()=>{Tp(t),e()})});return t}var jp=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,wp(this)}dispose(){this._isDisposed||(Tp(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Op(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return Ep(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),Ep(e,null))}};jp.DISABLE_DISPOSED_WARNING=!1;var Mp=jp,Np=class{constructor(){this._store=new Mp,wp(this),Ep(this._store,this)}dispose(){Tp(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};Np.None=Object.freeze({dispose(){}});var Pp=class{constructor(){this._isDisposed=!1,wp(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&Ep(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,Tp(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&Ep(e,null),e}},Fp=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};Fp.Undefined=new Fp(void 0);var Ip=globalThis.performance&&typeof globalThis.performance.now==`function`,Lp=class e{static create(t){return new e(t)}constructor(e){this._now=Ip&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},Rp=!1,zp=!1,Bp=!1,Vp;(e=>{e.None=()=>Np.None;function t(e){if(Bp){let{onDidAddListener:t}=e,n=qp.create(),r=0;e.onDidAddListener=()=>{++r===2&&(console.warn(`snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here`),n.print()),t?.()}}}function n(e,t){return f(e,()=>{},0,void 0,!0,void 0,t)}e.defer=n;function r(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=r;function i(e,t,n){return u((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=i;function a(e,t,n){return u((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=a;function o(e,t,n){return u((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=o;function s(e){return e}e.signal=s;function c(...e){return(t,n=null,r)=>d(kp(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=c;function l(e,t,n,r){let a=n;return i(e,e=>(a=t(a,e),a),r)}e.reduce=l;function u(e,n){let r,i={onWillAddFirstListener(){r=e(a.fire,a)},onDidRemoveLastListener(){r?.dispose()}};n||t(i);let a=new tm(i);return n?.add(a),a.event}function d(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function f(e,n,r=100,i=!1,a=!1,o,s){let c,l,u,d=0,f,p={leakWarningThreshold:o,onWillAddFirstListener(){c=e(e=>{d++,l=n(l,e),i&&!u&&(m.fire(l),l=void 0),f=()=>{let e=l;l=void 0,u=void 0,(!i||d>1)&&m.fire(e),d=0},typeof r==`number`?(clearTimeout(u),u=setTimeout(f,r)):u===void 0&&(u=0,queueMicrotask(f))})},onWillRemoveListener(){a&&d>0&&f?.()},onDidRemoveLastListener(){f=void 0,c.dispose()}};s||t(p);let m=new tm(p);return s?.add(m),m.event}e.debounce=f;function p(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=p;function m(e,t=(e,t)=>e===t,n){let r=!0,i;return o(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=m;function h(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=h;function g(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new tm({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=g;function _(e,t){return(n,r,i)=>{let a=t(new y);return e(function(e){let t=a.evaluate(e);t!==v&&n.call(r,t)},void 0,i)}}e.chain=_;let v=Symbol(`HaltChainable`);class y{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:v),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:v}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===v)break;return e}}function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new tm({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=b;function x(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new tm({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=x;function S(e){return new Promise(t=>r(e)(t))}e.toPromise=S;function C(e){let t=new tm;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=C;function w(e,t){return e(e=>t.fire(e))}e.forward=w;function T(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=T;class E{constructor(e,n){this._observable=e,this._counter=0,this._hasChanged=!1;let r={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};n||t(r),this.emitter=new tm(r),n&&n.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function D(e,t){return new E(e,t).emitter.event}e.fromObservable=D;function O(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof Mp?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=O})(Vp||={});var Hp=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Lp,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Hp.all=new Set,Hp._idPool=0;var Up=Hp,Wp=-1,Gp=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new Jp(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};Gp._idPool=1;var Kp=Gp,qp=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
62
+ `).slice(2).join(`
63
+ `))}},Jp=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},Yp=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},Xp=0,Zp=class{constructor(e){this.value=e,this.id=Xp++}},Qp=2,$p=(e,t)=>{if(e instanceof Zp)t(e);else for(let n=0;n<e.length;n++){let r=e[n];r&&t(r)}},em;if(Rp){let e=[];setInterval(()=>{e.length!==0&&(console.warn(`[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:`),console.warn(e.join(`
64
+ `)),e.length=0)},3e3),em=new FinalizationRegistry(t=>{typeof t==`string`&&e.push(t)})}var tm=class{constructor(e){this._size=0,this._options=e,this._leakageMon=Wp>0||this._options?.leakWarningThreshold?new Kp(e?.onListenerError??ap,this._options?.leakWarningThreshold??Wp):void 0,this._perfMon=this._options?._profName?new Up(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(zp){let e=this._listeners;queueMicrotask(()=>{$p(e,e=>e.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new Yp(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||ap)(n),Np.None}if(this._disposed)return Np.None;t&&(e=e.bind(t));let r=new Zp(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=qp.create(),i=this._leakageMon.check(r.stack,this._size+1)),zp&&(r.stack=qp.create()),this._listeners?this._listeners instanceof Zp?(this._deliveryQueue??=new nm,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=Ap(()=>{em?.unregister(a),i?.(),this._removeListener(r)});if(n instanceof Mp?n.add(a):Array.isArray(n)&&n.push(a),em){let e=Error().stack.split(`
65
+ `).slice(2,3).join(`
66
+ `).trim(),t=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(e);em.register(a,t?.[2]??e,a)}return a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Qp<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||ap;if(!n){e.value(t);return}try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof Zp)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}this._perfMon?.stop()}hasListeners(){return this._size>0}},nm=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},rm=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),im;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof am?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Vp.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:rm})})(im||={});var am=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?rm:(this._emitter||=new tm,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},om=`en`,sm=!1,cm=!1,lm=om,um,dm=globalThis,fm;typeof dm.vscode<`u`&&typeof dm.vscode.process<`u`?fm=dm.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(fm=process);var pm=typeof fm?.versions?.electron==`string`&&fm?.type===`renderer`;if(typeof fm==`object`){fm.platform,fm.platform,sm=fm.platform===`linux`,sm&&fm.env.SNAP&&fm.env.SNAP_REVISION,fm.env.CI||fm.env.BUILD_ARTIFACTSTAGINGDIRECTORY,lm=om;let e=fm.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,lm=t.resolvedLanguage||om,t.languagePack?.translationsConfigFile}catch{}}else typeof navigator==`object`&&!pm?(um=navigator.userAgent,um.indexOf(`Windows`),um.indexOf(`Macintosh`),(um.indexOf(`Macintosh`)>=0||um.indexOf(`iPad`)>=0||um.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,sm=um.indexOf(`Linux`)>=0,um?.indexOf(`Mobi`),cm=!0,lm=globalThis._VSCODE_NLS_LANGUAGE||om,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);cm&&typeof dm.importScripts==`function`&&dm.origin;var mm=um,hm=lm,gm;(e=>{function t(){return hm}e.value=t;function n(){return hm.length===2?hm===`en`:hm.length>=3?hm[0]===`e`&&hm[1]===`n`&&hm[2]===`-`:!1}e.isDefaultVariant=n;function r(){return hm===`en`}e.isDefault=r})(gm||={});var _m=typeof dm.postMessage==`function`&&!dm.importScripts;(()=>{if(_m){let e=[];dm.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),dm.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var vm=!!(mm&&mm.indexOf(`Chrome`)>=0);mm&&mm.indexOf(`Firefox`),!vm&&mm&&mm.indexOf(`Safari`),mm&&mm.indexOf(`Edg/`),mm&&mm.indexOf(`Android`);function ym(e,t=0,n){let r=setTimeout(()=>{e(),n&&i.dispose()},t),i=Ap(()=>{clearTimeout(r),n?.deleteAndLeak(i)});return n?.add(i),i}(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var bm;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(bm||={});var xm=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new tm,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await Vp.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};xm.EMPTY=xm.fromArray([]);var Sm=class extends Np{constructor(e){super(),this._terminal=e,this._linesCacheTimeout=this._register(new Pp),this._linesCacheDisposables=this._register(new Pp),this._register(Ap(()=>this._destroyLinesCache()))}initLinesCache(){this._linesCache||(this._linesCache=Array(this._terminal.buffer.active.length),this._linesCacheDisposables.value=kp(this._terminal.onLineFeed(()=>this._destroyLinesCache()),this._terminal.onCursorMove(()=>this._destroyLinesCache()),this._terminal.onResize(()=>this._destroyLinesCache()))),this._linesCacheTimeout.value=ym(()=>this._destroyLinesCache(),15e3)}_destroyLinesCache(){this._linesCache=void 0,this._linesCacheDisposables.clear(),this._linesCacheTimeout.clear()}getLineFromCache(e){return this._linesCache?.[e]}setLineInCache(e,t){this._linesCache&&(this._linesCache[e]=t)}translateBufferLineToStringWithWrap(e,t){let n=[],r=[0],i=this._terminal.buffer.active.getLine(e);for(;i;){let a=this._terminal.buffer.active.getLine(e+1),o=a?a.isWrapped:!1,s=i.translateToString(!o&&t);if(o&&a){let e=i.getCell(i.length-1);e&&e.getCode()===0&&e.getWidth()===1&&a.getCell(0)?.getWidth()===2&&(s=s.slice(0,-1))}if(n.push(s),o)r.push(r[r.length-1]+s.length);else break;e++,i=a}return[n.join(``),r]}},Cm=class{get cachedSearchTerm(){return this._cachedSearchTerm}set cachedSearchTerm(e){this._cachedSearchTerm=e}get lastSearchOptions(){return this._lastSearchOptions}set lastSearchOptions(e){this._lastSearchOptions=e}isValidSearchTerm(e){return!!(e&&e.length>0)}didOptionsChange(e){return this._lastSearchOptions?e?this._lastSearchOptions.caseSensitive!==e.caseSensitive||this._lastSearchOptions.regex!==e.regex||this._lastSearchOptions.wholeWord!==e.wholeWord:!1:!0}shouldUpdateHighlighting(e,t){return t?.decorations?this._cachedSearchTerm===void 0||e!==this._cachedSearchTerm||this.didOptionsChange(t):!1}clearCachedTerm(){this._cachedSearchTerm=void 0}reset(){this._cachedSearchTerm=void 0,this._lastSearchOptions=void 0}},wm=class{constructor(e,t){this._terminal=e,this._lineCache=t}find(e,t,n,r){if(!e||e.length===0){this._terminal.clearSelection();return}if(n>this._terminal.cols)throw Error(`Invalid col: ${n} to search in terminal of ${this._terminal.cols} cols`);this._lineCache.initLinesCache();let i={startRow:t,startCol:n},a=this._findInLine(e,i,r);if(!a)for(let n=t+1;n<this._terminal.buffer.active.baseY+this._terminal.rows&&(i.startRow=n,i.startCol=0,a=this._findInLine(e,i,r),!a);n++);return a}findNextWithSelection(e,t,n){if(!e||e.length===0){this._terminal.clearSelection();return}let r=this._terminal.getSelectionPosition();this._terminal.clearSelection();let i=0,a=0;r&&(n===e?(i=r.end.x,a=r.end.y):(i=r.start.x,a=r.start.y)),this._lineCache.initLinesCache();let o={startRow:a,startCol:i},s=this._findInLine(e,o,t);if(!s)for(let n=a+1;n<this._terminal.buffer.active.baseY+this._terminal.rows&&(o.startRow=n,o.startCol=0,s=this._findInLine(e,o,t),!s);n++);if(!s&&a!==0)for(let n=0;n<a&&(o.startRow=n,o.startCol=0,s=this._findInLine(e,o,t),!s);n++);return!s&&r&&(o.startRow=r.start.y,o.startCol=0,s=this._findInLine(e,o,t)),s}findPreviousWithSelection(e,t,n){if(!e||e.length===0){this._terminal.clearSelection();return}let r=this._terminal.getSelectionPosition();this._terminal.clearSelection();let i=this._terminal.buffer.active.baseY+this._terminal.rows-1,a=this._terminal.cols;this._lineCache.initLinesCache();let o={startRow:i,startCol:a},s;if(r&&(o.startRow=i=r.start.y,o.startCol=a=r.start.x,n!==e&&(s=this._findInLine(e,o,t,!1),s||(o.startRow=i=r.end.y,o.startCol=a=r.end.x))),s||=this._findInLine(e,o,t,!0),!s){o.startCol=Math.max(o.startCol,this._terminal.cols);for(let n=i-1;n>=0&&(o.startRow=n,s=this._findInLine(e,o,t,!0),!s);n--);}if(!s&&i!==this._terminal.buffer.active.baseY+this._terminal.rows-1)for(let n=this._terminal.buffer.active.baseY+this._terminal.rows-1;n>=i&&(o.startRow=n,s=this._findInLine(e,o,t,!0),!s);n--);return s}_isWholeWord(e,t,n){return(e===0||` ~!@#$%^&*()+\`-=[]{}|\\;:"',./<>?`.includes(t[e-1]))&&(e+n.length===t.length||` ~!@#$%^&*()+\`-=[]{}|\\;:"',./<>?`.includes(t[e+n.length]))}_findInLine(e,t,n={},r=!1){let i=t.startRow,a=t.startCol;if(this._terminal.buffer.active.getLine(i)?.isWrapped){if(r){t.startCol+=this._terminal.cols;return}return t.startRow--,t.startCol+=this._terminal.cols,this._findInLine(e,t,n)}let o=this._lineCache.getLineFromCache(i);o||(o=this._lineCache.translateBufferLineToStringWithWrap(i,!0),this._lineCache.setLineInCache(i,o));let[s,c]=o,l=this._bufferColsToStringOffset(i,a),u=e,d=s;n.regex||(u=n.caseSensitive?e:e.toLowerCase(),d=n.caseSensitive?s:s.toLowerCase());let f=-1;if(n.regex){let t=RegExp(u,n.caseSensitive?`g`:`gi`),i;if(r)for(;i=t.exec(d.slice(0,l));)f=t.lastIndex-i[0].length,e=i[0],t.lastIndex-=e.length-1;else i=t.exec(d.slice(l)),i&&i[0].length>0&&(f=l+(t.lastIndex-i[0].length),e=i[0])}else r?l-u.length>=0&&(f=d.lastIndexOf(u,l-u.length)):f=d.indexOf(u,l);if(f>=0){if(n.wholeWord&&!this._isWholeWord(f,d,e))return;let t=0;for(;t<c.length-1&&f>=c[t+1];)t++;let r=t;for(;r<c.length-1&&f+e.length>=c[r+1];)r++;let a=f-c[t],o=f+e.length-c[r],s=this._stringLengthToBufferSize(i+t,a),l=this._stringLengthToBufferSize(i+r,o)-s+this._terminal.cols*(r-t);return{term:e,col:s,row:i+t,size:l}}}_stringLengthToBufferSize(e,t){let n=this._terminal.buffer.active.getLine(e);if(!n)return 0;for(let e=0;e<t;e++){let r=n.getCell(e);if(!r)break;let i=r.getChars();i.length>1&&(t-=i.length-1);let a=n.getCell(e+1);a&&a.getWidth()===0&&t++}return t}_bufferColsToStringOffset(e,t){let n=e,r=0,i=this._terminal.buffer.active.getLine(n);for(;t>0&&i;){for(let e=0;e<t&&e<this._terminal.cols;e++){let t=i.getCell(e);if(!t)break;t.getWidth()&&(r+=t.getCode()===0?1:t.getChars().length)}if(n++,i=this._terminal.buffer.active.getLine(n),i&&!i.isWrapped)break;t-=this._terminal.cols}return r}},Tm=class extends Np{constructor(e){super(),this._terminal=e,this._highlightDecorations=[],this._highlightedLines=new Set,this._register(Ap(()=>this.clearHighlightDecorations()))}createHighlightDecorations(e,t){this.clearHighlightDecorations();for(let n of e){let e=this._createResultDecorations(n,t,!1);if(e)for(let t of e)this._storeDecoration(t,n)}}createActiveDecoration(e,t){let n=this._createResultDecorations(e,t,!0);if(n)return{decorations:n,match:e,dispose(){Op(n)}}}clearHighlightDecorations(){Op(this._highlightDecorations),this._highlightDecorations=[],this._highlightedLines.clear()}_storeDecoration(e,t){this._highlightedLines.add(e.marker.line),this._highlightDecorations.push({decoration:e,match:t,dispose(){e.dispose()}})}_applyStyles(e,t,n){e.classList.contains(`xterm-find-result-decoration`)||(e.classList.add(`xterm-find-result-decoration`),t&&(e.style.outline=`1px solid ${t}`)),n&&e.classList.add(`xterm-find-active-result-decoration`)}_createResultDecorations(e,t,n){let r=[],i=e.col,a=e.size,o=-this._terminal.buffer.active.baseY-this._terminal.buffer.active.cursorY+e.row;for(;a>0;){let e=Math.min(this._terminal.cols-i,a);r.push([o,i,e]),i=0,a-=e,o++}let s=[];for(let e of r){let r=this._terminal.registerMarker(e[0]),i=this._terminal.registerDecoration({marker:r,x:e[1],width:e[2],backgroundColor:n?t.activeMatchBackground:t.matchBackground,overviewRulerOptions:this._highlightedLines.has(r.line)?void 0:{color:n?t.activeMatchColorOverviewRuler:t.matchOverviewRuler,position:`center`}});if(i){let e=[];e.push(r),e.push(i.onRender(e=>this._applyStyles(e,n?t.activeMatchBorder:t.matchBorder,!1))),e.push(i.onDispose(()=>Op(e))),s.push(i)}}return s.length===0?void 0:s}},Em=class extends Np{constructor(){super(...arguments),this._searchResults=[],this._onDidChangeResults=this._register(new tm)}get onDidChangeResults(){return this._onDidChangeResults.event}get searchResults(){return this._searchResults}get selectedDecoration(){return this._selectedDecoration}set selectedDecoration(e){this._selectedDecoration=e}updateResults(e,t){this._searchResults=e.slice(0,t)}clearResults(){this._searchResults=[]}clearSelectedDecoration(){this._selectedDecoration&&=(this._selectedDecoration.dispose(),void 0)}findResultIndex(e){for(let t=0;t<this._searchResults.length;t++){let n=this._searchResults[t];if(n.row===e.row&&n.col===e.col&&n.size===e.size)return t}return-1}fireResultsChanged(e){if(!e)return;let t=-1;this._selectedDecoration&&(t=this.findResultIndex(this._selectedDecoration.match)),this._onDidChangeResults.fire({resultIndex:t,resultCount:this._searchResults.length})}reset(){this.clearSelectedDecoration(),this.clearResults()}},Dm=class extends Np{constructor(e){super(),this._highlightTimeout=this._register(new Pp),this._lineCache=this._register(new Pp),this._state=new Cm,this._resultTracker=this._register(new Em),this._highlightLimit=e?.highlightLimit??1e3}get onDidChangeResults(){return this._resultTracker.onDidChangeResults}activate(e){this._terminal=e,this._lineCache.value=new Sm(e),this._engine=new wm(e,this._lineCache.value),this._decorationManager=new Tm(e),this._register(this._terminal.onWriteParsed(()=>this._updateMatches())),this._register(this._terminal.onResize(()=>this._updateMatches())),this._register(Ap(()=>this.clearDecorations()))}_updateMatches(){this._highlightTimeout.clear(),this._state.cachedSearchTerm&&this._state.lastSearchOptions?.decorations&&(this._highlightTimeout.value=ym(()=>{let e=this._state.cachedSearchTerm;this._state.clearCachedTerm(),this.findPrevious(e,{...this._state.lastSearchOptions,incremental:!0},{noScroll:!0})},200))}clearDecorations(e){this._resultTracker.clearSelectedDecoration(),this._decorationManager?.clearHighlightDecorations(),this._resultTracker.clearResults(),e||this._state.clearCachedTerm()}clearActiveDecoration(){this._resultTracker.clearSelectedDecoration()}findNext(e,t,n){if(!this._terminal||!this._engine)throw Error(`Cannot use addon until it has been loaded`);this._state.lastSearchOptions=t,this._state.shouldUpdateHighlighting(e,t)&&this._highlightAllMatches(e,t);let r=this._findNextAndSelect(e,t,n);return this._fireResults(t),this._state.cachedSearchTerm=e,r}_highlightAllMatches(e,t){if(!this._terminal||!this._engine||!this._decorationManager)throw Error(`Cannot use addon until it has been loaded`);if(!this._state.isValidSearchTerm(e)){this.clearDecorations();return}this.clearDecorations(!0);let n=[],r,i=this._engine.find(e,0,0,t);for(;i&&(r?.row!==i.row||r?.col!==i.col)&&!(n.length>=this._highlightLimit);)r=i,n.push(r),i=this._engine.find(e,r.col+r.term.length>=this._terminal.cols?r.row+1:r.row,r.col+r.term.length>=this._terminal.cols?0:r.col+1,t);this._resultTracker.updateResults(n,this._highlightLimit),t.decorations&&this._decorationManager.createHighlightDecorations(n,t.decorations)}_findNextAndSelect(e,t,n){if(!this._terminal||!this._engine)return!1;if(!this._state.isValidSearchTerm(e))return this._terminal.clearSelection(),this.clearDecorations(),!1;let r=this._engine.findNextWithSelection(e,t,this._state.cachedSearchTerm);return this._selectResult(r,t?.decorations,n?.noScroll)}findPrevious(e,t,n){if(!this._terminal||!this._engine)throw Error(`Cannot use addon until it has been loaded`);this._state.lastSearchOptions=t,this._state.shouldUpdateHighlighting(e,t)&&this._highlightAllMatches(e,t);let r=this._findPreviousAndSelect(e,t,n);return this._fireResults(t),this._state.cachedSearchTerm=e,r}_fireResults(e){this._resultTracker.fireResultsChanged(!!e?.decorations)}_findPreviousAndSelect(e,t,n){if(!this._terminal||!this._engine)return!1;if(!this._state.isValidSearchTerm(e))return this._terminal.clearSelection(),this.clearDecorations(),!1;let r=this._engine.findPreviousWithSelection(e,t,this._state.cachedSearchTerm);return this._selectResult(r,t?.decorations,n?.noScroll)}_selectResult(e,t,n){if(!this._terminal||!this._decorationManager)return!1;if(this._resultTracker.clearSelectedDecoration(),!e)return this._terminal.clearSelection(),!1;if(this._terminal.select(e.col,e.row,e.size),t){let n=this._decorationManager.createActiveDecoration(e,t);n&&(this._resultTracker.selectedDecoration=n)}if(!n&&(e.row>=this._terminal.buffer.active.viewportY+this._terminal.rows||e.row<this._terminal.buffer.active.viewportY)){let t=e.row-this._terminal.buffer.active.viewportY;t-=Math.floor(this._terminal.rows/2),this._terminal.scrollLines(t)}return!0}},Om=0,km=0,Am=0,jm=0,Mm;(e=>{function t(e,t,n,r){return r===void 0?`#${Lm(e)}${Lm(t)}${Lm(n)}`:`#${Lm(e)}${Lm(t)}${Lm(n)}${Lm(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(Mm||={});var Nm;(e=>{function t(e,t){if(jm=(t.rgba&255)/255,jm===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return Om=a+Math.round((n-a)*jm),km=o+Math.round((r-o)*jm),Am=s+Math.round((i-s)*jm),{css:Mm.toCss(Om,km,Am),rgba:Mm.toRgba(Om,km,Am)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=Im.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return Mm.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[Om,km,Am]=Im.toChannels(t),{css:Mm.toCss(Om,km,Am),rgba:t}}e.opaque=i;function a(e,t){return jm=Math.round(t*255),[Om,km,Am]=Im.toChannels(e.rgba),{css:Mm.toCss(Om,km,Am,jm),rgba:Mm.toRgba(Om,km,Am,jm)}}e.opacity=a;function o(e,t){return jm=e.rgba&255,a(e,jm*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(Nm||={});var Pm;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return Om=parseInt(e.slice(1,2).repeat(2),16),km=parseInt(e.slice(2,3).repeat(2),16),Am=parseInt(e.slice(3,4).repeat(2),16),Mm.toColor(Om,km,Am);case 5:return Om=parseInt(e.slice(1,2).repeat(2),16),km=parseInt(e.slice(2,3).repeat(2),16),Am=parseInt(e.slice(3,4).repeat(2),16),jm=parseInt(e.slice(4,5).repeat(2),16),Mm.toColor(Om,km,Am,jm);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return Om=parseInt(r[1]),km=parseInt(r[2]),Am=parseInt(r[3]),jm=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),Mm.toColor(Om,km,Am,jm);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[Om,km,Am,jm]=t.getImageData(0,0,1,1).data,jm!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:Mm.toRgba(Om,km,Am,jm),css:e}}e.toColor=r})(Pm||={});var Fm;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(Fm||={});var Im;(e=>{function t(e,t){if(jm=(t&255)/255,jm===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return Om=a+Math.round((n-a)*jm),km=o+Math.round((r-o)*jm),Am=s+Math.round((i-s)*jm),Mm.toRgba(Om,km,Am)}e.blend=t;function n(e,t,n){let a=Fm.relativeLuminance(e>>8),o=Fm.relativeLuminance(t>>8);if(Rm(a,o)<n){if(o<a){let o=r(e,t,n),s=Rm(a,Fm.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>Rm(a,Fm.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=Rm(a,Fm.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>Rm(a,Fm.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Rm(Fm.relativeLuminance2(o,s,c),Fm.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=Rm(Fm.relativeLuminance2(o,s,c),Fm.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Rm(Fm.relativeLuminance2(o,s,c),Fm.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=Rm(Fm.relativeLuminance2(o,s,c),Fm.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(Im||={});function Lm(e){let t=e.toString(16);return t.length<2?`0`+t:t}function Rm(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var zm=Object.freeze((()=>{let e=[Pm.toColor(`#2e3436`),Pm.toColor(`#cc0000`),Pm.toColor(`#4e9a06`),Pm.toColor(`#c4a000`),Pm.toColor(`#3465a4`),Pm.toColor(`#75507b`),Pm.toColor(`#06989a`),Pm.toColor(`#d3d7cf`),Pm.toColor(`#555753`),Pm.toColor(`#ef2929`),Pm.toColor(`#8ae234`),Pm.toColor(`#fce94f`),Pm.toColor(`#729fcf`),Pm.toColor(`#ad7fa8`),Pm.toColor(`#34e2e2`),Pm.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:Mm.toCss(r,i,a),rgba:Mm.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:Mm.toCss(n,n,n),rgba:Mm.toRgba(n,n,n)})}return e})());function Bm(e,t,n){return Math.max(t,Math.min(e,n))}function Vm(e){switch(e){case`&`:return`&amp;`;case`<`:return`&lt;`}return e}var Hm=class{constructor(e){this._buffer=e}serialize(e,t){let n=this._buffer.getNullCell(),r=this._buffer.getNullCell(),i=n,a=e.start.y,o=e.end.y,s=e.start.x,c=e.end.x;this._beforeSerialize(o-a,a,o);for(let t=a;t<=o;t++){let a=this._buffer.getLine(t);if(a){let o=t===e.start.y?s:0,l=t===e.end.y?c:a.length;for(let e=o;e<l;e++){let o=a.getCell(e,i===n?r:n);if(!o){console.warn(`Can't get cell at row=${t}, col=${e}`);continue}this._nextCell(o,i,t,e),i=o}}this._rowEnd(t,t===o)}return this._afterSerialize(),this._serializeString(t)}_nextCell(e,t,n,r){}_rowEnd(e,t){}_beforeSerialize(e,t,n){}_afterSerialize(){}_serializeString(e){return``}};function Um(e,t){return e.getFgColorMode()===t.getFgColorMode()&&e.getFgColor()===t.getFgColor()}function Wm(e,t){return e.getBgColorMode()===t.getBgColorMode()&&e.getBgColor()===t.getBgColor()}function Gm(e,t){return e.isInverse()===t.isInverse()&&e.isBold()===t.isBold()&&e.isUnderline()===t.isUnderline()&&e.isOverline()===t.isOverline()&&e.isBlink()===t.isBlink()&&e.isInvisible()===t.isInvisible()&&e.isItalic()===t.isItalic()&&e.isDim()===t.isDim()&&e.isStrikethrough()===t.isStrikethrough()}var Km=class extends Hm{constructor(e,t){super(e),this._terminal=t,this._rowIndex=0,this._allRows=[],this._allRowSeparators=[],this._currentRow=``,this._nullCellCount=0,this._cursorStyle=this._buffer.getNullCell(),this._cursorStyleRow=0,this._cursorStyleCol=0,this._backgroundCell=this._buffer.getNullCell(),this._firstRow=0,this._lastCursorRow=0,this._lastCursorCol=0,this._lastContentCursorRow=0,this._lastContentCursorCol=0,this._thisRowLastChar=this._buffer.getNullCell(),this._thisRowLastSecondChar=this._buffer.getNullCell(),this._nextRowFirstChar=this._buffer.getNullCell()}_beforeSerialize(e,t,n){this._allRows=Array(e),this._lastContentCursorRow=t,this._lastCursorRow=t,this._firstRow=t}_rowEnd(e,t){this._nullCellCount>0&&!Wm(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let n=``;if(!t){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let t=this._buffer.getLine(e),r=this._buffer.getLine(e+1);if(!r.isWrapped)n=`\r
67
+ `,this._lastCursorRow=e+1,this._lastCursorCol=0;else{n=``;let i=t.getCell(t.length-1,this._thisRowLastChar),a=t.getCell(t.length-2,this._thisRowLastSecondChar),o=r.getCell(0,this._nextRowFirstChar),s=o.getWidth()>1,c=!1;(o.getChars()&&s?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||i.getWidth()===0)&&Wm(i,o)&&(c=!0),s&&(a.getChars()||a.getWidth()===0)&&Wm(i,o)&&Wm(a,o)&&(c=!0)),c||(n=`-`.repeat(this._nullCellCount+1),n+=`\x1B[1D\x1B[1X`,this._nullCellCount>0&&(n+=`\x1B[A`,n+=`\x1B[${t.length-this._nullCellCount}C`,n+=`\x1B[${this._nullCellCount}X`,n+=`\x1B[${t.length-this._nullCellCount}D`,n+=`\x1B[B`),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=n,this._currentRow=``,this._nullCellCount=0}_diffStyle(e,t){let n=[],r=!Um(e,t),i=!Wm(e,t),a=!Gm(e,t);if(r||i||a)if(e.isAttributeDefault())t.isAttributeDefault()||n.push(0);else{if(r){let t=e.getFgColor();e.isFgRGB()?n.push(38,2,t>>>16&255,t>>>8&255,t&255):e.isFgPalette()?t>=16?n.push(38,5,t):n.push(t&8?90+(t&7):30+(t&7)):n.push(39)}if(i){let t=e.getBgColor();e.isBgRGB()?n.push(48,2,t>>>16&255,t>>>8&255,t&255):e.isBgPalette()?t>=16?n.push(48,5,t):n.push(t&8?100+(t&7):40+(t&7)):n.push(49)}a&&(e.isInverse()!==t.isInverse()&&n.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&n.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&n.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&n.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&n.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&n.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&n.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&n.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&n.push(e.isStrikethrough()?9:29))}return n}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,this._cursorStyle);if(i?!Wm(this._cursorStyle,e):a.length>0){this._nullCellCount>0&&(Wm(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r,this._currentRow+=`\x1B[${a.join(`;`)}m`;let e=this._buffer.getLine(n);e!==void 0&&(e.getCell(r,this._cursorStyle),this._cursorStyleRow=n,this._cursorStyleCol=r)}i?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(Wm(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let n=``;for(let e=0;e<t;e++)n+=this._allRows[e],e+1<t&&(n+=this._allRowSeparators[e]);if(!e){let e=this._buffer.baseY+this._buffer.cursorY,t=this._buffer.cursorX;(e!==this._lastCursorRow||t!==this._lastCursorCol)&&((e=>{e>0?n+=`\x1B[${e}B`:e<0&&(n+=`\x1B[${-e}A`)})(e-this._lastCursorRow),(e=>{e>0?n+=`\x1B[${e}C`:e<0&&(n+=`\x1B[${-e}D`)})(t-this._lastCursorCol))}let r=this._terminal._core._inputHandler._curAttrData,i=this._diffStyle(r,this._cursorStyle);return i.length>0&&(n+=`\x1B[${i.join(`;`)}m`),n}},qm=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,n){let r=t.length,i=n===void 0?r:Bm(n+e.rows,0,r);return this._serializeBufferByRange(e,t,{start:r-i,end:r-1},!1)}_serializeBufferByRange(e,t,n,r){return new Km(t,e).serialize({start:{x:0,y:typeof n.start==`number`?n.start:n.start.line},end:{x:e.cols,y:typeof n.end==`number`?n.end:n.end.line}},r)}_serializeBufferAsHTML(e,t){let n=e.buffer.active,r=new Jm(n,e,t),i=t.onlySelection??!1,a=t.range;if(a)return r.serialize({start:{x:a.startCol,y:(a.startLine,a.startLine)},end:{x:e.cols,y:(a.endLine,a.endLine)}});if(!i){let i=n.length,a=t.scrollback,o=a===void 0?i:Bm(a+e.rows,0,i);return r.serialize({start:{x:0,y:i-o},end:{x:e.cols,y:i-1}})}let o=this._terminal?.getSelectionPosition();return o===void 0?``:r.serialize({start:{x:o.start.x,y:o.start.y},end:{x:o.end.x,y:o.end.y}})}_serializeModes(e){let t=``,n=e.modes;if(n.applicationCursorKeysMode&&(t+=`\x1B[?1h`),n.applicationKeypadMode&&(t+=`\x1B[?66h`),n.bracketedPasteMode&&(t+=`\x1B[?2004h`),n.insertMode&&(t+=`\x1B[4h`),n.originMode&&(t+=`\x1B[?6h`),n.reverseWraparoundMode&&(t+=`\x1B[?45h`),n.sendFocusMode&&(t+=`\x1B[?1004h`),n.wraparoundMode===!1&&(t+=`\x1B[?7l`),n.mouseTrackingMode!==`none`)switch(n.mouseTrackingMode){case`x10`:t+=`\x1B[?9h`;break;case`vt200`:t+=`\x1B[?1000h`;break;case`drag`:t+=`\x1B[?1002h`;break;case`any`:t+=`\x1B[?1003h`;break}return t}serialize(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);let t=e?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e?.scrollback);if(!e?.excludeAltBuffer&&this._terminal.buffer.active.type===`alternate`){let e=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);t+=`\x1B[?1049h\x1B[H${e}`}return e?.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}},Jm=class extends Hm{constructor(e,t,n){super(e),this._terminal=t,this._options=n,this._currentRow=``,this._htmlContent=``,t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=zm}_padStart(e,t,n){return t>>=0,n??=` `,e.length>t?e:(t-=e.length,t>n.length&&(n+=n.repeat(t/n.length)),n.slice(0,t)+e)}_beforeSerialize(e,t,n){this._htmlContent+=`<html><body><!--StartFragment--><pre>`;let r=`#000000`,i=`#ffffff`;(this._options.includeGlobalBackground??!1)&&(r=this._terminal.options.theme?.foreground??`#ffffff`,i=this._terminal.options.theme?.background??`#000000`);let a=[];a.push(`color: `+r+`;`),a.push(`background-color: `+i+`;`),a.push(`font-family: `+this._terminal.options.fontFamily+`;`),a.push(`font-size: `+this._terminal.options.fontSize+`px;`),this._htmlContent+=`<div style='`+a.join(` `)+`'>`}_afterSerialize(){this._htmlContent+=`</div>`,this._htmlContent+=`</pre><!--EndFragment--></body></html>`}_rowEnd(e,t){this._htmlContent+=`<div><span>`+this._currentRow+`</span></div>`,this._currentRow=``}_getHexColor(e,t){let n=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return`#`+[n>>16&255,n>>8&255,n&255].map(e=>this._padStart(e.toString(16),2,`0`)).join(``);if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[n].css}_diffStyle(e,t){let n=[],r=!Um(e,t),i=!Wm(e,t),a=!Gm(e,t);if(r||i||a){let t=this._getHexColor(e,!0);t&&n.push(`color: `+t+`;`);let r=this._getHexColor(e,!1);return r&&n.push(`background-color: `+r+`;`),e.isInverse()&&n.push(`color: #000000; background-color: #BFBFBF;`),e.isBold()&&n.push(`font-weight: bold;`),e.isUnderline()&&e.isOverline()?n.push(`text-decoration: overline underline;`):e.isUnderline()?n.push(`text-decoration: underline;`):e.isOverline()&&n.push(`text-decoration: overline;`),e.isBlink()&&n.push(`text-decoration: blink;`),e.isInvisible()&&n.push(`visibility: hidden;`),e.isItalic()&&n.push(`font-style: italic;`),e.isDim()&&n.push(`opacity: 0.5;`),e.isStrikethrough()&&n.push(`text-decoration: line-through;`),n}}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,t);a&&(this._currentRow+=a.length===0?`</span><span>`:`</span><span style='`+a.join(` `)+`'>`),i?this._currentRow+=` `:this._currentRow+=Vm(e.getChars())}_serializeString(){return this._htmlContent}},Ym=Object.defineProperty,Xm=Object.getOwnPropertyDescriptor,Zm=(e,t,n,r)=>{for(var i=r>1?void 0:r?Xm(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&Ym(t,n,i),i},Qm=(e,t)=>(n,r)=>t(n,r,e),$m=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?ih.isErrorNoTelemetry(e)?new ih(e.message+`
68
+
69
+ `+e.stack):Error(e.message+`
70
+
71
+ `+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function eh(e){nh(e)||$m.onUnexpectedError(e)}var th=`Canceled`;function nh(e){return e instanceof rh?!0:e instanceof Error&&e.name===th&&e.message===th}var rh=class extends Error{constructor(){super(th),this.name=this.message}},ih=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}};function ah(e,t,n=0,r=e.length){let i=n,a=r;for(;i<a;){let n=Math.floor((i+a)/2);t(e[n])?i=n+1:a=n}return i-1}var oh=class e{constructor(e){this._array=e,this._findLastMonotonousLastIdx=0}findLastMonotonous(t){if(e.assertInvariants){if(this._prevFindLastPredicate){for(let e of this._array)if(this._prevFindLastPredicate(e)&&!t(e))throw Error(`MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.`)}this._prevFindLastPredicate=t}let n=ah(this._array,t,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=n+1,n===-1?void 0:this._array[n]}};oh.assertInvariants=!1;var sh;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(sh||={});function ch(e,t){return(n,r)=>t(e(n),e(r))}var lh=(e,t)=>e-t,uh=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>t(n)?e(n):!0))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>e(n)?(t=n,!1):!0),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||sh.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};uh.empty=new uh(e=>{});function dh(e,t){let n=Object.create(null);for(let r of e){let e=t(r),i=n[e];i||=n[e]=[],i.push(r)}return n}var fh=class{constructor(){this.map=new Map}add(e,t){let n=this.map.get(e);n||(n=new Set,this.map.set(e,n)),n.add(t)}delete(e,t){let n=this.map.get(e);n&&(n.delete(t),n.size===0&&this.map.delete(e))}forEach(e,t){let n=this.map.get(e);n&&n.forEach(t)}get(e){return this.map.get(e)||new Set}};function ph(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var mh;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(mh||={});var hh=!1,gh=null,_h=class e{constructor(){this.livingDisposables=new Map}getDisposableData(t){let n=this.livingDisposables.get(t);return n||(n={parent:null,source:null,isSingleton:!1,value:t,idx:e.idx++},this.livingDisposables.set(t,n)),n}trackDisposable(e){let t=this.getDisposableData(e);t.source||=Error().stack}setParent(e,t){let n=this.getDisposableData(e);n.parent=t}markAsDisposed(e){this.livingDisposables.delete(e)}markAsSingleton(e){this.getDisposableData(e).isSingleton=!0}getRootParent(e,t){let n=t.get(e);if(n)return n;let r=e.parent?this.getRootParent(this.getDisposableData(e.parent),t):e;return t.set(e,r),r}getTrackedDisposables(){let e=new Map;return[...this.livingDisposables.entries()].filter(([,t])=>t.source!==null&&!this.getRootParent(t,e).isSingleton).flatMap(([e])=>e)}computeLeakingDisposables(e=10,t){let n;if(t)n=t;else{let e=new Map,t=[...this.livingDisposables.values()].filter(t=>t.source!==null&&!this.getRootParent(t,e).isSingleton);if(t.length===0)return;let r=new Set(t.map(e=>e.value));if(n=t.filter(e=>!(e.parent&&r.has(e.parent))),n.length===0)throw Error(`There are cyclic diposable chains!`)}if(!n)return;function r(e){function t(e,t){for(;e.length>0&&t.some(t=>typeof t==`string`?t===e[0]:e[0].match(t));)e.shift()}let n=e.source.split(`
72
+ `).map(e=>e.trim().replace(`at `,``)).filter(e=>e!==``);return t(n,[`Error`,/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),n.reverse()}let i=new fh;for(let e of n){let t=r(e);for(let n=0;n<=t.length;n++)i.add(t.slice(0,n).join(`
73
+ `),e)}n.sort(ch(e=>e.idx,lh));let a=``,o=0;for(let t of n.slice(0,e)){o++;let e=r(t),s=[];for(let t=0;t<e.length;t++){let a=e[t];a=`(shared with ${i.get(e.slice(0,t+1).join(`
74
+ `)).size}/${n.length} leaks) at ${a}`;let o=dh([...i.get(e.slice(0,t).join(`
75
+ `))].map(e=>r(e)[t]),e=>e);delete o[e[t]];for(let[e,t]of Object.entries(o))s.unshift(` - stacktraces of ${t.length} other leaks continue with ${e}`);s.unshift(a)}a+=`
76
+
77
+
78
+ ==================== Leaking disposable ${o}/${n.length}: ${t.value.constructor.name} ====================
79
+ ${s.join(`
80
+ `)}
81
+ ============================================================
82
+
83
+ `}return n.length>e&&(a+=`
84
+
85
+
86
+ ... and ${n.length-e} more leaking disposables
87
+
88
+ `),{leaks:n,details:a}}};_h.idx=0;function vh(e){gh=e}if(hh){let e=`__is_disposable_tracked__`;vh(new class{trackDisposable(t){let n=Error(`Potentially leaked disposable`).stack;setTimeout(()=>{t[e]||console.log(n)},3e3)}setParent(t,n){if(t&&t!==Oh.None)try{t[e]=!0}catch{}}markAsDisposed(t){if(t&&t!==Oh.None)try{t[e]=!0}catch{}}markAsSingleton(e){}})}function yh(e){return gh?.trackDisposable(e),e}function bh(e){gh?.markAsDisposed(e)}function xh(e,t){gh?.setParent(e,t)}function Sh(e,t){if(gh)for(let n of e)gh.setParent(n,t)}function Ch(e){if(mh.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function wh(...e){let t=Th(()=>Ch(e));return Sh(e,t),t}function Th(e){let t=yh({dispose:ph(()=>{bh(t),e()})});return t}var Eh=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,yh(this)}dispose(){this._isDisposed||(bh(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Ch(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return xh(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),xh(e,null))}};Eh.DISABLE_DISPOSED_WARNING=!1;var Dh=Eh,Oh=class{constructor(){this._store=new Dh,yh(this),xh(this._store,this)}dispose(){bh(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};Oh.None=Object.freeze({dispose(){}});var kh=class{constructor(){this._isDisposed=!1,yh(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&xh(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,bh(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&xh(e,null),e}},Ah=typeof process<`u`&&`title`in process,jh=Ah?`node`:navigator.userAgent,Mh=Ah?`node`:navigator.platform,Nh=jh.includes(`Firefox`),Ph=jh.includes(`Edge`),Fh=/^((?!chrome|android).)*safari/i.test(jh);function Ih(){if(!Fh)return 0;let e=jh.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(Mh),[`Windows`,`Win16`,`Win32`,`WinCE`].includes(Mh),Mh.indexOf(`Linux`),/\bCrOS\b/.test(jh);var Lh=``,Rh=0,zh=0,Bh=0,Vh=0,Hh={css:`#00000000`,rgba:0},Uh;(e=>{function t(e,t,n,r){return r===void 0?`#${Jh(e)}${Jh(t)}${Jh(n)}`:`#${Jh(e)}${Jh(t)}${Jh(n)}${Jh(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(Uh||={});var Wh;(e=>{function t(e,t){if(Vh=(t.rgba&255)/255,Vh===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return Rh=a+Math.round((n-a)*Vh),zh=o+Math.round((r-o)*Vh),Bh=s+Math.round((i-s)*Vh),{css:Uh.toCss(Rh,zh,Bh),rgba:Uh.toRgba(Rh,zh,Bh)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=qh.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return Uh.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[Rh,zh,Bh]=qh.toChannels(t),{css:Uh.toCss(Rh,zh,Bh),rgba:t}}e.opaque=i;function a(e,t){return Vh=Math.round(t*255),[Rh,zh,Bh]=qh.toChannels(e.rgba),{css:Uh.toCss(Rh,zh,Bh,Vh),rgba:Uh.toRgba(Rh,zh,Bh,Vh)}}e.opacity=a;function o(e,t){return Vh=e.rgba&255,a(e,Vh*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(Wh||={});var Gh;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return Rh=parseInt(e.slice(1,2).repeat(2),16),zh=parseInt(e.slice(2,3).repeat(2),16),Bh=parseInt(e.slice(3,4).repeat(2),16),Uh.toColor(Rh,zh,Bh);case 5:return Rh=parseInt(e.slice(1,2).repeat(2),16),zh=parseInt(e.slice(2,3).repeat(2),16),Bh=parseInt(e.slice(3,4).repeat(2),16),Vh=parseInt(e.slice(4,5).repeat(2),16),Uh.toColor(Rh,zh,Bh,Vh);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return Rh=parseInt(r[1]),zh=parseInt(r[2]),Bh=parseInt(r[3]),Vh=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),Uh.toColor(Rh,zh,Bh,Vh);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[Rh,zh,Bh,Vh]=t.getImageData(0,0,1,1).data,Vh!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:Uh.toRgba(Rh,zh,Bh,Vh),css:e}}e.toColor=r})(Gh||={});var Kh;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(Kh||={});var qh;(e=>{function t(e,t){if(Vh=(t&255)/255,Vh===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return Rh=a+Math.round((n-a)*Vh),zh=o+Math.round((r-o)*Vh),Bh=s+Math.round((i-s)*Vh),Uh.toRgba(Rh,zh,Bh)}e.blend=t;function n(e,t,n){let a=Kh.relativeLuminance(e>>8),o=Kh.relativeLuminance(t>>8);if(Yh(a,o)<n){if(o<a){let o=r(e,t,n),s=Yh(a,Kh.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>Yh(a,Kh.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=Yh(a,Kh.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>Yh(a,Kh.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Yh(Kh.relativeLuminance2(o,s,c),Kh.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=Yh(Kh.relativeLuminance2(o,s,c),Kh.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Yh(Kh.relativeLuminance2(o,s,c),Kh.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=Yh(Kh.relativeLuminance2(o,s,c),Kh.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(qh||={});function Jh(e){let t=e.toString(16);return t.length<2?`0`+t:t}function Yh(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}function Xh(e){if(!e)throw Error(`value must not be falsy`);return e}function Zh(e){return 57508<=e&&e<=57558}function Qh(e){return 57520<=e&&e<=57527}function $h(e){return 57344<=e&&e<=63743}function eg(e){return 9472<=e&&e<=9631}function tg(e){return e>=128512&&e<=128591||e>=127744&&e<=128511||e>=128640&&e<=128767||e>=9728&&e<=9983||e>=9984&&e<=10175||e>=65024&&e<=65039||e>=129280&&e<=129535||e>=127462&&e<=127487}function ng(e,t,n,r){return t===1&&n>Math.ceil(r*1.5)&&e!==void 0&&e>255&&!tg(e)&&!Zh(e)&&!$h(e)}function rg(e){return Zh(e)||eg(e)}function ig(){return{css:{canvas:ag(),cell:ag()},device:{canvas:ag(),cell:ag(),char:{width:0,height:0,left:0,top:0}}}}function ag(){return{width:0,height:0}}function og(e,t,n=0){return(e-(Math.round(t)*2-n))%(Math.round(t)*2)}var sg=0,cg=0,lg=!1,ug=!1,dg=!1,fg,pg=0,mg=class{constructor(e,t,n,r,i,a){this._terminal=e,this._optionService=t,this._selectionRenderModel=n,this._decorationService=r,this._coreBrowserService=i,this._themeService=a,this.result={fg:0,bg:0,ext:0}}resolve(e,t,n,r){if(this.result.bg=e.bg,this.result.fg=e.fg,this.result.ext=e.bg&268435456?e.extended.ext:0,cg=0,sg=0,ug=!1,lg=!1,dg=!1,fg=this._themeService.colors,pg=0,e.getCode()!==0&&e.extended.underlineStyle===4){let e=Math.max(1,Math.floor(this._optionService.rawOptions.fontSize*this._coreBrowserService.dpr/15));pg=t*r%(Math.round(e)*2)}if(this._decorationService.forEachDecorationAtCell(t,n,`bottom`,e=>{e.backgroundColorRGB&&(cg=e.backgroundColorRGB.rgba>>8&16777215,ug=!0),e.foregroundColorRGB&&(sg=e.foregroundColorRGB.rgba>>8&16777215,lg=!0)}),dg=this._selectionRenderModel.isCellSelected(this._terminal,t,n),dg){if(this.result.fg&67108864||this.result.bg&50331648){if(this.result.fg&67108864)switch(this.result.fg&50331648){case 16777216:case 33554432:cg=this._themeService.colors.ansi[this.result.fg&255].rgba;break;case 50331648:cg=(this.result.fg&16777215)<<8|255;break;case 0:default:cg=this._themeService.colors.foreground.rgba}else switch(this.result.bg&50331648){case 16777216:case 33554432:cg=this._themeService.colors.ansi[this.result.bg&255].rgba;break;case 50331648:cg=(this.result.bg&16777215)<<8|255;break}cg=qh.blend(cg,(this._coreBrowserService.isFocused?fg.selectionBackgroundOpaque:fg.selectionInactiveBackgroundOpaque).rgba&4294967040|128)>>8&16777215}else cg=(this._coreBrowserService.isFocused?fg.selectionBackgroundOpaque:fg.selectionInactiveBackgroundOpaque).rgba>>8&16777215;if(ug=!0,fg.selectionForeground&&(sg=fg.selectionForeground.rgba>>8&16777215,lg=!0),rg(e.getCode())){if(this.result.fg&67108864&&!(this.result.bg&50331648))sg=(this._coreBrowserService.isFocused?fg.selectionBackgroundOpaque:fg.selectionInactiveBackgroundOpaque).rgba>>8&16777215;else{if(this.result.fg&67108864)switch(this.result.bg&50331648){case 16777216:case 33554432:sg=this._themeService.colors.ansi[this.result.bg&255].rgba;break;case 50331648:sg=(this.result.bg&16777215)<<8|255;break}else switch(this.result.fg&50331648){case 16777216:case 33554432:sg=this._themeService.colors.ansi[this.result.fg&255].rgba;break;case 50331648:sg=(this.result.fg&16777215)<<8|255;break;case 0:default:sg=this._themeService.colors.foreground.rgba}sg=qh.blend(sg,(this._coreBrowserService.isFocused?fg.selectionBackgroundOpaque:fg.selectionInactiveBackgroundOpaque).rgba&4294967040|128)>>8&16777215}lg=!0}}this._decorationService.forEachDecorationAtCell(t,n,`top`,e=>{e.backgroundColorRGB&&(cg=e.backgroundColorRGB.rgba>>8&16777215,ug=!0),e.foregroundColorRGB&&(sg=e.foregroundColorRGB.rgba>>8&16777215,lg=!0)}),ug&&(cg=dg?e.bg&-150994944|cg|50331648:e.bg&-16777216|cg|50331648),lg&&(sg=e.fg&-83886080|sg|50331648),this.result.fg&67108864&&(ug&&!lg&&(sg=this.result.bg&50331648?this.result.fg&-134217728|this.result.bg&67108863:this.result.fg&-134217728|fg.background.rgba>>8&16777215|50331648,lg=!0),!ug&&lg&&(cg=this.result.fg&50331648?this.result.bg&-67108864|this.result.fg&67108863:this.result.bg&-67108864|fg.foreground.rgba>>8&16777215|50331648,ug=!0)),fg=void 0,this.result.bg=ug?cg:this.result.bg,this.result.fg=lg?sg:this.result.fg,this.result.ext&=536870911,this.result.ext|=pg<<29&3758096384}},hg=.5,gg=Nh||Ph?`bottom`:`ideographic`,_g={"▀":[{x:0,y:0,w:8,h:4}],"▁":[{x:0,y:7,w:8,h:1}],"▂":[{x:0,y:6,w:8,h:2}],"▃":[{x:0,y:5,w:8,h:3}],"▄":[{x:0,y:4,w:8,h:4}],"▅":[{x:0,y:3,w:8,h:5}],"▆":[{x:0,y:2,w:8,h:6}],"▇":[{x:0,y:1,w:8,h:7}],"█":[{x:0,y:0,w:8,h:8}],"▉":[{x:0,y:0,w:7,h:8}],"▊":[{x:0,y:0,w:6,h:8}],"▋":[{x:0,y:0,w:5,h:8}],"▌":[{x:0,y:0,w:4,h:8}],"▍":[{x:0,y:0,w:3,h:8}],"▎":[{x:0,y:0,w:2,h:8}],"▏":[{x:0,y:0,w:1,h:8}],"▐":[{x:4,y:0,w:4,h:8}],"▔":[{x:0,y:0,w:8,h:1}],"▕":[{x:7,y:0,w:1,h:8}],"▖":[{x:0,y:4,w:4,h:4}],"▗":[{x:4,y:4,w:4,h:4}],"▘":[{x:0,y:0,w:4,h:4}],"▙":[{x:0,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}],"▚":[{x:0,y:0,w:4,h:4},{x:4,y:4,w:4,h:4}],"▛":[{x:0,y:0,w:4,h:8},{x:4,y:0,w:4,h:4}],"▜":[{x:0,y:0,w:8,h:4},{x:4,y:0,w:4,h:8}],"▝":[{x:4,y:0,w:4,h:4}],"▞":[{x:4,y:0,w:4,h:4},{x:0,y:4,w:4,h:4}],"▟":[{x:4,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}],"🭰":[{x:1,y:0,w:1,h:8}],"🭱":[{x:2,y:0,w:1,h:8}],"🭲":[{x:3,y:0,w:1,h:8}],"🭳":[{x:4,y:0,w:1,h:8}],"🭴":[{x:5,y:0,w:1,h:8}],"🭵":[{x:6,y:0,w:1,h:8}],"🭶":[{x:0,y:1,w:8,h:1}],"🭷":[{x:0,y:2,w:8,h:1}],"🭸":[{x:0,y:3,w:8,h:1}],"🭹":[{x:0,y:4,w:8,h:1}],"🭺":[{x:0,y:5,w:8,h:1}],"🭻":[{x:0,y:6,w:8,h:1}],"🭼":[{x:0,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}],"🭽":[{x:0,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}],"🭾":[{x:7,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}],"🭿":[{x:7,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}],"🮀":[{x:0,y:0,w:8,h:1},{x:0,y:7,w:8,h:1}],"🮁":[{x:0,y:0,w:8,h:1},{x:0,y:2,w:8,h:1},{x:0,y:4,w:8,h:1},{x:0,y:7,w:8,h:1}],"🮂":[{x:0,y:0,w:8,h:2}],"🮃":[{x:0,y:0,w:8,h:3}],"🮄":[{x:0,y:0,w:8,h:5}],"🮅":[{x:0,y:0,w:8,h:6}],"🮆":[{x:0,y:0,w:8,h:7}],"🮇":[{x:6,y:0,w:2,h:8}],"🮈":[{x:5,y:0,w:3,h:8}],"🮉":[{x:3,y:0,w:5,h:8}],"🮊":[{x:2,y:0,w:6,h:8}],"🮋":[{x:1,y:0,w:7,h:8}],"🮕":[{x:0,y:0,w:2,h:2},{x:4,y:0,w:2,h:2},{x:2,y:2,w:2,h:2},{x:6,y:2,w:2,h:2},{x:0,y:4,w:2,h:2},{x:4,y:4,w:2,h:2},{x:2,y:6,w:2,h:2},{x:6,y:6,w:2,h:2}],"🮖":[{x:2,y:0,w:2,h:2},{x:6,y:0,w:2,h:2},{x:0,y:2,w:2,h:2},{x:4,y:2,w:2,h:2},{x:2,y:4,w:2,h:2},{x:6,y:4,w:2,h:2},{x:0,y:6,w:2,h:2},{x:4,y:6,w:2,h:2}],"🮗":[{x:0,y:2,w:8,h:2},{x:0,y:6,w:8,h:2}]},vg={"░":[[1,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]],"▒":[[1,0],[0,0],[0,1],[0,0]],"▓":[[0,1],[1,1],[1,0],[1,1]]},yg={"─":{1:`M0,.5 L1,.5`},"━":{3:`M0,.5 L1,.5`},"│":{1:`M.5,0 L.5,1`},"┃":{3:`M.5,0 L.5,1`},"┌":{1:`M0.5,1 L.5,.5 L1,.5`},"┏":{3:`M0.5,1 L.5,.5 L1,.5`},"┐":{1:`M0,.5 L.5,.5 L.5,1`},"┓":{3:`M0,.5 L.5,.5 L.5,1`},"└":{1:`M.5,0 L.5,.5 L1,.5`},"┗":{3:`M.5,0 L.5,.5 L1,.5`},"┘":{1:`M.5,0 L.5,.5 L0,.5`},"┛":{3:`M.5,0 L.5,.5 L0,.5`},"├":{1:`M.5,0 L.5,1 M.5,.5 L1,.5`},"┣":{3:`M.5,0 L.5,1 M.5,.5 L1,.5`},"┤":{1:`M.5,0 L.5,1 M.5,.5 L0,.5`},"┫":{3:`M.5,0 L.5,1 M.5,.5 L0,.5`},"┬":{1:`M0,.5 L1,.5 M.5,.5 L.5,1`},"┳":{3:`M0,.5 L1,.5 M.5,.5 L.5,1`},"┴":{1:`M0,.5 L1,.5 M.5,.5 L.5,0`},"┻":{3:`M0,.5 L1,.5 M.5,.5 L.5,0`},"┼":{1:`M0,.5 L1,.5 M.5,0 L.5,1`},"╋":{3:`M0,.5 L1,.5 M.5,0 L.5,1`},"╴":{1:`M.5,.5 L0,.5`},"╸":{3:`M.5,.5 L0,.5`},"╵":{1:`M.5,.5 L.5,0`},"╹":{3:`M.5,.5 L.5,0`},"╶":{1:`M.5,.5 L1,.5`},"╺":{3:`M.5,.5 L1,.5`},"╷":{1:`M.5,.5 L.5,1`},"╻":{3:`M.5,.5 L.5,1`},"═":{1:(e,t)=>`M0,${.5-t} L1,${.5-t} M0,${.5+t} L1,${.5+t}`},"║":{1:(e,t)=>`M${.5-e},0 L${.5-e},1 M${.5+e},0 L${.5+e},1`},"╒":{1:(e,t)=>`M.5,1 L.5,${.5-t} L1,${.5-t} M.5,${.5+t} L1,${.5+t}`},"╓":{1:(e,t)=>`M${.5-e},1 L${.5-e},.5 L1,.5 M${.5+e},.5 L${.5+e},1`},"╔":{1:(e,t)=>`M1,${.5-t} L${.5-e},${.5-t} L${.5-e},1 M1,${.5+t} L${.5+e},${.5+t} L${.5+e},1`},"╕":{1:(e,t)=>`M0,${.5-t} L.5,${.5-t} L.5,1 M0,${.5+t} L.5,${.5+t}`},"╖":{1:(e,t)=>`M${.5+e},1 L${.5+e},.5 L0,.5 M${.5-e},.5 L${.5-e},1`},"╗":{1:(e,t)=>`M0,${.5+t} L${.5-e},${.5+t} L${.5-e},1 M0,${.5-t} L${.5+e},${.5-t} L${.5+e},1`},"╘":{1:(e,t)=>`M.5,0 L.5,${.5+t} L1,${.5+t} M.5,${.5-t} L1,${.5-t}`},"╙":{1:(e,t)=>`M1,.5 L${.5-e},.5 L${.5-e},0 M${.5+e},.5 L${.5+e},0`},"╚":{1:(e,t)=>`M1,${.5-t} L${.5+e},${.5-t} L${.5+e},0 M1,${.5+t} L${.5-e},${.5+t} L${.5-e},0`},"╛":{1:(e,t)=>`M0,${.5+t} L.5,${.5+t} L.5,0 M0,${.5-t} L.5,${.5-t}`},"╜":{1:(e,t)=>`M0,.5 L${.5+e},.5 L${.5+e},0 M${.5-e},.5 L${.5-e},0`},"╝":{1:(e,t)=>`M0,${.5-t} L${.5-e},${.5-t} L${.5-e},0 M0,${.5+t} L${.5+e},${.5+t} L${.5+e},0`},"╞":{1:(e,t)=>`M.5,0 L.5,1 M.5,${.5-t} L1,${.5-t} M.5,${.5+t} L1,${.5+t}`},"╟":{1:(e,t)=>`M${.5-e},0 L${.5-e},1 M${.5+e},0 L${.5+e},1 M${.5+e},.5 L1,.5`},"╠":{1:(e,t)=>`M${.5-e},0 L${.5-e},1 M1,${.5+t} L${.5+e},${.5+t} L${.5+e},1 M1,${.5-t} L${.5+e},${.5-t} L${.5+e},0`},"╡":{1:(e,t)=>`M.5,0 L.5,1 M0,${.5-t} L.5,${.5-t} M0,${.5+t} L.5,${.5+t}`},"╢":{1:(e,t)=>`M0,.5 L${.5-e},.5 M${.5-e},0 L${.5-e},1 M${.5+e},0 L${.5+e},1`},"╣":{1:(e,t)=>`M${.5+e},0 L${.5+e},1 M0,${.5+t} L${.5-e},${.5+t} L${.5-e},1 M0,${.5-t} L${.5-e},${.5-t} L${.5-e},0`},"╤":{1:(e,t)=>`M0,${.5-t} L1,${.5-t} M0,${.5+t} L1,${.5+t} M.5,${.5+t} L.5,1`},"╥":{1:(e,t)=>`M0,.5 L1,.5 M${.5-e},.5 L${.5-e},1 M${.5+e},.5 L${.5+e},1`},"╦":{1:(e,t)=>`M0,${.5-t} L1,${.5-t} M0,${.5+t} L${.5-e},${.5+t} L${.5-e},1 M1,${.5+t} L${.5+e},${.5+t} L${.5+e},1`},"╧":{1:(e,t)=>`M.5,0 L.5,${.5-t} M0,${.5-t} L1,${.5-t} M0,${.5+t} L1,${.5+t}`},"╨":{1:(e,t)=>`M0,.5 L1,.5 M${.5-e},.5 L${.5-e},0 M${.5+e},.5 L${.5+e},0`},"╩":{1:(e,t)=>`M0,${.5+t} L1,${.5+t} M0,${.5-t} L${.5-e},${.5-t} L${.5-e},0 M1,${.5-t} L${.5+e},${.5-t} L${.5+e},0`},"╪":{1:(e,t)=>`M.5,0 L.5,1 M0,${.5-t} L1,${.5-t} M0,${.5+t} L1,${.5+t}`},"╫":{1:(e,t)=>`M0,.5 L1,.5 M${.5-e},0 L${.5-e},1 M${.5+e},0 L${.5+e},1`},"╬":{1:(e,t)=>`M0,${.5+t} L${.5-e},${.5+t} L${.5-e},1 M1,${.5+t} L${.5+e},${.5+t} L${.5+e},1 M0,${.5-t} L${.5-e},${.5-t} L${.5-e},0 M1,${.5-t} L${.5+e},${.5-t} L${.5+e},0`},"╱":{1:`M1,0 L0,1`},"╲":{1:`M0,0 L1,1`},"╳":{1:`M1,0 L0,1 M0,0 L1,1`},"╼":{1:`M.5,.5 L0,.5`,3:`M.5,.5 L1,.5`},"╽":{1:`M.5,.5 L.5,0`,3:`M.5,.5 L.5,1`},"╾":{1:`M.5,.5 L1,.5`,3:`M.5,.5 L0,.5`},"╿":{1:`M.5,.5 L.5,1`,3:`M.5,.5 L.5,0`},"┍":{1:`M.5,.5 L.5,1`,3:`M.5,.5 L1,.5`},"┎":{1:`M.5,.5 L1,.5`,3:`M.5,.5 L.5,1`},"┑":{1:`M.5,.5 L.5,1`,3:`M.5,.5 L0,.5`},"┒":{1:`M.5,.5 L0,.5`,3:`M.5,.5 L.5,1`},"┕":{1:`M.5,.5 L.5,0`,3:`M.5,.5 L1,.5`},"┖":{1:`M.5,.5 L1,.5`,3:`M.5,.5 L.5,0`},"┙":{1:`M.5,.5 L.5,0`,3:`M.5,.5 L0,.5`},"┚":{1:`M.5,.5 L0,.5`,3:`M.5,.5 L.5,0`},"┝":{1:`M.5,0 L.5,1`,3:`M.5,.5 L1,.5`},"┞":{1:`M0.5,1 L.5,.5 L1,.5`,3:`M.5,.5 L.5,0`},"┟":{1:`M.5,0 L.5,.5 L1,.5`,3:`M.5,.5 L.5,1`},"┠":{1:`M.5,.5 L1,.5`,3:`M.5,0 L.5,1`},"┡":{1:`M.5,.5 L.5,1`,3:`M.5,0 L.5,.5 L1,.5`},"┢":{1:`M.5,.5 L.5,0`,3:`M0.5,1 L.5,.5 L1,.5`},"┥":{1:`M.5,0 L.5,1`,3:`M.5,.5 L0,.5`},"┦":{1:`M0,.5 L.5,.5 L.5,1`,3:`M.5,.5 L.5,0`},"┧":{1:`M.5,0 L.5,.5 L0,.5`,3:`M.5,.5 L.5,1`},"┨":{1:`M.5,.5 L0,.5`,3:`M.5,0 L.5,1`},"┩":{1:`M.5,.5 L.5,1`,3:`M.5,0 L.5,.5 L0,.5`},"┪":{1:`M.5,.5 L.5,0`,3:`M0,.5 L.5,.5 L.5,1`},"┭":{1:`M0.5,1 L.5,.5 L1,.5`,3:`M.5,.5 L0,.5`},"┮":{1:`M0,.5 L.5,.5 L.5,1`,3:`M.5,.5 L1,.5`},"┯":{1:`M.5,.5 L.5,1`,3:`M0,.5 L1,.5`},"┰":{1:`M0,.5 L1,.5`,3:`M.5,.5 L.5,1`},"┱":{1:`M.5,.5 L1,.5`,3:`M0,.5 L.5,.5 L.5,1`},"┲":{1:`M.5,.5 L0,.5`,3:`M0.5,1 L.5,.5 L1,.5`},"┵":{1:`M.5,0 L.5,.5 L1,.5`,3:`M.5,.5 L0,.5`},"┶":{1:`M.5,0 L.5,.5 L0,.5`,3:`M.5,.5 L1,.5`},"┷":{1:`M.5,.5 L.5,0`,3:`M0,.5 L1,.5`},"┸":{1:`M0,.5 L1,.5`,3:`M.5,.5 L.5,0`},"┹":{1:`M.5,.5 L1,.5`,3:`M.5,0 L.5,.5 L0,.5`},"┺":{1:`M.5,.5 L0,.5`,3:`M.5,0 L.5,.5 L1,.5`},"┽":{1:`M.5,0 L.5,1 M.5,.5 L1,.5`,3:`M.5,.5 L0,.5`},"┾":{1:`M.5,0 L.5,1 M.5,.5 L0,.5`,3:`M.5,.5 L1,.5`},"┿":{1:`M.5,0 L.5,1`,3:`M0,.5 L1,.5`},"╀":{1:`M0,.5 L1,.5 M.5,.5 L.5,1`,3:`M.5,.5 L.5,0`},"╁":{1:`M.5,.5 L.5,0 M0,.5 L1,.5`,3:`M.5,.5 L.5,1`},"╂":{1:`M0,.5 L1,.5`,3:`M.5,0 L.5,1`},"╃":{1:`M0.5,1 L.5,.5 L1,.5`,3:`M.5,0 L.5,.5 L0,.5`},"╄":{1:`M0,.5 L.5,.5 L.5,1`,3:`M.5,0 L.5,.5 L1,.5`},"╅":{1:`M.5,0 L.5,.5 L1,.5`,3:`M0,.5 L.5,.5 L.5,1`},"╆":{1:`M.5,0 L.5,.5 L0,.5`,3:`M0.5,1 L.5,.5 L1,.5`},"╇":{1:`M.5,.5 L.5,1`,3:`M.5,.5 L.5,0 M0,.5 L1,.5`},"╈":{1:`M.5,.5 L.5,0`,3:`M0,.5 L1,.5 M.5,.5 L.5,1`},"╉":{1:`M.5,.5 L1,.5`,3:`M.5,0 L.5,1 M.5,.5 L0,.5`},"╊":{1:`M.5,.5 L0,.5`,3:`M.5,0 L.5,1 M.5,.5 L1,.5`},"╌":{1:`M.1,.5 L.4,.5 M.6,.5 L.9,.5`},"╍":{3:`M.1,.5 L.4,.5 M.6,.5 L.9,.5`},"┄":{1:`M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5`},"┅":{3:`M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5`},"┈":{1:`M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5`},"┉":{3:`M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5`},"╎":{1:`M.5,.1 L.5,.4 M.5,.6 L.5,.9`},"╏":{3:`M.5,.1 L.5,.4 M.5,.6 L.5,.9`},"┆":{1:`M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333`},"┇":{3:`M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333`},"┊":{1:`M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95`},"┋":{3:`M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95`},"╭":{1:(e,t)=>`M.5,1 L.5,${.5+t/.15*.5} C.5,${.5+t/.15*.5},.5,.5,1,.5`},"╮":{1:(e,t)=>`M.5,1 L.5,${.5+t/.15*.5} C.5,${.5+t/.15*.5},.5,.5,0,.5`},"╯":{1:(e,t)=>`M.5,0 L.5,${.5-t/.15*.5} C.5,${.5-t/.15*.5},.5,.5,0,.5`},"╰":{1:(e,t)=>`M.5,0 L.5,${.5-t/.15*.5} C.5,${.5-t/.15*.5},.5,.5,1,.5`}},bg={"":{d:`M.3,1 L.03,1 L.03,.88 C.03,.82,.06,.78,.11,.73 C.15,.7,.2,.68,.28,.65 L.43,.6 C.49,.58,.53,.56,.56,.53 C.59,.5,.6,.47,.6,.43 L.6,.27 L.4,.27 L.69,.1 L.98,.27 L.78,.27 L.78,.46 C.78,.52,.76,.56,.72,.61 C.68,.66,.63,.67,.56,.7 L.48,.72 C.42,.74,.38,.76,.35,.78 C.32,.8,.31,.84,.31,.88 L.31,1 M.3,.5 L.03,.59 L.03,.09 L.3,.09 L.3,.655`,type:0},"":{d:`M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.355,.03 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5`,type:0},"":{d:`M.25,.94 C.16,.94,.11,.92,.11,.87 L.11,.53 C.11,.48,.15,.455,.23,.45 L.23,.3 C.23,.25,.26,.22,.31,.19 C.36,.16,.43,.15,.51,.15 C.59,.15,.66,.16,.71,.19 C.77,.22,.79,.26,.79,.3 L.79,.45 C.87,.45,.91,.48,.91,.53 L.91,.87 C.91,.92,.86,.94,.77,.94 L.24,.94 M.53,.2 C.49,.2,.45,.21,.42,.23 C.39,.25,.38,.27,.38,.3 L.38,.45 L.68,.45 L.68,.3 C.68,.27,.67,.25,.64,.23 C.61,.21,.58,.2,.53,.2 M.58,.82 L.58,.66 C.63,.65,.65,.63,.65,.6 C.65,.58,.64,.57,.61,.56 C.58,.55,.56,.54,.52,.54 C.48,.54,.46,.55,.43,.56 C.4,.57,.39,.59,.39,.6 C.39,.63,.41,.64,.46,.66 L.46,.82 L.57,.82`,type:0},"":{d:`M0,0 L1,.5 L0,1`,type:0,rightPadding:2},"":{d:`M-1,-.5 L1,.5 L-1,1.5`,type:1,leftPadding:1,rightPadding:1},"":{d:`M1,0 L0,.5 L1,1`,type:0,leftPadding:2},"":{d:`M2,-.5 L0,.5 L2,1.5`,type:1,leftPadding:1,rightPadding:1},"":{d:`M0,0 L0,1 C0.552,1,1,0.776,1,.5 C1,0.224,0.552,0,0,0`,type:0,rightPadding:1},"":{d:`M.2,1 C.422,1,.8,.826,.78,.5 C.8,.174,0.422,0,.2,0`,type:1,rightPadding:1},"":{d:`M1,0 L1,1 C0.448,1,0,0.776,0,.5 C0,0.224,0.448,0,1,0`,type:0,leftPadding:1},"":{d:`M.8,1 C0.578,1,0.2,.826,.22,.5 C0.2,0.174,0.578,0,0.8,0`,type:1,leftPadding:1},"":{d:`M-.5,-.5 L1.5,1.5 L-.5,1.5`,type:0},"":{d:`M-.5,-.5 L1.5,1.5`,type:1,leftPadding:1,rightPadding:1},"":{d:`M1.5,-.5 L-.5,1.5 L1.5,1.5`,type:0},"":{d:`M1.5,-.5 L-.5,1.5 L-.5,-.5`,type:0},"":{d:`M1.5,-.5 L-.5,1.5`,type:1,leftPadding:1,rightPadding:1},"":{d:`M-.5,-.5 L1.5,1.5 L1.5,-.5`,type:0}};bg[``]=bg[``],bg[``]=bg[``];function xg(e,t,n,r,i,a,o,s){let c=_g[t];if(c)return Sg(e,c,n,r,i,a),!0;let l=vg[t];if(l)return wg(e,l,n,r,i,a),!0;let u=yg[t];if(u)return Tg(e,u,n,r,i,a,s),!0;let d=bg[t];return d?(Eg(e,d,n,r,i,a,o,s),!0):!1}function Sg(e,t,n,r,i,a){for(let o=0;o<t.length;o++){let s=t[o],c=i/8,l=a/8;e.fillRect(n+s.x*c,r+s.y*l,s.w*c,s.h*l)}}var Cg=new Map;function wg(e,t,n,r,i,a){let o=Cg.get(t);o||(o=new Map,Cg.set(t,o));let s=e.fillStyle;if(typeof s!=`string`)throw Error(`Unexpected fillStyle type "${s}"`);let c=o.get(s);if(!c){let n=t[0].length,r=t.length,i=e.canvas.ownerDocument.createElement(`canvas`);i.width=n,i.height=r;let a=Xh(i.getContext(`2d`)),l=new ImageData(n,r),u,d,f,p;if(s.startsWith(`#`))u=parseInt(s.slice(1,3),16),d=parseInt(s.slice(3,5),16),f=parseInt(s.slice(5,7),16),p=s.length>7&&parseInt(s.slice(7,9),16)||1;else if(s.startsWith(`rgba`))[u,d,f,p]=s.substring(5,s.length-1).split(`,`).map(e=>parseFloat(e));else throw Error(`Unexpected fillStyle color format "${s}" when drawing pattern glyph`);for(let e=0;e<r;e++)for(let r=0;r<n;r++)l.data[(e*n+r)*4]=u,l.data[(e*n+r)*4+1]=d,l.data[(e*n+r)*4+2]=f,l.data[(e*n+r)*4+3]=t[e][r]*(p*255);a.putImageData(l,0,0),c=Xh(e.createPattern(i,null)),o.set(s,c)}e.fillStyle=c,e.fillRect(n,r,i,a)}function Tg(e,t,n,r,i,a,o){e.strokeStyle=e.fillStyle;for(let[s,c]of Object.entries(t)){e.beginPath(),e.lineWidth=o*Number.parseInt(s);let t;t=typeof c==`function`?c(.15,.15/a*i):c;for(let s of t.split(` `)){let t=s[0],c=Og[t];if(!c){console.error(`Could not find drawing instructions for "${t}"`);continue}let l=s.substring(1).split(`,`);!l[0]||!l[1]||c(e,kg(l,i,a,n,r,!0,o))}e.stroke(),e.closePath()}}function Eg(e,t,n,r,i,a,o,s){let c=new Path2D;c.rect(n,r,i,a),e.clip(c),e.beginPath();let l=o/12;e.lineWidth=s*l;for(let o of t.d.split(` `)){let c=o[0],u=Og[c];if(!u){console.error(`Could not find drawing instructions for "${c}"`);continue}let d=o.substring(1).split(`,`);!d[0]||!d[1]||u(e,kg(d,i,a,n,r,!1,s,(t.leftPadding??0)*(l/2),(t.rightPadding??0)*(l/2)))}t.type===1?(e.strokeStyle=e.fillStyle,e.stroke()):e.fill(),e.closePath()}function Dg(e,t,n=0){return Math.max(Math.min(e,t),n)}var Og={C:(e,t)=>e.bezierCurveTo(t[0],t[1],t[2],t[3],t[4],t[5]),L:(e,t)=>e.lineTo(t[0],t[1]),M:(e,t)=>e.moveTo(t[0],t[1])};function kg(e,t,n,r,i,a,o,s=0,c=0){let l=e.map(e=>parseFloat(e)||parseInt(e));if(l.length<2)throw Error(`Too few arguments for instruction`);for(let e=0;e<l.length;e+=2)l[e]*=t-s*o-c*o,a&&l[e]!==0&&(l[e]=Dg(Math.round(l[e]+.5)-.5,t,0)),l[e]+=r+s*o;for(let e=1;e<l.length;e+=2)l[e]*=n,a&&l[e]!==0&&(l[e]=Dg(Math.round(l[e]+.5)-.5,n,0)),l[e]+=i;return l}var Ag=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},jg=class{constructor(){this._data=new Ag}set(e,t,n,r,i){this._data.get(e,t)||this._data.set(e,t,new Ag),this._data.get(e,t).set(n,r,i)}get(e,t,n,r){return this._data.get(e,t)?.get(n,r)}clear(){this._data.clear()}},Mg=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},Ng=class extends Mg{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Pg=class extends Mg{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Fg=!Ah&&`requestIdleCallback`in window?Pg:Ng,Ig=class e{constructor(){this.fg=0,this.bg=0,this.extended=new Lg}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return(this.fg&50331648)==0}isBgDefault(){return(this.bg&50331648)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Lg=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Rg=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};Rg.Undefined=new Rg(void 0);var zg=globalThis.performance&&typeof globalThis.performance.now==`function`,Bg=class e{static create(t){return new e(t)}constructor(e){this._now=zg&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},Vg=!1,Hg=!1,Ug=!1,Wg;(e=>{e.None=()=>Oh.None;function t(e){if(Ug){let{onDidAddListener:t}=e,n=Xg.create(),r=0;e.onDidAddListener=()=>{++r===2&&(console.warn(`snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here`),n.print()),t?.()}}}function n(e,t){return f(e,()=>{},0,void 0,!0,void 0,t)}e.defer=n;function r(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=r;function i(e,t,n){return u((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=i;function a(e,t,n){return u((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=a;function o(e,t,n){return u((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=o;function s(e){return e}e.signal=s;function c(...e){return(t,n=null,r)=>d(wh(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=c;function l(e,t,n,r){let a=n;return i(e,e=>(a=t(a,e),a),r)}e.reduce=l;function u(e,n){let r,i={onWillAddFirstListener(){r=e(a.fire,a)},onDidRemoveLastListener(){r?.dispose()}};n||t(i);let a=new i_(i);return n?.add(a),a.event}function d(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function f(e,n,r=100,i=!1,a=!1,o,s){let c,l,u,d=0,f,p={leakWarningThreshold:o,onWillAddFirstListener(){c=e(e=>{d++,l=n(l,e),i&&!u&&(m.fire(l),l=void 0),f=()=>{let e=l;l=void 0,u=void 0,(!i||d>1)&&m.fire(e),d=0},typeof r==`number`?(clearTimeout(u),u=setTimeout(f,r)):u===void 0&&(u=0,queueMicrotask(f))})},onWillRemoveListener(){a&&d>0&&f?.()},onDidRemoveLastListener(){f=void 0,c.dispose()}};s||t(p);let m=new i_(p);return s?.add(m),m.event}e.debounce=f;function p(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=p;function m(e,t=(e,t)=>e===t,n){let r=!0,i;return o(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=m;function h(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=h;function g(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new i_({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=g;function _(e,t){return(n,r,i)=>{let a=t(new y);return e(function(e){let t=a.evaluate(e);t!==v&&n.call(r,t)},void 0,i)}}e.chain=_;let v=Symbol(`HaltChainable`);class y{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:v),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:v}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===v)break;return e}}function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new i_({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=b;function x(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new i_({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=x;function S(e){return new Promise(t=>r(e)(t))}e.toPromise=S;function C(e){let t=new i_;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=C;function w(e,t){return e(e=>t.fire(e))}e.forward=w;function T(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=T;class E{constructor(e,n){this._observable=e,this._counter=0,this._hasChanged=!1;let r={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};n||t(r),this.emitter=new i_(r),n&&n.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function D(e,t){return new E(e,t).emitter.event}e.fromObservable=D;function O(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof Dh?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=O})(Wg||={});var Gg=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Bg,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Gg.all=new Set,Gg._idPool=0;var Kg=Gg,qg=-1,Jg=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new Zg(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};Jg._idPool=1;var Yg=Jg,Xg=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
89
+ `).slice(2).join(`
90
+ `))}},Zg=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},Qg=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},$g=0,e_=class{constructor(e){this.value=e,this.id=$g++}},t_=2,n_=(e,t)=>{if(e instanceof e_)t(e);else for(let n=0;n<e.length;n++){let r=e[n];r&&t(r)}},r_;if(Vg){let e=[];setInterval(()=>{e.length!==0&&(console.warn(`[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:`),console.warn(e.join(`
91
+ `)),e.length=0)},3e3),r_=new FinalizationRegistry(t=>{typeof t==`string`&&e.push(t)})}var i_=class{constructor(e){this._size=0,this._options=e,this._leakageMon=qg>0||this._options?.leakWarningThreshold?new Yg(e?.onListenerError??eh,this._options?.leakWarningThreshold??qg):void 0,this._perfMon=this._options?._profName?new Kg(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(Hg){let e=this._listeners;queueMicrotask(()=>{n_(e,e=>e.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new Qg(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||eh)(n),Oh.None}if(this._disposed)return Oh.None;t&&(e=e.bind(t));let r=new e_(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Xg.create(),i=this._leakageMon.check(r.stack,this._size+1)),Hg&&(r.stack=Xg.create()),this._listeners?this._listeners instanceof e_?(this._deliveryQueue??=new a_,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=Th(()=>{r_?.unregister(a),i?.(),this._removeListener(r)});if(n instanceof Dh?n.add(a):Array.isArray(n)&&n.push(a),r_){let e=Error().stack.split(`
92
+ `).slice(2,3).join(`
93
+ `).trim(),t=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(e);r_.register(a,t?.[2]??e,a)}return a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*t_<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||eh;if(!n){e.value(t);return}try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof e_)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}this._perfMon?.stop()}hasListeners(){return this._size>0}},a_=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},o_={texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},offset:{x:0,y:0},size:{x:0,y:0},sizeClipSpace:{x:0,y:0}},s_=2,c_,l_=class e{constructor(e,t,n){this._document=e,this._config=t,this._unicodeService=n,this._didWarmUp=!1,this._cacheMap=new jg,this._cacheMapCombined=new jg,this._pages=[],this._activePages=[],this._workBoundingBox={top:0,left:0,bottom:0,right:0},this._workAttributeData=new Ig,this._textureSize=512,this._onAddTextureAtlasCanvas=new i_,this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=new i_,this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._requestClearModel=!1,this._createNewPage(),this._tmpCanvas=p_(e,this._config.deviceCellWidth*4+s_*2,this._config.deviceCellHeight+s_*2),this._tmpCtx=Xh(this._tmpCanvas.getContext(`2d`,{alpha:this._config.allowTransparency,willReadFrequently:!0}))}get pages(){return this._pages}dispose(){this._tmpCanvas.remove();for(let e of this.pages)e.canvas.remove();this._onAddTextureAtlasCanvas.dispose()}warmUp(){this._didWarmUp||=(this._doWarmUp(),!0)}_doWarmUp(){let e=new Fg;for(let t=33;t<126;t++)e.enqueue(()=>{if(!this._cacheMap.get(t,0,0,0)){let e=this._drawToCache(t,0,0,0,!1,void 0);this._cacheMap.set(t,0,0,0,e)}})}beginFrame(){return this._requestClearModel}clearTexture(){if(!(this._pages[0].currentRow.x===0&&this._pages[0].currentRow.y===0)){for(let e of this._pages)e.clear();this._cacheMap.clear(),this._cacheMapCombined.clear(),this._didWarmUp=!1}}_createNewPage(){if(e.maxAtlasPages&&this._pages.length>=Math.max(4,e.maxAtlasPages)){let t=this._pages.filter(t=>t.canvas.width*2<=(e.maxTextureSize||4096)).sort((e,t)=>t.canvas.width===e.canvas.width?t.percentageUsed-e.percentageUsed:t.canvas.width-e.canvas.width),n=-1,r=0;for(let e=0;e<t.length;e++)if(t[e].canvas.width!==r)n=e,r=t[e].canvas.width;else if(e-n===3)break;let i=t.slice(n,n+4),a=i.map(e=>e.glyphs[0].texturePage).sort((e,t)=>e>t?1:-1),o=this.pages.length-i.length,s=this._mergePages(i,o);s.version++;for(let e=a.length-1;e>=0;e--)this._deletePage(a[e]);this.pages.push(s),this._requestClearModel=!0,this._onAddTextureAtlasCanvas.fire(s.canvas)}let t=new u_(this._document,this._textureSize);return this._pages.push(t),this._activePages.push(t),this._onAddTextureAtlasCanvas.fire(t.canvas),t}_mergePages(e,t){let n=e[0].canvas.width*2,r=new u_(this._document,n,e);for(let[i,a]of e.entries()){let e=i*a.canvas.width%n,o=Math.floor(i/2)*a.canvas.height;r.ctx.drawImage(a.canvas,e,o);for(let r of a.glyphs)r.texturePage=t,r.sizeClipSpace.x=r.size.x/n,r.sizeClipSpace.y=r.size.y/n,r.texturePosition.x+=e,r.texturePosition.y+=o,r.texturePositionClipSpace.x=r.texturePosition.x/n,r.texturePositionClipSpace.y=r.texturePosition.y/n;this._onRemoveTextureAtlasCanvas.fire(a.canvas);let s=this._activePages.indexOf(a);s!==-1&&this._activePages.splice(s,1)}return r}_deletePage(e){this._pages.splice(e,1);for(let t=e;t<this._pages.length;t++){let e=this._pages[t];for(let t of e.glyphs)t.texturePage--;e.version++}}getRasterizedGlyphCombinedChar(e,t,n,r,i,a){return this._getFromCacheMap(this._cacheMapCombined,e,t,n,r,i,a)}getRasterizedGlyph(e,t,n,r,i,a){return this._getFromCacheMap(this._cacheMap,e,t,n,r,i,a)}_getFromCacheMap(e,t,n,r,i,a,o){return c_=e.get(t,n,r,i),c_||(c_=this._drawToCache(t,n,r,i,a,o),e.set(t,n,r,i,c_)),c_}_getColorFromAnsiIndex(e){if(e>=this._config.colors.ansi.length)throw Error(`No color found for idx `+e);return this._config.colors.ansi[e]}_getBackgroundColor(e,t,n,r){if(this._config.allowTransparency)return Hh;let i;switch(e){case 16777216:case 33554432:i=this._getColorFromAnsiIndex(t);break;case 50331648:let e=Ig.toColorRGB(t);i=Uh.toColor(e[0],e[1],e[2]);break;default:i=n?Wh.opaque(this._config.colors.foreground):this._config.colors.background;break}return this._config.allowTransparency||(i=Wh.opaque(i)),i}_getForegroundColor(e,t,n,r,i,a,o,s,c,l){let u=this._getMinimumContrastColor(e,t,n,r,i,a,o,c,s,l);if(u)return u;let d;switch(i){case 16777216:case 33554432:this._config.drawBoldTextInBrightColors&&c&&a<8&&(a+=8),d=this._getColorFromAnsiIndex(a);break;case 50331648:let e=Ig.toColorRGB(a);d=Uh.toColor(e[0],e[1],e[2]);break;default:d=o?this._config.colors.background:this._config.colors.foreground}return this._config.allowTransparency&&(d=Wh.opaque(d)),s&&(d=Wh.multiplyOpacity(d,hg)),d}_resolveBackgroundRgba(e,t,n){switch(e){case 16777216:case 33554432:return this._getColorFromAnsiIndex(t).rgba;case 50331648:return t<<8;default:return n?this._config.colors.foreground.rgba:this._config.colors.background.rgba}}_resolveForegroundRgba(e,t,n,r){switch(e){case 16777216:case 33554432:return this._config.drawBoldTextInBrightColors&&r&&t<8&&(t+=8),this._getColorFromAnsiIndex(t).rgba;case 50331648:return t<<8;default:return n?this._config.colors.background.rgba:this._config.colors.foreground.rgba}}_getMinimumContrastColor(e,t,n,r,i,a,o,s,c,l){if(this._config.minimumContrastRatio===1||l)return;let u=this._getContrastCache(c),d=u.getColor(e,r);if(d!==void 0)return d||void 0;let f=this._resolveBackgroundRgba(t,n,o),p=this._resolveForegroundRgba(i,a,o,s),m=qh.ensureContrastRatio(f,p,this._config.minimumContrastRatio/(c?2:1));if(!m){u.setColor(e,r,null);return}let h=Uh.toColor(m>>24&255,m>>16&255,m>>8&255);return u.setColor(e,r,h),h}_getContrastCache(e){return e?this._config.colors.halfContrastCache:this._config.colors.contrastCache}_drawToCache(t,n,r,i,a,o){let s=typeof t==`number`?String.fromCharCode(t):t;o&&this._tmpCanvas.parentElement!==o&&(this._tmpCanvas.style.display=`none`,o.append(this._tmpCanvas));let c=Math.min(this._config.deviceCellWidth*Math.max(s.length,2)+s_*2,this._config.deviceMaxTextureSize);this._tmpCanvas.width<c&&(this._tmpCanvas.width=c);let l=Math.min(this._config.deviceCellHeight+s_*4,this._textureSize);if(this._tmpCanvas.height<l&&(this._tmpCanvas.height=l),this._tmpCtx.save(),this._workAttributeData.fg=r,this._workAttributeData.bg=n,this._workAttributeData.extended.ext=i,this._workAttributeData.isInvisible())return o_;let u=!!this._workAttributeData.isBold(),d=!!this._workAttributeData.isInverse(),f=!!this._workAttributeData.isDim(),p=!!this._workAttributeData.isItalic(),m=!!this._workAttributeData.isUnderline(),h=!!this._workAttributeData.isStrikethrough(),g=!!this._workAttributeData.isOverline(),_=this._workAttributeData.getFgColor(),v=this._workAttributeData.getFgColorMode(),y=this._workAttributeData.getBgColor(),b=this._workAttributeData.getBgColorMode();if(d){let e=_;_=y,y=e;let t=v;v=b,b=t}let x=this._getBackgroundColor(b,y,d,f);this._tmpCtx.globalCompositeOperation=`copy`,this._tmpCtx.fillStyle=x.css,this._tmpCtx.fillRect(0,0,this._tmpCanvas.width,this._tmpCanvas.height),this._tmpCtx.globalCompositeOperation=`source-over`;let S=u?this._config.fontWeightBold:this._config.fontWeight,C=p?`italic`:``;this._tmpCtx.font=`${C} ${S} ${this._config.fontSize*this._config.devicePixelRatio}px ${this._config.fontFamily}`,this._tmpCtx.textBaseline=gg;let w=s.length===1&&Zh(s.charCodeAt(0)),T=s.length===1&&Qh(s.charCodeAt(0)),E=this._getForegroundColor(n,b,y,r,v,_,d,f,u,rg(s.charCodeAt(0)));this._tmpCtx.fillStyle=E.css;let D=T?0:s_*2,O=!1;this._config.customGlyphs!==!1&&(O=xg(this._tmpCtx,s,D,D,this._config.deviceCellWidth,this._config.deviceCellHeight,this._config.fontSize,this._config.devicePixelRatio));let k=!w,A;if(A=typeof t==`number`?this._unicodeService.wcwidth(t):this._unicodeService.getStringCellWidth(t),m){this._tmpCtx.save();let e=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/15)),t=e%2==1?.5:0;if(this._tmpCtx.lineWidth=e,this._workAttributeData.isUnderlineColorDefault())this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle;else if(this._workAttributeData.isUnderlineColorRGB())k=!1,this._tmpCtx.strokeStyle=`rgb(${Ig.toColorRGB(this._workAttributeData.getUnderlineColor()).join(`,`)})`;else{k=!1;let e=this._workAttributeData.getUnderlineColor();this._config.drawBoldTextInBrightColors&&this._workAttributeData.isBold()&&e<8&&(e+=8),this._tmpCtx.strokeStyle=this._getColorFromAnsiIndex(e).css}this._tmpCtx.beginPath();let n=D,r=Math.ceil(D+this._config.deviceCharHeight)-t-(a?e*2:0),i=r+e,o=r+e*2,c=this._workAttributeData.getUnderlineVariantOffset();for(let a=0;a<A;a++){this._tmpCtx.save();let s=n+a*this._config.deviceCellWidth,l=n+(a+1)*this._config.deviceCellWidth,u=s+this._config.deviceCellWidth/2;switch(this._workAttributeData.extended.underlineStyle){case 2:this._tmpCtx.moveTo(s,r),this._tmpCtx.lineTo(l,r),this._tmpCtx.moveTo(s,o),this._tmpCtx.lineTo(l,o);break;case 3:let n=e<=1?o:Math.ceil(D+this._config.deviceCharHeight-e/2)-t,a=e<=1?r:Math.ceil(D+this._config.deviceCharHeight+e/2)-t,d=new Path2D;d.rect(s,r,this._config.deviceCellWidth,o-r),this._tmpCtx.clip(d),this._tmpCtx.moveTo(s-this._config.deviceCellWidth/2,i),this._tmpCtx.bezierCurveTo(s-this._config.deviceCellWidth/2,a,s,a,s,i),this._tmpCtx.bezierCurveTo(s,n,u,n,u,i),this._tmpCtx.bezierCurveTo(u,a,l,a,l,i),this._tmpCtx.bezierCurveTo(l,n,l+this._config.deviceCellWidth/2,n,l+this._config.deviceCellWidth/2,i);break;case 4:let f=c===0?0:c>=e?e*2-c:e-c;c>=e||f===0?(this._tmpCtx.setLineDash([Math.round(e),Math.round(e)]),this._tmpCtx.moveTo(s+f,r),this._tmpCtx.lineTo(l,r)):(this._tmpCtx.setLineDash([Math.round(e),Math.round(e)]),this._tmpCtx.moveTo(s,r),this._tmpCtx.lineTo(s+f,r),this._tmpCtx.moveTo(s+f+e,r),this._tmpCtx.lineTo(l,r)),c=og(l-s,e,c);break;case 5:let p=l-s,m=Math.floor(.6*p),h=Math.floor(.3*p),g=p-m-h;this._tmpCtx.setLineDash([m,h,g]),this._tmpCtx.moveTo(s,r),this._tmpCtx.lineTo(l,r);break;default:this._tmpCtx.moveTo(s,r),this._tmpCtx.lineTo(l,r);break}this._tmpCtx.stroke(),this._tmpCtx.restore()}if(this._tmpCtx.restore(),!O&&this._config.fontSize>=12&&!this._config.allowTransparency&&s!==` `){this._tmpCtx.save(),this._tmpCtx.textBaseline=`alphabetic`;let t=this._tmpCtx.measureText(s);if(this._tmpCtx.restore(),`actualBoundingBoxDescent`in t&&t.actualBoundingBoxDescent>0){this._tmpCtx.save();let t=new Path2D;t.rect(n,r-Math.ceil(e/2),this._config.deviceCellWidth*A,o-r+Math.ceil(e/2)),this._tmpCtx.clip(t),this._tmpCtx.lineWidth=this._config.devicePixelRatio*3,this._tmpCtx.strokeStyle=x.css,this._tmpCtx.strokeText(s,D,D+this._config.deviceCharHeight),this._tmpCtx.restore()}}}if(g){let e=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/15)),t=e%2==1?.5:0;this._tmpCtx.lineWidth=e,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(D,D+t),this._tmpCtx.lineTo(D+this._config.deviceCharWidth*A,D+t),this._tmpCtx.stroke()}if(O||this._tmpCtx.fillText(s,D,D+this._config.deviceCharHeight),s===`_`&&!this._config.allowTransparency){let e=d_(this._tmpCtx.getImageData(D,D,this._config.deviceCellWidth,this._config.deviceCellHeight),x,E,k);if(e)for(let t=1;t<=5&&(this._tmpCtx.save(),this._tmpCtx.fillStyle=x.css,this._tmpCtx.fillRect(0,0,this._tmpCanvas.width,this._tmpCanvas.height),this._tmpCtx.restore(),this._tmpCtx.fillText(s,D,D+this._config.deviceCharHeight-t),e=d_(this._tmpCtx.getImageData(D,D,this._config.deviceCellWidth,this._config.deviceCellHeight),x,E,k),e);t++);}if(h){let e=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/10)),t=this._tmpCtx.lineWidth%2==1?.5:0;this._tmpCtx.lineWidth=e,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(D,D+Math.floor(this._config.deviceCharHeight/2)-t),this._tmpCtx.lineTo(D+this._config.deviceCharWidth*A,D+Math.floor(this._config.deviceCharHeight/2)-t),this._tmpCtx.stroke()}this._tmpCtx.restore();let j=this._tmpCtx.getImageData(0,0,this._tmpCanvas.width,this._tmpCanvas.height),M;if(M=this._config.allowTransparency?f_(j):d_(j,x,E,k),M)return o_;let N=this._findGlyphBoundingBox(j,this._workBoundingBox,c,T,O,D),P,F;for(;;){if(this._activePages.length===0){let e=this._createNewPage();P=e,F=e.currentRow,F.height=N.size.y;break}P=this._activePages[this._activePages.length-1],F=P.currentRow;for(let e of this._activePages)N.size.y<=e.currentRow.height&&(P=e,F=e.currentRow);for(let e=this._activePages.length-1;e>=0;e--)for(let t of this._activePages[e].fixedRows)t.height<=F.height&&N.size.y<=t.height&&(P=this._activePages[e],F=t);if(N.size.x>this._textureSize){this._overflowSizePage||(this._overflowSizePage=new u_(this._document,this._config.deviceMaxTextureSize),this.pages.push(this._overflowSizePage),this._requestClearModel=!0,this._onAddTextureAtlasCanvas.fire(this._overflowSizePage.canvas)),P=this._overflowSizePage,F=this._overflowSizePage.currentRow,F.x+N.size.x>=P.canvas.width&&(F.x=0,F.y+=F.height,F.height=0);break}if(F.y+N.size.y>=P.canvas.height||F.height>N.size.y+2){let t=!1;if(P.currentRow.y+P.currentRow.height+N.size.y>=P.canvas.height){let n;for(let e of this._activePages)if(e.currentRow.y+e.currentRow.height+N.size.y<e.canvas.height){n=e;break}if(n)P=n;else if(e.maxAtlasPages&&this._pages.length>=e.maxAtlasPages&&F.y+N.size.y<=P.canvas.height&&F.height>=N.size.y&&F.x+N.size.x<=P.canvas.width)t=!0;else{let e=this._createNewPage();P=e,F=e.currentRow,F.height=N.size.y,t=!0}}t||(P.currentRow.height>0&&P.fixedRows.push(P.currentRow),F={x:0,y:P.currentRow.y+P.currentRow.height,height:N.size.y},P.fixedRows.push(F),P.currentRow={x:0,y:F.y+F.height,height:0})}if(F.x+N.size.x<=P.canvas.width)break;F===P.currentRow?(F.x=0,F.y+=F.height,F.height=0):P.fixedRows.splice(P.fixedRows.indexOf(F),1)}return N.texturePage=this._pages.indexOf(P),N.texturePosition.x=F.x,N.texturePosition.y=F.y,N.texturePositionClipSpace.x=F.x/P.canvas.width,N.texturePositionClipSpace.y=F.y/P.canvas.height,N.sizeClipSpace.x/=P.canvas.width,N.sizeClipSpace.y/=P.canvas.height,F.height=Math.max(F.height,N.size.y),F.x+=N.size.x,P.ctx.putImageData(j,N.texturePosition.x-this._workBoundingBox.left,N.texturePosition.y-this._workBoundingBox.top,this._workBoundingBox.left,this._workBoundingBox.top,N.size.x,N.size.y),P.addGlyph(N),P.version++,N}_findGlyphBoundingBox(e,t,n,r,i,a){t.top=0;let o=r?this._config.deviceCellHeight:this._tmpCanvas.height,s=r?this._config.deviceCellWidth:n,c=!1;for(let n=0;n<o;n++){for(let r=0;r<s;r++){let i=n*this._tmpCanvas.width*4+r*4+3;if(e.data[i]!==0){t.top=n,c=!0;break}}if(c)break}t.left=0,c=!1;for(let n=0;n<a+s;n++){for(let r=0;r<o;r++){let i=r*this._tmpCanvas.width*4+n*4+3;if(e.data[i]!==0){t.left=n,c=!0;break}}if(c)break}t.right=s,c=!1;for(let n=a+s-1;n>=a;n--){for(let r=0;r<o;r++){let i=r*this._tmpCanvas.width*4+n*4+3;if(e.data[i]!==0){t.right=n,c=!0;break}}if(c)break}t.bottom=o,c=!1;for(let n=o-1;n>=0;n--){for(let r=0;r<s;r++){let i=n*this._tmpCanvas.width*4+r*4+3;if(e.data[i]!==0){t.bottom=n,c=!0;break}}if(c)break}return{texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},size:{x:t.right-t.left+1,y:t.bottom-t.top+1},sizeClipSpace:{x:t.right-t.left+1,y:t.bottom-t.top+1},offset:{x:-t.left+a+(r||i?Math.floor((this._config.deviceCellWidth-this._config.deviceCharWidth)/2):0),y:-t.top+a+(r||i?this._config.lineHeight===1?0:Math.round((this._config.deviceCellHeight-this._config.deviceCharHeight)/2):0)}}}},u_=class{constructor(e,t,n){if(this._usedPixels=0,this._glyphs=[],this.version=0,this.currentRow={x:0,y:0,height:0},this.fixedRows=[],n)for(let e of n)this._glyphs.push(...e.glyphs),this._usedPixels+=e._usedPixels;this.canvas=p_(e,t,t),this.ctx=Xh(this.canvas.getContext(`2d`,{alpha:!0}))}get percentageUsed(){return this._usedPixels/(this.canvas.width*this.canvas.height)}get glyphs(){return this._glyphs}addGlyph(e){this._glyphs.push(e),this._usedPixels+=e.size.x*e.size.y}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.currentRow.x=0,this.currentRow.y=0,this.currentRow.height=0,this.fixedRows.length=0,this.version++}};function d_(e,t,n,r){let i=t.rgba>>>24,a=t.rgba>>>16&255,o=t.rgba>>>8&255,s=n.rgba>>>24,c=n.rgba>>>16&255,l=n.rgba>>>8&255,u=Math.floor((Math.abs(i-s)+Math.abs(a-c)+Math.abs(o-l))/12),d=!0;for(let t=0;t<e.data.length;t+=4)e.data[t]===i&&e.data[t+1]===a&&e.data[t+2]===o||r&&Math.abs(e.data[t]-i)+Math.abs(e.data[t+1]-a)+Math.abs(e.data[t+2]-o)<u?e.data[t+3]=0:d=!1;return d}function f_(e){for(let t=0;t<e.data.length;t+=4)if(e.data[t+3]>0)return!1;return!0}function p_(e,t,n){let r=e.createElement(`canvas`);return r.width=t,r.height=n,r}function m_(e,t,n,r,i,a,o,s){let c={foreground:a.foreground,background:a.background,cursor:Hh,cursorAccent:Hh,selectionForeground:Hh,selectionBackgroundTransparent:Hh,selectionBackgroundOpaque:Hh,selectionInactiveBackgroundTransparent:Hh,selectionInactiveBackgroundOpaque:Hh,overviewRulerBorder:Hh,scrollbarSliderBackground:Hh,scrollbarSliderHoverBackground:Hh,scrollbarSliderActiveBackground:Hh,ansi:a.ansi.slice(),contrastCache:a.contrastCache,halfContrastCache:a.halfContrastCache};return{customGlyphs:i.customGlyphs,devicePixelRatio:o,deviceMaxTextureSize:s,letterSpacing:i.letterSpacing,lineHeight:i.lineHeight,deviceCellWidth:e,deviceCellHeight:t,deviceCharWidth:n,deviceCharHeight:r,fontFamily:i.fontFamily,fontSize:i.fontSize,fontWeight:i.fontWeight,fontWeightBold:i.fontWeightBold,allowTransparency:i.allowTransparency,drawBoldTextInBrightColors:i.drawBoldTextInBrightColors,minimumContrastRatio:i.minimumContrastRatio,colors:c}}function h_(e,t){for(let n=0;n<e.colors.ansi.length;n++)if(e.colors.ansi[n].rgba!==t.colors.ansi[n].rgba)return!1;return e.devicePixelRatio===t.devicePixelRatio&&e.customGlyphs===t.customGlyphs&&e.lineHeight===t.lineHeight&&e.letterSpacing===t.letterSpacing&&e.fontFamily===t.fontFamily&&e.fontSize===t.fontSize&&e.fontWeight===t.fontWeight&&e.fontWeightBold===t.fontWeightBold&&e.allowTransparency===t.allowTransparency&&e.deviceCharWidth===t.deviceCharWidth&&e.deviceCharHeight===t.deviceCharHeight&&e.drawBoldTextInBrightColors===t.drawBoldTextInBrightColors&&e.minimumContrastRatio===t.minimumContrastRatio&&e.colors.foreground.rgba===t.colors.foreground.rgba&&e.colors.background.rgba===t.colors.background.rgba}function g_(e){return(e&50331648)==16777216||(e&50331648)==33554432}var __=[];function v_(e,t,n,r,i,a,o,s,c){let l=m_(r,i,a,o,t,n,s,c);for(let t=0;t<__.length;t++){let n=__[t],r=n.ownedBy.indexOf(e);if(r>=0){if(h_(n.config,l))return n.atlas;n.ownedBy.length===1?(n.atlas.dispose(),__.splice(t,1)):n.ownedBy.splice(r,1);break}}for(let t=0;t<__.length;t++){let n=__[t];if(h_(n.config,l))return n.ownedBy.push(e),n.atlas}let u=e._core,d={atlas:new l_(document,l,u.unicodeService),config:l,ownedBy:[e]};return __.push(d),d.atlas}function y_(e){for(let t=0;t<__.length;t++){let n=__[t].ownedBy.indexOf(e);if(n!==-1){__[t].ownedBy.length===1?(__[t].atlas.dispose(),__.splice(t,1)):__[t].ownedBy.splice(n,1);break}}}var b_=600,x_=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this.isCursorVisible=!0,this._coreBrowserService.isFocused&&this._restartInterval()}get isPaused(){return!(this._blinkStartTimeout||this._blinkInterval)}dispose(){this._blinkInterval&&=(this._coreBrowserService.window.clearInterval(this._blinkInterval),void 0),this._blinkStartTimeout&&=(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),void 0),this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}restartBlinkAnimation(){this.isPaused||(this._animationTimeRestarted=Date.now(),this.isCursorVisible=!0,this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0}))}_restartInterval(e=b_){this._blinkInterval&&=(this._coreBrowserService.window.clearInterval(this._blinkInterval),void 0),this._blinkStartTimeout=this._coreBrowserService.window.setTimeout(()=>{if(this._animationTimeRestarted){let e=b_-(Date.now()-this._animationTimeRestarted);if(this._animationTimeRestarted=void 0,e>0){this._restartInterval(e);return}}this.isCursorVisible=!1,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0}),this._blinkInterval=this._coreBrowserService.window.setInterval(()=>{if(this._animationTimeRestarted){let e=b_-(Date.now()-this._animationTimeRestarted);this._animationTimeRestarted=void 0,this._restartInterval(e);return}this.isCursorVisible=!this.isCursorVisible,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0})},b_)},e)}pause(){this.isCursorVisible=!0,this._blinkInterval&&=(this._coreBrowserService.window.clearInterval(this._blinkInterval),void 0),this._blinkStartTimeout&&=(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),void 0),this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}resume(){this.pause(),this._animationTimeRestarted=void 0,this._restartInterval(),this.restartBlinkAnimation()}};function S_(e,t,n){let r=new t.ResizeObserver(t=>{let i=t.find(t=>t.target===e);if(!i)return;if(!(`devicePixelContentBoxSize`in i)){r?.disconnect(),r=void 0;return}let a=i.devicePixelContentBoxSize[0].inlineSize,o=i.devicePixelContentBoxSize[0].blockSize;a>0&&o>0&&n(a,o)});try{r.observe(e,{box:[`device-pixel-content-box`]})}catch{r.disconnect(),r=void 0}return Th(()=>r?.disconnect())}function C_(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}var w_=class e extends Ig{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Lg,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?C_(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},T_=new Float32Array([2,0,0,0,0,-2,0,0,0,0,1,0,-1,1,0,1]);function E_(e,t,n){let r=Xh(e.createProgram());if(e.attachShader(r,Xh(D_(e,e.VERTEX_SHADER,t))),e.attachShader(r,Xh(D_(e,e.FRAGMENT_SHADER,n))),e.linkProgram(r),e.getProgramParameter(r,e.LINK_STATUS))return r;console.error(e.getProgramInfoLog(r)),e.deleteProgram(r)}function D_(e,t,n){let r=Xh(e.createShader(t));if(e.shaderSource(r,n),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS))return r;console.error(e.getShaderInfoLog(r)),e.deleteShader(r)}function O_(e,t){let n=Math.min(e.length*2,t),r=new Float32Array(n);for(let t=0;t<e.length;t++)r[t]=e[t];return r}var k_=class{constructor(e){this.texture=e,this.version=-1}},A_=`#version 300 es
94
+ layout (location = 0) in vec2 a_unitquad;
95
+ layout (location = 1) in vec2 a_cellpos;
96
+ layout (location = 2) in vec2 a_offset;
97
+ layout (location = 3) in vec2 a_size;
98
+ layout (location = 4) in float a_texpage;
99
+ layout (location = 5) in vec2 a_texcoord;
100
+ layout (location = 6) in vec2 a_texsize;
101
+
102
+ uniform mat4 u_projection;
103
+ uniform vec2 u_resolution;
104
+
105
+ out vec2 v_texcoord;
106
+ flat out int v_texpage;
107
+
108
+ void main() {
109
+ vec2 zeroToOne = (a_offset / u_resolution) + a_cellpos + (a_unitquad * a_size);
110
+ gl_Position = u_projection * vec4(zeroToOne, 0.0, 1.0);
111
+ v_texpage = int(a_texpage);
112
+ v_texcoord = a_texcoord + a_unitquad * a_texsize;
113
+ }`;function j_(e){let t=``;for(let n=1;n<e;n++)t+=` else if (v_texpage == ${n}) { outColor = texture(u_texture[${n}], v_texcoord); }`;return`#version 300 es
114
+ precision lowp float;
115
+
116
+ in vec2 v_texcoord;
117
+ flat in int v_texpage;
118
+
119
+ uniform sampler2D u_texture[${e}];
120
+
121
+ out vec4 outColor;
122
+
123
+ void main() {
124
+ if (v_texpage == 0) {
125
+ outColor = texture(u_texture[0], v_texcoord);
126
+ } ${t}
127
+ }`}var M_=11,N_=M_*Float32Array.BYTES_PER_ELEMENT,P_=2,F_=0,I_,L_=0,R_=0,z_=class extends Oh{constructor(e,t,n,r){super(),this._terminal=e,this._gl=t,this._dimensions=n,this._optionsService=r,this._activeBuffer=0,this._vertices={count:0,attributes:new Float32Array,attributesBuffers:[new Float32Array,new Float32Array]};let i=this._gl;l_.maxAtlasPages===void 0&&(l_.maxAtlasPages=Math.min(32,Xh(i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS))),l_.maxTextureSize=Xh(i.getParameter(i.MAX_TEXTURE_SIZE))),this._program=Xh(E_(i,A_,j_(l_.maxAtlasPages))),this._register(Th(()=>i.deleteProgram(this._program))),this._projectionLocation=Xh(i.getUniformLocation(this._program,`u_projection`)),this._resolutionLocation=Xh(i.getUniformLocation(this._program,`u_resolution`)),this._textureLocation=Xh(i.getUniformLocation(this._program,`u_texture`)),this._vertexArrayObject=i.createVertexArray(),i.bindVertexArray(this._vertexArrayObject);let a=new Float32Array([0,0,1,0,0,1,1,1]),o=i.createBuffer();this._register(Th(()=>i.deleteBuffer(o))),i.bindBuffer(i.ARRAY_BUFFER,o),i.bufferData(i.ARRAY_BUFFER,a,i.STATIC_DRAW),i.enableVertexAttribArray(0),i.vertexAttribPointer(0,2,this._gl.FLOAT,!1,0,0);let s=new Uint8Array([0,1,2,3]),c=i.createBuffer();this._register(Th(()=>i.deleteBuffer(c))),i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,c),i.bufferData(i.ELEMENT_ARRAY_BUFFER,s,i.STATIC_DRAW),this._attributesBuffer=Xh(i.createBuffer()),this._register(Th(()=>i.deleteBuffer(this._attributesBuffer))),i.bindBuffer(i.ARRAY_BUFFER,this._attributesBuffer),i.enableVertexAttribArray(2),i.vertexAttribPointer(2,2,i.FLOAT,!1,N_,0),i.vertexAttribDivisor(2,1),i.enableVertexAttribArray(3),i.vertexAttribPointer(3,2,i.FLOAT,!1,N_,2*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(3,1),i.enableVertexAttribArray(4),i.vertexAttribPointer(4,1,i.FLOAT,!1,N_,4*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(4,1),i.enableVertexAttribArray(5),i.vertexAttribPointer(5,2,i.FLOAT,!1,N_,5*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(5,1),i.enableVertexAttribArray(6),i.vertexAttribPointer(6,2,i.FLOAT,!1,N_,7*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(6,1),i.enableVertexAttribArray(1),i.vertexAttribPointer(1,2,i.FLOAT,!1,N_,9*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(1,1),i.useProgram(this._program);let l=new Int32Array(l_.maxAtlasPages);for(let e=0;e<l_.maxAtlasPages;e++)l[e]=e;i.uniform1iv(this._textureLocation,l),i.uniformMatrix4fv(this._projectionLocation,!1,T_),this._atlasTextures=[];for(let e=0;e<l_.maxAtlasPages;e++){let t=new k_(Xh(i.createTexture()));this._register(Th(()=>i.deleteTexture(t.texture))),i.activeTexture(i.TEXTURE0+e),i.bindTexture(i.TEXTURE_2D,t.texture),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[e]=t}i.enable(i.BLEND),i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){return this._atlas?this._atlas.beginFrame():!0}updateCell(e,t,n,r,i,a,o,s,c){this._updateCell(this._vertices.attributes,e,t,n,r,i,a,o,s,c)}_updateCell(e,t,n,r,i,a,o,s,c,l){if(F_=(n*this._terminal.cols+t)*M_,r===0||r===void 0){e.fill(0,F_,F_+M_-1-P_);return}this._atlas&&(I_=s&&s.length>1?this._atlas.getRasterizedGlyphCombinedChar(s,i,a,o,!1,this._terminal.element):this._atlas.getRasterizedGlyph(r,i,a,o,!1,this._terminal.element),L_=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),i!==l&&I_.offset.x>L_?(R_=I_.offset.x-L_,e[F_]=-(I_.offset.x-R_)+this._dimensions.device.char.left,e[F_+1]=-I_.offset.y+this._dimensions.device.char.top,e[F_+2]=(I_.size.x-R_)/this._dimensions.device.canvas.width,e[F_+3]=I_.size.y/this._dimensions.device.canvas.height,e[F_+4]=I_.texturePage,e[F_+5]=I_.texturePositionClipSpace.x+R_/this._atlas.pages[I_.texturePage].canvas.width,e[F_+6]=I_.texturePositionClipSpace.y,e[F_+7]=I_.sizeClipSpace.x-R_/this._atlas.pages[I_.texturePage].canvas.width,e[F_+8]=I_.sizeClipSpace.y):(e[F_]=-I_.offset.x+this._dimensions.device.char.left,e[F_+1]=-I_.offset.y+this._dimensions.device.char.top,e[F_+2]=I_.size.x/this._dimensions.device.canvas.width,e[F_+3]=I_.size.y/this._dimensions.device.canvas.height,e[F_+4]=I_.texturePage,e[F_+5]=I_.texturePositionClipSpace.x,e[F_+6]=I_.texturePositionClipSpace.y,e[F_+7]=I_.sizeClipSpace.x,e[F_+8]=I_.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&ng(r,c,I_.size.x,this._dimensions.device.cell.width)&&(e[F_+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width))}clear(){let e=this._terminal,t=e.cols*e.rows*M_;this._vertices.count===t?this._vertices.attributes.fill(0):this._vertices.attributes=new Float32Array(t);let n=0;for(;n<this._vertices.attributesBuffers.length;n++)this._vertices.count===t?this._vertices.attributesBuffers[n].fill(0):this._vertices.attributesBuffers[n]=new Float32Array(t);this._vertices.count=t,n=0;for(let t=0;t<e.rows;t++)for(let r=0;r<e.cols;r++)this._vertices.attributes[n+9]=r/e.cols,this._vertices.attributes[n+10]=t/e.rows,n+=M_}handleResize(){let e=this._gl;e.useProgram(this._program),e.viewport(0,0,e.canvas.width,e.canvas.height),e.uniform2f(this._resolutionLocation,e.canvas.width,e.canvas.height),this.clear()}render(e){if(!this._atlas)return;let t=this._gl;t.useProgram(this._program),t.bindVertexArray(this._vertexArrayObject),this._activeBuffer=(this._activeBuffer+1)%2;let n=this._vertices.attributesBuffers[this._activeBuffer],r=0;for(let t=0;t<e.lineLengths.length;t++){let i=t*this._terminal.cols*M_,a=this._vertices.attributes.subarray(i,i+e.lineLengths[t]*M_);n.set(a,r),r+=a.length}t.bindBuffer(t.ARRAY_BUFFER,this._attributesBuffer),t.bufferData(t.ARRAY_BUFFER,n.subarray(0,r),t.STREAM_DRAW);for(let e=0;e<this._atlas.pages.length;e++)this._atlas.pages[e].version!==this._atlasTextures[e].version&&this._bindAtlasPageTexture(t,this._atlas,e);t.drawElementsInstanced(t.TRIANGLE_STRIP,4,t.UNSIGNED_BYTE,0,r/M_)}setAtlas(e){this._atlas=e;for(let e of this._atlasTextures)e.version=-1}_bindAtlasPageTexture(e,t,n){e.activeTexture(e.TEXTURE0+n),e.bindTexture(e.TEXTURE_2D,this._atlasTextures[n].texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t.pages[n].canvas),e.generateMipmap(e.TEXTURE_2D),this._atlasTextures[n].version=t.pages[n].version}setDimensions(e){this._dimensions=e}},B_=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);if(s>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function V_(){return new B_}var H_=4,U_=1,W_=2,G_=3,K_=2147483648,q_=class{constructor(){this.cells=new Uint32Array,this.lineLengths=new Uint32Array,this.selection=V_()}resize(e,t){let n=e*t*H_;n!==this.cells.length&&(this.cells=new Uint32Array(n),this.lineLengths=new Uint32Array(t))}clear(){this.cells.fill(0,0),this.lineLengths.fill(0,0)}},J_=`#version 300 es
128
+ layout (location = 0) in vec2 a_position;
129
+ layout (location = 1) in vec2 a_size;
130
+ layout (location = 2) in vec4 a_color;
131
+ layout (location = 3) in vec2 a_unitquad;
132
+
133
+ uniform mat4 u_projection;
134
+
135
+ out vec4 v_color;
136
+
137
+ void main() {
138
+ vec2 zeroToOne = a_position + (a_unitquad * a_size);
139
+ gl_Position = u_projection * vec4(zeroToOne, 0.0, 1.0);
140
+ v_color = a_color;
141
+ }`,Y_=`#version 300 es
142
+ precision lowp float;
143
+
144
+ in vec4 v_color;
145
+
146
+ out vec4 outColor;
147
+
148
+ void main() {
149
+ outColor = v_color;
150
+ }`,X_=8,Z_=X_*Float32Array.BYTES_PER_ELEMENT,Q_=20*X_,$_=class{constructor(){this.attributes=new Float32Array(Q_),this.count=0}},ev=0,tv=0,nv=0,rv=0,iv=0,av=0,ov=0,sv=class extends Oh{constructor(e,t,n,r){super(),this._terminal=e,this._gl=t,this._dimensions=n,this._themeService=r,this._vertices=new $_,this._verticesCursor=new $_;let i=this._gl;this._program=Xh(E_(i,J_,Y_)),this._register(Th(()=>i.deleteProgram(this._program))),this._projectionLocation=Xh(i.getUniformLocation(this._program,`u_projection`)),this._vertexArrayObject=i.createVertexArray(),i.bindVertexArray(this._vertexArrayObject);let a=new Float32Array([0,0,1,0,0,1,1,1]),o=i.createBuffer();this._register(Th(()=>i.deleteBuffer(o))),i.bindBuffer(i.ARRAY_BUFFER,o),i.bufferData(i.ARRAY_BUFFER,a,i.STATIC_DRAW),i.enableVertexAttribArray(3),i.vertexAttribPointer(3,2,this._gl.FLOAT,!1,0,0);let s=new Uint8Array([0,1,2,3]),c=i.createBuffer();this._register(Th(()=>i.deleteBuffer(c))),i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,c),i.bufferData(i.ELEMENT_ARRAY_BUFFER,s,i.STATIC_DRAW),this._attributesBuffer=Xh(i.createBuffer()),this._register(Th(()=>i.deleteBuffer(this._attributesBuffer))),i.bindBuffer(i.ARRAY_BUFFER,this._attributesBuffer),i.enableVertexAttribArray(0),i.vertexAttribPointer(0,2,i.FLOAT,!1,Z_,0),i.vertexAttribDivisor(0,1),i.enableVertexAttribArray(1),i.vertexAttribPointer(1,2,i.FLOAT,!1,Z_,2*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(1,1),i.enableVertexAttribArray(2),i.vertexAttribPointer(2,4,i.FLOAT,!1,Z_,4*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(2,1),this._updateCachedColors(r.colors),this._register(this._themeService.onChangeColors(e=>{this._updateCachedColors(e),this._updateViewportRectangle()}))}renderBackgrounds(){this._renderVertices(this._vertices)}renderCursor(){this._renderVertices(this._verticesCursor)}_renderVertices(e){let t=this._gl;t.useProgram(this._program),t.bindVertexArray(this._vertexArrayObject),t.uniformMatrix4fv(this._projectionLocation,!1,T_),t.bindBuffer(t.ARRAY_BUFFER,this._attributesBuffer),t.bufferData(t.ARRAY_BUFFER,e.attributes,t.DYNAMIC_DRAW),t.drawElementsInstanced(this._gl.TRIANGLE_STRIP,4,t.UNSIGNED_BYTE,0,e.count)}handleResize(){this._updateViewportRectangle()}setDimensions(e){this._dimensions=e}_updateCachedColors(e){this._bgFloat=this._colorToFloat32Array(e.background),this._cursorFloat=this._colorToFloat32Array(e.cursor)}_updateViewportRectangle(){this._addRectangleFloat(this._vertices.attributes,0,0,0,this._terminal.cols*this._dimensions.device.cell.width,this._terminal.rows*this._dimensions.device.cell.height,this._bgFloat)}updateBackgrounds(e){let t=this._terminal,n=this._vertices,r=1,i,a,o,s,c,l,u,d,f,p,m;for(i=0;i<t.rows;i++){for(o=-1,s=0,c=0,l=!1,a=0;a<t.cols;a++)u=(i*t.cols+a)*H_,d=e.cells[u+U_],f=e.cells[u+W_],p=!!(f&67108864),(d!==s||f!==c&&(l||p))&&((s!==0||l&&c!==0)&&(m=r++*X_,this._updateRectangle(n,m,c,s,o,a,i)),o=a,s=d,c=f,l=p);(s!==0||l&&c!==0)&&(m=r++*X_,this._updateRectangle(n,m,c,s,o,t.cols,i))}n.count=r}updateCursor(e){let t=this._verticesCursor,n=e.cursor;if(!n||n.style===`block`){t.count=0;return}let r,i=0;(n.style===`bar`||n.style===`outline`)&&(r=i++*X_,this._addRectangleFloat(t.attributes,r,n.x*this._dimensions.device.cell.width,n.y*this._dimensions.device.cell.height,n.style===`bar`?n.dpr*n.cursorWidth:n.dpr,this._dimensions.device.cell.height,this._cursorFloat)),(n.style===`underline`||n.style===`outline`)&&(r=i++*X_,this._addRectangleFloat(t.attributes,r,n.x*this._dimensions.device.cell.width,(n.y+1)*this._dimensions.device.cell.height-n.dpr,n.width*this._dimensions.device.cell.width,n.dpr,this._cursorFloat)),n.style===`outline`&&(r=i++*X_,this._addRectangleFloat(t.attributes,r,n.x*this._dimensions.device.cell.width,n.y*this._dimensions.device.cell.height,n.width*this._dimensions.device.cell.width,n.dpr,this._cursorFloat),r=i++*X_,this._addRectangleFloat(t.attributes,r,(n.x+n.width)*this._dimensions.device.cell.width-n.dpr,n.y*this._dimensions.device.cell.height,n.dpr,this._dimensions.device.cell.height,this._cursorFloat)),t.count=i}_updateRectangle(e,t,n,r,i,a,o){if(n&67108864)switch(n&50331648){case 16777216:case 33554432:ev=this._themeService.colors.ansi[n&255].rgba;break;case 50331648:ev=(n&16777215)<<8;break;case 0:default:ev=this._themeService.colors.foreground.rgba}else switch(r&50331648){case 16777216:case 33554432:ev=this._themeService.colors.ansi[r&255].rgba;break;case 50331648:ev=(r&16777215)<<8;break;case 0:default:ev=this._themeService.colors.background.rgba}e.attributes.length<t+4&&(e.attributes=O_(e.attributes,this._terminal.rows*this._terminal.cols*X_)),tv=i*this._dimensions.device.cell.width,nv=o*this._dimensions.device.cell.height,rv=(ev>>24&255)/255,iv=(ev>>16&255)/255,av=(ev>>8&255)/255,ov=1,this._addRectangle(e.attributes,t,tv,nv,(a-i)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,rv,iv,av,ov)}_addRectangle(e,t,n,r,i,a,o,s,c,l){e[t]=n/this._dimensions.device.canvas.width,e[t+1]=r/this._dimensions.device.canvas.height,e[t+2]=i/this._dimensions.device.canvas.width,e[t+3]=a/this._dimensions.device.canvas.height,e[t+4]=o,e[t+5]=s,e[t+6]=c,e[t+7]=l}_addRectangleFloat(e,t,n,r,i,a,o){e[t]=n/this._dimensions.device.canvas.width,e[t+1]=r/this._dimensions.device.canvas.height,e[t+2]=i/this._dimensions.device.canvas.width,e[t+3]=a/this._dimensions.device.canvas.height,e[t+4]=o[0],e[t+5]=o[1],e[t+6]=o[2],e[t+7]=o[3]}_colorToFloat32Array(e){return new Float32Array([(e.rgba>>24&255)/255,(e.rgba>>16&255)/255,(e.rgba>>8&255)/255,(e.rgba&255)/255])}},cv=class extends Oh{constructor(e,t,n,r,i,a,o,s){super(),this._container=t,this._alpha=i,this._coreBrowserService=a,this._optionsService=o,this._themeService=s,this._deviceCharWidth=0,this._deviceCharHeight=0,this._deviceCellWidth=0,this._deviceCellHeight=0,this._deviceCharLeft=0,this._deviceCharTop=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-${n}-layer`),this._canvas.style.zIndex=r.toString(),this._initCanvas(),this._container.appendChild(this._canvas),this._register(this._themeService.onChangeColors(t=>{this._refreshCharAtlas(e,t),this.reset(e)})),this._register(Th(()=>{this._canvas.remove()}))}_initCanvas(){this._ctx=Xh(this._canvas.getContext(`2d`,{alpha:this._alpha})),this._alpha||this._clearAll()}handleBlur(e){}handleFocus(e){}handleCursorMove(e){}handleGridChanged(e,t,n){}handleSelectionChanged(e,t,n,r=!1){}_setTransparency(e,t){if(t===this._alpha)return;let n=this._canvas;this._alpha=t,this._canvas=this._canvas.cloneNode(),this._initCanvas(),this._container.replaceChild(this._canvas,n),this._refreshCharAtlas(e,this._themeService.colors),this.handleGridChanged(e,0,e.rows-1)}_refreshCharAtlas(e,t){this._deviceCharWidth<=0&&this._deviceCharHeight<=0||(this._charAtlas=v_(e,this._optionsService.rawOptions,t,this._deviceCellWidth,this._deviceCellHeight,this._deviceCharWidth,this._deviceCharHeight,this._coreBrowserService.dpr,2048),this._charAtlas.warmUp())}resize(e,t){this._deviceCellWidth=t.device.cell.width,this._deviceCellHeight=t.device.cell.height,this._deviceCharWidth=t.device.char.width,this._deviceCharHeight=t.device.char.height,this._deviceCharLeft=t.device.char.left,this._deviceCharTop=t.device.char.top,this._canvas.width=t.device.canvas.width,this._canvas.height=t.device.canvas.height,this._canvas.style.width=`${t.css.canvas.width}px`,this._canvas.style.height=`${t.css.canvas.height}px`,this._alpha||this._clearAll(),this._refreshCharAtlas(e,this._themeService.colors)}_fillBottomLineAtCells(e,t,n=1){this._ctx.fillRect(e*this._deviceCellWidth,(t+1)*this._deviceCellHeight-this._coreBrowserService.dpr-1,n*this._deviceCellWidth,this._coreBrowserService.dpr)}_clearAll(){this._alpha?this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height))}_clearCells(e,t,n,r){this._alpha?this._ctx.clearRect(e*this._deviceCellWidth,t*this._deviceCellHeight,n*this._deviceCellWidth,r*this._deviceCellHeight):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(e*this._deviceCellWidth,t*this._deviceCellHeight,n*this._deviceCellWidth,r*this._deviceCellHeight))}_fillCharTrueColor(e,t,n,r){this._ctx.font=this._getFont(e,!1,!1),this._ctx.textBaseline=gg,this._clipCell(n,r,t.getWidth()),this._ctx.fillText(t.getChars(),n*this._deviceCellWidth+this._deviceCharLeft,r*this._deviceCellHeight+this._deviceCharTop+this._deviceCharHeight)}_clipCell(e,t,n){this._ctx.beginPath(),this._ctx.rect(e*this._deviceCellWidth,t*this._deviceCellHeight,n*this._deviceCellWidth,this._deviceCellHeight),this._ctx.clip()}_getFont(e,t,n){let r=t?e.options.fontWeightBold:e.options.fontWeight;return`${n?`italic`:``} ${r} ${e.options.fontSize*this._coreBrowserService.dpr}px ${e.options.fontFamily}`}},lv=class extends cv{constructor(e,t,n,r,i,a,o){super(n,e,`link`,t,!0,i,a,o),this._register(r.onShowLinkUnderline(e=>this._handleShowLinkUnderline(e))),this._register(r.onHideLinkUnderline(e=>this._handleHideLinkUnderline(e)))}resize(e,t){super.resize(e,t),this._state=void 0}reset(e){this._clearCurrentLink()}_clearCurrentLink(){if(this._state){this._clearCells(this._state.x1,this._state.y1,this._state.cols-this._state.x1,1);let e=this._state.y2-this._state.y1-1;e>0&&this._clearCells(0,this._state.y1+1,this._state.cols,e),this._clearCells(0,this._state.y2,this._state.x2,1),this._state=void 0}}_handleShowLinkUnderline(e){if(e.fg===257?this._ctx.fillStyle=this._themeService.colors.background.css:e.fg!==void 0&&g_(e.fg)?this._ctx.fillStyle=this._themeService.colors.ansi[e.fg].css:this._ctx.fillStyle=this._themeService.colors.foreground.css,e.y1===e.y2)this._fillBottomLineAtCells(e.x1,e.y1,e.x2-e.x1);else{this._fillBottomLineAtCells(e.x1,e.y1,e.cols-e.x1);for(let t=e.y1+1;t<e.y2;t++)this._fillBottomLineAtCells(0,t,e.cols);this._fillBottomLineAtCells(0,e.y2,e.x2)}this._state=e}_handleHideLinkUnderline(e){this._clearCurrentLink()}},uv=typeof window==`object`?window:globalThis,dv=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new i_,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new i_,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};dv.INSTANCE=new dv;var fv=dv;function pv(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}fv.INSTANCE.onDidChangeZoomLevel,fv.INSTANCE.onDidChangeFullscreen;var mv=typeof navigator==`object`?navigator.userAgent:``;mv.indexOf(`Firefox`);var hv=mv.indexOf(`AppleWebKit`)>=0;!(mv.indexOf(`Chrome`)>=0)&&mv.indexOf(`Safari`),mv.indexOf(`Electron/`),mv.indexOf(`Android`);var gv=!1;if(typeof uv.matchMedia==`function`){let e=uv.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=uv.matchMedia(`(display-mode: fullscreen)`);gv=e.matches,pv(uv,e,({matches:e})=>{gv&&t.matches||(gv=e)})}function _v(){return gv}var vv=`en`,yv=!1,bv=!1,xv=!1,Sv=vv,Cv,wv=globalThis,Tv;typeof wv.vscode<`u`&&typeof wv.vscode.process<`u`?Tv=wv.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(Tv=process);var Ev=typeof Tv?.versions?.electron==`string`&&Tv?.type===`renderer`;if(typeof Tv==`object`){Tv.platform,Tv.platform,yv=Tv.platform===`linux`,yv&&Tv.env.SNAP&&Tv.env.SNAP_REVISION,Tv.env.CI||Tv.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Sv=vv;let e=Tv.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,Sv=t.resolvedLanguage||vv,t.languagePack?.translationsConfigFile}catch{}bv=!0}else typeof navigator==`object`&&!Ev?(Cv=navigator.userAgent,Cv.indexOf(`Windows`),Cv.indexOf(`Macintosh`),(Cv.indexOf(`Macintosh`)>=0||Cv.indexOf(`iPad`)>=0||Cv.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,yv=Cv.indexOf(`Linux`)>=0,Cv?.indexOf(`Mobi`),xv=!0,Sv=globalThis._VSCODE_NLS_LANGUAGE||vv,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var Dv=bv;xv&&typeof wv.importScripts==`function`&&wv.origin;var Ov=Cv,kv=Sv,Av;(e=>{function t(){return kv}e.value=t;function n(){return kv.length===2?kv===`en`:kv.length>=3?kv[0]===`e`&&kv[1]===`n`&&kv[2]===`-`:!1}e.isDefaultVariant=n;function r(){return kv===`en`}e.isDefault=r})(Av||={});var jv=typeof wv.postMessage==`function`&&!wv.importScripts;(()=>{if(jv){let e=[];wv.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),wv.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var Mv=!!(Ov&&Ov.indexOf(`Chrome`)>=0);Ov&&Ov.indexOf(`Firefox`),!Mv&&Ov&&Ov.indexOf(`Safari`),Ov&&Ov.indexOf(`Edg/`),Ov&&Ov.indexOf(`Android`);var Nv=typeof navigator==`object`?navigator:{};Dv||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||Nv&&Nv.clipboard&&Nv.clipboard.writeText,Dv||Nv&&Nv.clipboard&&Nv.clipboard.readText,Dv||_v()||Nv.keyboard,`ontouchstart`in uv||Nv.maxTouchPoints,uv.PointerEvent&&(`ontouchstart`in uv||navigator.maxTouchPoints);var Pv=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Fv=new Pv,Iv=new Pv,Lv=new Pv;Array(230);var Rv;(e=>{function t(e){return Fv.keyCodeToStr(e)}e.toString=t;function n(e){return Fv.strToKeyCode(e)}e.fromString=n;function r(e){return Iv.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return Lv.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return Iv.strToKeyCode(e)||Lv.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return Fv.keyCodeToStr(e)}e.toElectronAccelerator=o})(Rv||={});var zv=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),Bv;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof Vv?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Wg.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:zv})})(Bv||={});var Vv=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?zv:(this._emitter||=new i_,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var Hv;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(Hv||={});var Uv=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new i_,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await Wg.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};Uv.EMPTY=Uv.fromArray([]);function Wv(e){return 55296<=e&&e<=56319}function Gv(e){return 56320<=e&&e<=57343}function Kv(e,t){return(e-55296<<10)+(t-56320)+65536}function qv(e){return Jv(e,0)}function Jv(e,t){switch(typeof e){case`object`:return e===null?Yv(349,t):Array.isArray(e)?Qv(e,t):$v(e,t);case`string`:return Zv(e,t);case`boolean`:return Xv(e,t);case`number`:return Yv(e,t);case`undefined`:return Yv(937,t);default:return Yv(617,t)}}function Yv(e,t){return(t<<5)-t+e|0}function Xv(e,t){return Yv(e?433:863,t)}function Zv(e,t){t=Yv(149417,t);for(let n=0,r=e.length;n<r;n++)t=Yv(e.charCodeAt(n),t);return t}function Qv(e,t){return t=Yv(104579,t),e.reduce((e,t)=>Jv(t,e),t)}function $v(e,t){return t=Yv(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=Zv(n,t),Jv(e[n],t)),t)}function ey(e,t,n=32){let r=n-t,i=~((1<<r)-1);return(e<<t|(i&e)>>>r)>>>0}function ty(e,t=0,n=e.byteLength,r=0){for(let i=0;i<n;i++)e[t+i]=r}function ny(e,t,n=`0`){for(;e.length<t;)e=n+e;return e}function ry(e,t=32){return e instanceof ArrayBuffer?Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,`0`)).join(``):ny((e>>>0).toString(16),t/4)}var iy=class e{constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(e){let t=e.length;if(t===0)return;let n=this._buff,r=this._buffLen,i=this._leftoverHighSurrogate,a,o;for(i===0?(a=e.charCodeAt(0),o=0):(a=i,o=-1,i=0);;){let s=a;if(Wv(a))if(o+1<t){let t=e.charCodeAt(o+1);Gv(t)?(o++,s=Kv(a,t)):s=65533}else{i=a;break}else Gv(a)&&(s=65533);if(r=this._push(n,r,s),o++,o<t)a=e.charCodeAt(o);else break}this._buffLen=r,this._leftoverHighSurrogate=i}_push(e,t,n){return n<128?e[t++]=n:n<2048?(e[t++]=192|(n&1984)>>>6,e[t++]=128|(n&63)>>>0):n<65536?(e[t++]=224|(n&61440)>>>12,e[t++]=128|(n&4032)>>>6,e[t++]=128|(n&63)>>>0):(e[t++]=240|(n&1835008)>>>18,e[t++]=128|(n&258048)>>>12,e[t++]=128|(n&4032)>>>6,e[t++]=128|(n&63)>>>0),t>=64&&(this._step(),t-=64,this._totalLen+=64,e[0]=e[64],e[1]=e[65],e[2]=e[66]),t}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),ry(this._h0)+ry(this._h1)+ry(this._h2)+ry(this._h3)+ry(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,ty(this._buff,this._buffLen),this._buffLen>56&&(this._step(),ty(this._buff));let e=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(e/4294967296),!1),this._buffDV.setUint32(60,e%4294967296,!1),this._step()}_step(){let t=e._bigBlock32,n=this._buffDV;for(let e=0;e<64;e+=4)t.setUint32(e,n.getUint32(e,!1),!1);for(let e=64;e<320;e+=4)t.setUint32(e,ey(t.getUint32(e-12,!1)^t.getUint32(e-32,!1)^t.getUint32(e-56,!1)^t.getUint32(e-64,!1),1),!1);let r=this._h0,i=this._h1,a=this._h2,o=this._h3,s=this._h4,c,l,u;for(let e=0;e<80;e++)e<20?(c=i&a|~i&o,l=1518500249):e<40?(c=i^a^o,l=1859775393):e<60?(c=i&a|i&o|a&o,l=2400959708):(c=i^a^o,l=3395469782),u=ey(r,5)+c+s+l+t.getUint32(e*4,!1)&4294967295,s=o,o=a,a=ey(i,30),i=r,r=u;this._h0=this._h0+r&4294967295,this._h1=this._h1+i&4294967295,this._h2=this._h2+a&4294967295,this._h3=this._h3+o&4294967295,this._h4=this._h4+s&4294967295}};iy._bigBlock32=new DataView(new ArrayBuffer(320));var{registerWindow:ay,getWindow:oy,getDocument:sy,getWindows:cy,getWindowsCount:ly,getWindowId:uy,getWindowById:dy,hasWindow:fy,onDidRegisterWindow:py,onWillUnregisterWindow:my,onDidUnregisterWindow:hy}=function(){let e=new Map,t={window:uv,disposables:new Dh};e.set(uv.vscodeWindowId,t);let n=new i_,r=new i_,i=new i_;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return Oh.None;let a=new Dh,o={window:t,disposables:a.add(new Dh)};return e.set(t.vscodeWindowId,o),a.add(Th(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(_y(t,yy.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:uv},getDocument(e){return oy(e).document}}}(),gy=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function _y(e,t,n,r){return new gy(e,t,n,r)}var vy=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};vy.None=new vy(0,0),new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=qv(n),a=r.get(i);if(a)a.users+=1;else{let o=new i_,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(Th(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var yy={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:hv?`webkitAnimationStart`:`animationstart`,ANIMATION_END:hv?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:hv?`webkitAnimationIteration`:`animationiteration`},by=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;function xy(e,t,n,...r){let i=by.exec(t);if(!i)throw Error(`Bad use of emmet`);let a=i[1]||`div`,o;return o=e===`http://www.w3.org/1999/xhtml`?document.createElement(a):document.createElementNS(e,a),i[3]&&(o.id=i[3]),i[4]&&(o.className=i[4].replace(/\./g,` `).trim()),n&&Object.entries(n).forEach(([e,t])=>{typeof t>`u`||(/^on\w+$/.test(e)?o[e]=t:e===`selected`?t&&o.setAttribute(e,`true`):o.setAttribute(e,t))}),o.append(...r),o}function Sy(e,t,...n){return xy(`http://www.w3.org/1999/xhtml`,e,t,...n)}Sy.SVG=function(e,t,...n){return xy(`http://www.w3.org/2000/svg`,e,t,...n)};var Cy=class extends Oh{constructor(e,t,n,r,i,a,o,s,c){super(),this._terminal=e,this._characterJoinerService=t,this._charSizeService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._optionsService=o,this._themeService=s,this._cursorBlinkStateManager=new kh,this._charAtlasDisposable=this._register(new kh),this._observerDisposable=this._register(new kh),this._model=new q_,this._workCell=new w_,this._workCell2=new w_,this._rectangleRenderer=this._register(new kh),this._glyphRenderer=this._register(new kh),this._onChangeTextureAtlas=this._register(new i_),this.onChangeTextureAtlas=this._onChangeTextureAtlas.event,this._onAddTextureAtlasCanvas=this._register(new i_),this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=this._register(new i_),this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._onRequestRedraw=this._register(new i_),this.onRequestRedraw=this._onRequestRedraw.event,this._onContextLoss=this._register(new i_),this.onContextLoss=this._onContextLoss.event,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`);let l={antialias:!1,depth:!1,preserveDrawingBuffer:c};if(this._gl=this._canvas.getContext(`webgl2`,l),!this._gl)throw Error(`WebGL2 not supported `+this._gl);this._register(this._themeService.onChangeColors(()=>this._handleColorChange())),this._cellColorResolver=new mg(this._terminal,this._optionsService,this._model.selection,this._decorationService,this._coreBrowserService,this._themeService),this._core=this._terminal._core,this._renderLayers=[new lv(this._core.screenElement,2,this._terminal,this._core.linkifier,this._coreBrowserService,o,this._themeService)],this.dimensions=ig(),this._devicePixelRatio=this._coreBrowserService.dpr,this._updateDimensions(),this._updateCursorBlink(),this._register(o.onOptionChange(()=>this._handleOptionsChanged())),this._deviceMaxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),this._register(_y(this._canvas,`webglcontextlost`,e=>{console.log(`webglcontextlost event received`),e.preventDefault(),this._contextRestorationTimeout=setTimeout(()=>{this._contextRestorationTimeout=void 0,console.warn(`webgl context not restored; firing onContextLoss`),this._onContextLoss.fire(e)},3e3)})),this._register(_y(this._canvas,`webglcontextrestored`,e=>{console.warn(`webglcontextrestored event received`),clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0,y_(this._terminal),this._initializeWebGLState(),this._requestRedrawViewport()})),this._observerDisposable.value=S_(this._canvas,this._coreBrowserService.window,(e,t)=>this._setCanvasDevicePixelDimensions(e,t)),this._register(this._coreBrowserService.onWindowChange(e=>{this._observerDisposable.value=S_(this._canvas,e,(e,t)=>this._setCanvasDevicePixelDimensions(e,t))})),this._core.screenElement.appendChild(this._canvas),[this._rectangleRenderer.value,this._glyphRenderer.value]=this._initializeWebGLState(),this._isAttached=this._core.screenElement.isConnected,this._register(Th(()=>{for(let e of this._renderLayers)e.dispose();this._canvas.parentElement?.removeChild(this._canvas),y_(this._terminal)}))}get textureAtlas(){return this._charAtlas?.pages[0].canvas}_handleColorChange(){this._refreshCharAtlas(),this._clearModel(!0)}handleDevicePixelRatioChange(){this._devicePixelRatio!==this._coreBrowserService.dpr&&(this._devicePixelRatio=this._coreBrowserService.dpr,this.handleResize(this._terminal.cols,this._terminal.rows))}handleResize(e,t){this._updateDimensions(),this._model.resize(this._terminal.cols,this._terminal.rows);for(let e of this._renderLayers)e.resize(this._terminal,this.dimensions);this._canvas.width=this.dimensions.device.canvas.width,this._canvas.height=this.dimensions.device.canvas.height,this._canvas.style.width=`${this.dimensions.css.canvas.width}px`,this._canvas.style.height=`${this.dimensions.css.canvas.height}px`,this._core.screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._core.screenElement.style.height=`${this.dimensions.css.canvas.height}px`,this._rectangleRenderer.value?.setDimensions(this.dimensions),this._rectangleRenderer.value?.handleResize(),this._glyphRenderer.value?.setDimensions(this.dimensions),this._glyphRenderer.value?.handleResize(),this._refreshCharAtlas(),this._clearModel(!1)}handleCharSizeChanged(){this.handleResize(this._terminal.cols,this._terminal.rows)}handleBlur(){for(let e of this._renderLayers)e.handleBlur(this._terminal);this._cursorBlinkStateManager.value?.pause(),this._requestRedrawViewport()}handleFocus(){for(let e of this._renderLayers)e.handleFocus(this._terminal);this._cursorBlinkStateManager.value?.resume(),this._requestRedrawViewport()}handleSelectionChanged(e,t,n){for(let r of this._renderLayers)r.handleSelectionChanged(this._terminal,e,t,n);this._model.selection.update(this._core,e,t,n),this._requestRedrawViewport()}handleCursorMove(){for(let e of this._renderLayers)e.handleCursorMove(this._terminal);this._cursorBlinkStateManager.value?.restartBlinkAnimation()}_handleOptionsChanged(){this._updateDimensions(),this._refreshCharAtlas(),this._updateCursorBlink()}_initializeWebGLState(){return this._rectangleRenderer.value=new sv(this._terminal,this._gl,this.dimensions,this._themeService),this._glyphRenderer.value=new z_(this._terminal,this._gl,this.dimensions,this._optionsService),this.handleCharSizeChanged(),[this._rectangleRenderer.value,this._glyphRenderer.value]}_refreshCharAtlas(){if(this.dimensions.device.char.width<=0&&this.dimensions.device.char.height<=0){this._isAttached=!1;return}let e=v_(this._terminal,this._optionsService.rawOptions,this._themeService.colors,this.dimensions.device.cell.width,this.dimensions.device.cell.height,this.dimensions.device.char.width,this.dimensions.device.char.height,this._coreBrowserService.dpr,this._deviceMaxTextureSize);this._charAtlas!==e&&(this._onChangeTextureAtlas.fire(e.pages[0].canvas),this._charAtlasDisposable.value=wh(Wg.forward(e.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas),Wg.forward(e.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas))),this._charAtlas=e,this._charAtlas.warmUp(),this._glyphRenderer.value?.setAtlas(this._charAtlas)}_clearModel(e){this._model.clear(),e&&this._glyphRenderer.value?.clear()}clearTextureAtlas(){this._charAtlas?.clearTexture(),this._clearModel(!0),this._requestRedrawViewport()}clear(){this._clearModel(!0);for(let e of this._renderLayers)e.reset(this._terminal);this._cursorBlinkStateManager.value?.restartBlinkAnimation(),this._updateCursorBlink()}renderRows(e,t){if(!this._isAttached)if(this._core.screenElement?.isConnected&&this._charSizeService.width&&this._charSizeService.height)this._updateDimensions(),this._refreshCharAtlas(),this._isAttached=!0;else return;for(let n of this._renderLayers)n.handleGridChanged(this._terminal,e,t);!this._glyphRenderer.value||!this._rectangleRenderer.value||(this._glyphRenderer.value.beginFrame()?(this._clearModel(!0),this._updateModel(0,this._terminal.rows-1)):this._updateModel(e,t),this._rectangleRenderer.value.renderBackgrounds(),this._glyphRenderer.value.render(this._model),(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible)&&this._rectangleRenderer.value.renderCursor())}_updateCursorBlink(){this._coreService.decPrivateModes.cursorBlink??this._terminal.options.cursorBlink?this._cursorBlinkStateManager.value=new x_(()=>{this._requestRedrawCursor()},this._coreBrowserService):this._cursorBlinkStateManager.clear(),this._requestRedrawCursor()}_updateModel(e,t){let n=this._core,r=this._workCell,i,a,o,s,c,l,u=0,d=!0,f,p,m,h,g,_,v,y,b;e=Ty(e,n.rows-1,0),t=Ty(t,n.rows-1,0);let x=this._coreService.decPrivateModes.cursorStyle??n.options.cursorStyle??`block`,S=this._terminal.buffer.active.baseY+this._terminal.buffer.active.cursorY,C=S-n.buffer.ydisp,w=Math.min(this._terminal.buffer.active.cursorX,n.cols-1),T=-1,E=this._coreService.isCursorInitialized&&!this._coreService.isCursorHidden&&(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible);this._model.cursor=void 0;let D=!1;for(a=e;a<=t;a++)for(o=a+n.buffer.ydisp,s=n.buffer.lines.get(o),this._model.lineLengths[a]=0,m=S===o,u=0,c=this._characterJoinerService.getJoinedCharacters(o),y=0;y<n.cols;y++){if(i=this._cellColorResolver.result.bg,s.loadCell(y,r),y===0&&(i=this._cellColorResolver.result.bg),l=!1,d=y>=u,f=y,c.length>0&&y===c[0][0]&&d){p=c.shift();let e=this._model.selection.isCellSelected(this._terminal,p[0],o);for(v=p[0]+1;v<p[1];v++)d&&=e===this._model.selection.isCellSelected(this._terminal,v,o);d&&=!m||w<p[0]||w>=p[1],d?(l=!0,r=new wy(r,s.translateToString(!0,p[0],p[1]),p[1]-p[0]),f=p[1]-1):u=p[1]}if(h=r.getChars(),g=r.getCode(),v=(a*n.cols+y)*H_,this._cellColorResolver.resolve(r,y,o,this.dimensions.device.cell.width),E&&o===S&&(y===w&&(this._model.cursor={x:w,y:C,width:r.getWidth(),style:this._coreBrowserService.isFocused?x:n.options.cursorInactiveStyle,cursorWidth:n.options.cursorWidth,dpr:this._devicePixelRatio},T=w+r.getWidth()-1),y>=w&&y<=T&&(this._coreBrowserService.isFocused&&x===`block`||this._coreBrowserService.isFocused===!1&&n.options.cursorInactiveStyle===`block`)&&(this._cellColorResolver.result.fg=50331648|this._themeService.colors.cursorAccent.rgba>>8&16777215,this._cellColorResolver.result.bg=50331648|this._themeService.colors.cursor.rgba>>8&16777215)),g!==0&&(this._model.lineLengths[a]=y+1),!(this._model.cells[v]===g&&this._model.cells[v+U_]===this._cellColorResolver.result.bg&&this._model.cells[v+W_]===this._cellColorResolver.result.fg&&this._model.cells[v+G_]===this._cellColorResolver.result.ext)&&(D=!0,h.length>1&&(g|=K_),this._model.cells[v]=g,this._model.cells[v+U_]=this._cellColorResolver.result.bg,this._model.cells[v+W_]=this._cellColorResolver.result.fg,this._model.cells[v+G_]=this._cellColorResolver.result.ext,_=r.getWidth(),this._glyphRenderer.value.updateCell(y,a,g,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext,h,_,i),l)){for(r=this._workCell,y++;y<=f;y++)b=(a*n.cols+y)*H_,this._glyphRenderer.value.updateCell(y,a,0,0,0,0,Lh,0,0),this._model.cells[b]=0,this._model.cells[b+U_]=this._cellColorResolver.result.bg,this._model.cells[b+W_]=this._cellColorResolver.result.fg,this._model.cells[b+G_]=this._cellColorResolver.result.ext;y--}}D&&this._rectangleRenderer.value.updateBackgrounds(this._model),this._rectangleRenderer.value.updateCursor(this._model)}_updateDimensions(){!this._charSizeService.width||!this._charSizeService.height||(this.dimensions.device.char.width=Math.floor(this._charSizeService.width*this._devicePixelRatio),this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*this._devicePixelRatio),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.top=this._optionsService.rawOptions.lineHeight===1?0:Math.round((this.dimensions.device.cell.height-this.dimensions.device.char.height)/2),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.char.left=Math.floor(this._optionsService.rawOptions.letterSpacing/2),this.dimensions.device.canvas.height=this._terminal.rows*this.dimensions.device.cell.height,this.dimensions.device.canvas.width=this._terminal.cols*this.dimensions.device.cell.width,this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/this._devicePixelRatio),this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/this._devicePixelRatio),this.dimensions.css.cell.height=this.dimensions.device.cell.height/this._devicePixelRatio,this.dimensions.css.cell.width=this.dimensions.device.cell.width/this._devicePixelRatio)}_setCanvasDevicePixelDimensions(e,t){this._canvas.width===e&&this._canvas.height===t||(this._canvas.width=e,this._canvas.height=t,this._requestRedrawViewport())}_requestRedrawViewport(){this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1})}_requestRedrawCursor(){let e=this._terminal.buffer.active.cursorY;this._onRequestRedraw.fire({start:e,end:e})}},wy=class extends Ig{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}};function Ty(e,t,n=0){return Math.max(Math.min(e,t),n)}var Ey=`di$target`,Dy=`di$dependencies`,Oy=new Map;function ky(e){if(Oy.has(e))return Oy.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);Ay(t,e,r)};return t._id=e,Oy.set(e,t),t}function Ay(e,t,n){t[Ey]===t?t[Dy].push({id:e,index:n}):(t[Dy]=[{id:e,index:n}],t[Ey]=t)}ky(`BufferService`),ky(`CoreMouseService`),ky(`CoreService`),ky(`CharsetService`),ky(`InstantiationService`),ky(`LogService`);var jy=ky(`OptionsService`);ky(`OscLinkService`),ky(`UnicodeService`),ky(`DecorationService`);var My={trace:0,debug:1,info:2,warn:3,error:4,off:5},Ny=`xterm.js: `,Py=class extends Oh{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),Fy=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=My[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:Ny)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};Py=Zm([Qm(0,jy)],Py);var Fy,Iy=class extends Oh{constructor(e){if(Fh&&Ih()<16&&!document.createElement(`canvas`).getContext(`webgl2`,{antialias:!1,depth:!1,preserveDrawingBuffer:!0}))throw Error(`Webgl2 is only supported on Safari 16 and above`);super(),this._preserveDrawingBuffer=e,this._onChangeTextureAtlas=this._register(new i_),this.onChangeTextureAtlas=this._onChangeTextureAtlas.event,this._onAddTextureAtlasCanvas=this._register(new i_),this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=this._register(new i_),this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._onContextLoss=this._register(new i_),this.onContextLoss=this._onContextLoss.event}activate(e){let t=e._core;if(!e.element){this._register(t.onWillOpen(()=>this.activate(e)));return}this._terminal=e;let n=t.coreService,r=t.optionsService,i=t,a=i._renderService,o=i._characterJoinerService,s=i._charSizeService,c=i._coreBrowserService,l=i._decorationService;i._logService;let u=i._themeService;this._renderer=this._register(new Cy(e,o,s,c,n,l,r,u,this._preserveDrawingBuffer)),this._register(Wg.forward(this._renderer.onContextLoss,this._onContextLoss)),this._register(Wg.forward(this._renderer.onChangeTextureAtlas,this._onChangeTextureAtlas)),this._register(Wg.forward(this._renderer.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas)),this._register(Wg.forward(this._renderer.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas)),a.setRenderer(this._renderer),this._register(Th(()=>{if(this._terminal._core._store._isDisposed)return;let t=this._terminal._core._renderService;t.setRenderer(this._terminal._core._createRenderer()),t.handleResize(e.cols,e.rows)}))}get textureAtlas(){return this._renderer?.textureAtlas}clearTextureAtlas(){this._renderer?.clearTextureAtlas()}},Ly={background:`#181818`,foreground:`#ffffff`,cursor:`#ffffff`,cursorAccent:`#181818`,selectionBackground:`rgba(51, 156, 255, 0.32)`,selectionInactiveBackground:`rgba(51, 156, 255, 0.22)`,black:`#484f58`,red:`#fa423e`,green:`#40c977`,yellow:`#d29922`,blue:`#339cff`,magenta:`#ad7bf9`,cyan:`#39c5cf`,white:`#b1bac4`,brightBlack:`#6e7681`,brightRed:`#ffa198`,brightGreen:`#56d364`,brightYellow:`#e3b341`,brightBlue:`#79c0ff`,brightMagenta:`#d2a8ff`,brightCyan:`#56d4dd`,brightWhite:`#f0f6fc`,scrollbarSliderBackground:`rgba(139, 148, 158, 0.32)`,scrollbarSliderHoverBackground:`rgba(139, 148, 158, 0.44)`,scrollbarSliderActiveBackground:`rgba(139, 148, 158, 0.56)`};function Ry(){return typeof document<`u`&&document.body?.dataset.appearance===`dark`?Ly:{...Br,selectionInactiveBackground:Br.selectionBackground,scrollbarSliderBackground:`rgba(87, 96, 106, 0.24)`,scrollbarSliderHoverBackground:`rgba(87, 96, 106, 0.34)`,scrollbarSliderActiveBackground:`rgba(87, 96, 106, 0.44)`}}function zy(e,t){let n=t||Ry();e.options.theme=n,Vy(e,n),e.refresh?.(0,Math.max(0,e.rows-1))}function By(e){e.querySelectorAll(`textarea`).forEach((e,t)=>{e.setAttribute(`name`,t===0?`farming-terminal-input`:`farming-terminal-input-${t+1}`),e.setAttribute(`autocomplete`,`off`),e.setAttribute(`autocorrect`,`off`),e.setAttribute(`autocapitalize`,`none`),e.setAttribute(`spellcheck`,`false`),e.setAttribute(`data-lpignore`,`true`),e.setAttribute(`data-1p-ignore`,`true`),e.setAttribute(`data-bwignore`,`true`),e.setAttribute(`data-form-type`,`other`)})}function Vy(e,t=Ry()){let n=Wy(e);if(!n)return;let r=t.background,i=t.foreground;By(n),n.style.backgroundColor=r,n.style.color=i,n.querySelectorAll(`.xterm-screen, .xterm-viewport, .xterm-rows, .xterm-helper-textarea`).forEach(e=>{e.style.backgroundColor=r,e.style.color=i})}function Hy(e,t){if(typeof window>`u`)return()=>{};let n=()=>{Vy(e,t||Ry()),e.refresh?.(0,Math.max(0,e.rows-1))},r=window.requestAnimationFrame(n),i=window.setTimeout(n,80);return()=>{window.cancelAnimationFrame(r),window.clearTimeout(i)}}function Uy(e,t){if(typeof document>`u`)return;let n=[];zy(e,t);let r=new MutationObserver(()=>{zy(e,t),n.push(Hy(e,t))});r.observe(document.body,{attributes:!0,attributeFilter:[`data-appearance`]});let i=e.dispose.bind(e);e.dispose=()=>{r.disconnect(),n.forEach(e=>e()),n.length=0,i()}}function Wy(e){return e.element instanceof HTMLElement?e.element:null}function Gy(e){let t=Wy(e),n=t?.querySelector(`.xterm-screen`);return n instanceof HTMLElement?n:t}function Ky(e){let t=Gy(e);if(!t||e.cols<=0||e.rows<=0)return;let n=t.getBoundingClientRect();if(!(n.width<=0||n.height<=0))return{width:n.width/e.cols,height:n.height/e.rows}}function qy(e){return Math.max(0,e.buffer.active.viewportY)}var Jy=new Set;function Yy(){let e=[];return Jy.forEach(({serializeAddon:t,terminal:n})=>{let r=Gy(n);if(!r||!r.isConnected)return;let i=r.getBoundingClientRect();if(i.width<=0||i.height<=0)return;let a=qy(n),o=t.serializeAsHTML({includeGlobalBackground:!0,range:{startLine:a,endLine:a+Math.max(0,n.rows-1),startCol:0}}),s=new DOMParser().parseFromString(o,`text/html`).querySelector(`pre > div`);if(!(s instanceof HTMLElement))return;let c=document.createElement(`div`);c.dataset.petXtermSnapshot=``,c.setAttribute(`aria-hidden`,`true`),Object.assign(c.style,{position:`fixed`,zIndex:`2147480000`,left:`${i.left}px`,top:`${i.top}px`,width:`${i.width}px`,height:`${i.height}px`,overflow:`hidden`,pointerEvents:`none`,visibility:`hidden`,background:n.options.theme?.background??`#181818`});let l=s.cloneNode(!0);Object.assign(l.style,{width:`max-content`,minWidth:`100%`,margin:`0`,lineHeight:String(n.options.lineHeight),whiteSpace:`pre`}),c.append(l),document.body.append(c),e.push(c)}),()=>e.forEach(e=>e.remove())}function Xy(){return typeof document<`u`&&document.body?.dataset.appearance===`dark`?{matchBackground:`#3b3f1c`,matchBorder:`#8a7b24`,matchOverviewRuler:`#8a7b24`,activeMatchBackground:`#8a5a12`,activeMatchBorder:`#d29922`,activeMatchColorOverviewRuler:`#d29922`}:{matchBackground:`#fff4a3`,matchBorder:`#d4a72c`,matchOverviewRuler:`#d4a72c`,activeMatchBackground:`#ffd33d`,activeMatchBorder:`#9a6700`,activeMatchColorOverviewRuler:`#9a6700`}}function Zy(e,t,n,r){let i=e,a=e.open.bind(e),o=e.dispose.bind(e),s=e.scrollToLine.bind(e),c=e.scrollToBottom.bind(e),l=new Set,u=null,d=``,f=`pending`,p=null,m=null,h={serializeAddon:n,terminal:e};Jy.add(h);let g=e=>{f!==`failed`&&(f=`failed`,p=e,l.forEach(t=>t(e)))};return t.onDidChangeResults(e=>{u=e}),i.__farmingTerminalEngine=`xterm`,i.getRendererType=()=>f,i.onRendererFailure=e=>(l.add(e),p&&e(p),{dispose:()=>l.delete(e)}),i.open=t=>{a(t);let n=new Iy;try{e.loadAddon(n)}catch(t){try{n.dispose()}catch{}let r=t instanceof Error?`: ${t.message}`:``,i=Error(`Terminal WebGL renderer failed to initialize${r}`);throw f=`failed`,p=i,e.dispose(),i}f=`webgl`,m=n.onContextLoss(()=>{g(Error(`Terminal WebGL context was lost; reopen the terminal to retry.`))})},i.dispose=()=>{m?.dispose(),m=null,Jy.delete(h),l.clear(),o()},i.getScrollbackLength=()=>Math.max(0,e.buffer.active.baseY),i.getVisibleBufferBase=()=>qy(e),i.getCellMetrics=()=>Ky(e),i.getScreenElement=()=>Gy(e),i.getTerminalElement=()=>Wy(e),i.syncAppearanceTheme=()=>zy(e,r),i.reattach=()=>{Wy(e)&&(Vy(e),e.refresh?.(0,Math.max(0,e.rows-1)))},i.forceRedraw=()=>{e.clearTextureAtlas(),Vy(e),e.refresh?.(0,Math.max(0,e.rows-1))},i.clearTerminalSelection=()=>e.clearSelection(),i.clearBuffer=()=>{e.write(`\x1B[2J\x1B[3J\x1B[H`),e.clearSelection()},i.selectAll=()=>e.selectAll(),i.search=(n,r=`next`,i={})=>{let a=n.trim();if(!a)return t.clearDecorations(),e.clearSelection(),u=null,d=``,{found:!1,resultIndex:0,resultCount:0};let o={caseSensitive:i.caseSensitive===!0,wholeWord:i.wholeWord===!0,regex:i.regex===!0,incremental:i.incremental===!0,decorations:Xy()},s=[o.caseSensitive,o.wholeWord,o.regex].join(`:`);d&&d!==s&&(t.clearDecorations(),e.clearSelection(),u=null),d=s;let c=!1;try{c=r===`previous`?t.findPrevious(a,o):t.findNext(a,o)}catch(n){if(o.regex)return t.clearDecorations(),e.clearSelection(),u=null,d=``,{found:!1,resultIndex:0,resultCount:0};throw n}return{found:c,resultIndex:u?.resultIndex,resultCount:u?.resultCount}},i.clearSearch=()=>{t.clearDecorations(),e.clearSelection(),u=null,d=``},i.scrollToLine=t=>{let n=Number.isFinite(t)?Math.max(0,t):0;s(Math.max(0,e.buffer.active.baseY-n))},i.scrollToBottom=()=>{Math.max(0,e.buffer.active.baseY),c()},i.wasmTerm={getCursor:()=>({x:e.buffer.active.cursorX,y:e.buffer.active.cursorY,visible:e.textarea?document.activeElement===e.textarea:!0})},Object.defineProperty(i,`viewportY`,{configurable:!0,get:()=>Math.max(0,e.buffer.active.baseY-qy(e)),set:t=>{let n=Number.isFinite(t)?Math.max(0,Number(t)):0;s(Math.max(0,e.buffer.active.baseY-n))}}),i}async function Qy(e){let t=e?.fontSize??12,n=e?.theme===`dark`?Ly:void 0,r=new mf({allowProposedApi:!0,altClickMovesCursor:!1,cols:80,convertEol:!0,cursorBlink:!1,cursorInactiveStyle:`none`,cursorStyle:`block`,drawBoldTextInBrightColors:!1,fontFamily:Vr,fontSize:t,lineHeight:1.18,linkHandler:{allowNonHttpProtocols:!1,activate:(e,t)=>{window.open(t,`_blank`,`noopener,noreferrer`)}},macOptionClickForcesSelection:!0,minimumContrastRatio:4.5,rightClickSelectsWord:!1,rows:30,scrollback:5e3,scrollOnEraseInDisplay:!0,scrollOnUserInput:!0,smoothScrollDuration:0,theme:n||Ry(),wordSeparator:` ()[]{}'"\`─`,windowOptions:{getCellSizePixels:!0,getWinSizeChars:!0,getWinSizePixels:!0}}),i=new Dm({highlightLimit:2e3}),a=new qm;return r.loadAddon(new tp(void 0,ue())),r.loadAddon(i),r.loadAddon(a),Uy(r,n),{terminal:Zy(r,i,a,n),fitAddon:new _f}}function $y(e){return e.__farmingTerminalEngine===`xterm`}function eb(){return typeof window>`u`?`xterm`:window.localStorage.getItem(`farmingTerminalEngine`)===`ghostty`?`ghostty`:`xterm`}async function tb(e){if(eb()===`ghostty`){let t=await Gr(e);return t?{terminal:t.terminal,fitAddon:t.fitAddon}:null}return await Qy(e)}function nb(e){let t=0,n=0,r=0,i=0,a=()=>`(?<line${t++}>\\d+)`,o=()=>`(?<column${n++}>\\d+)`,s=()=>`(?<endLine${r++}>\\d+)`,c=()=>`(?<endColumn${i++}>\\d+)`,l=e?`$`:``,u=[`(?::|#| |['"],|, )${a()}([:.]${o()}(?:-(?:${s()}\\.)?${c()})?)?${l}`,`['"]?(?:,? |: ?| on )lines? ${a()}(?:-${s()})?(?:,? (?:col(?:umn)?|characters?) ${o()}(?:-${c()})?)?${l}`,`:? ?[\\[\\(]${a()}(?:(?:, ?|:)${o()})?[\\]\\)]${l}`].join(`|`).replace(/ /g,`[\\u00a0 ]`);return RegExp(`(${u})`,e?void 0:`g`)}var rb=nb(!1),ib=/(?<path>(?:file:\/\/\/)?[^\s|<>\[\({][^\s|<>]*)$/;function ab(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0?t:void 0}function ob(e){let t=e.groups||{};return{lineNumber:ab(t.line0||t.line1||t.line2),column:ab(t.column0||t.column1||t.column2),endLineNumber:ab(t.endLine0||t.endLine1||t.endLine2),endColumn:ab(t.endColumn0||t.endColumn1||t.endColumn2),range:{index:e.index,text:e[0]}}}function sb(e){let t=[];for(rb.lastIndex=0;;){let n=rb.exec(e);if(!n)break;let r=ob(n);if(e[r.range.index+r.range.text.length]===`/`)continue;let i=e.slice(0,r.range.index).match(ib),a=i?.groups?.path;if(!a||i.index===void 0)continue;let o=a,s=i.index,c,l=o.match(/^(?<prefix>['"]+)/);if(l?.groups?.prefix){if(c={index:s,text:l.groups.prefix},o=o.slice(c.text.length),!o.trim())continue;if(c.text.length>1&&/^['"]/.test(r.range.text)&&c.text[c.text.length-1]===r.range.text[0]){let e=c.text.length-1;c={index:c.index+e,text:c.text.slice(-1)},s+=e}}t.push({path:{index:s+(c?.text.length||0),text:o},...c?{prefix:c}:{},suffix:r});for(let e of o.matchAll(/[\[(](?![\])])/g))t.push({path:{index:s+(c?.text.length||0)+e.index+1,text:o.slice(e.index+1)},...c?{prefix:c}:{},suffix:r})}return t}var cb="`",lb=String.raw`(?:\.\.?|\~|file:\/\/)`,ub=String.raw`\/`,db=String.raw`[^\0<>\?\s!${cb}&*()'":;\\]`,fb=String.raw`[^\0<>\?\s!${cb}&*()\[\]'":;\\]`,pb=`(?:(?:`+lb+`|(?:`+fb+db+`*))?(?:`+ub+`(?:`+db+`)+)+)`,mb=String.raw`(?:\\\\\?\\|file:\/\/\/)?[a-zA-Z]:`,hb=String.raw`\.\.?|\~`,gb=String.raw`(?:\\|\/)`,_b=String.raw`[^\0<>\?\|\/\s!${cb}&*()'":;]`,vb=String.raw`[^\0<>\?\|\/\s!${cb}&*()\[\]'":;]`,yb=`(?:(?:(?:`+mb+`|`+hb+`)|(?:`+vb+_b+`*))?(?:`+gb+`(?:`+_b+`)+)+)`,bb=/^[abciow12]\//,xb=/^[-+]{3} [abciow12]\//;function Sb(e,t){let n=new RegExp(t===`windows`?yb:pb,`g`),r=[];for(;;){let t=n.exec(e);if(!t)break;let i=t[0],a=t.index;if(!i)break;(xb.test(e)&&a===4||e.startsWith(`diff --git`)&&bb.test(i))&&(i=i.slice(2),a+=2),r.push({path:{index:a,text:i}})}return r}function Cb(e,t){let n=e.prefix?.index??e.path.index,r=(e.suffix?.range.index??e.path.index+e.path.text.length-1)+(e.suffix?.range.text.length??1),i=t.prefix?.index??t.path.index;return n<(t.suffix?.range.index??t.path.index+t.path.text.length-1)+(t.suffix?.range.text.length??1)&&i<r}function wb(e,t=`auto`){let n=sb(e),r=(t===`auto`?[`posix`,`windows`]:[t]).flatMap(t=>Sb(e,t)),i=[...n];for(let e of r)i.some(t=>Cb(t,e))||i.push(e);return i.sort((e,t)=>e.path.index-t.path.index)}var Tb=2048,Eb=2e3,Db=1024,Ob=10,kb=100,Ab=100,jb=/[ ()[\]{}',"`─‘’“”|\uE0B0-\uE0BF]/gu,Mb=new Set([`Dockerfile`,`Gemfile`,`LICENSE`,`Makefile`,`README`]),Nb=[/^ *File (?<link>"(?<path>.+)"(?:, line (?<line>\d+)(?:, (?:col(?:umn)?|character) (?<col>\d+))?)?)/,/^ +FILE +(?<link>(?<path>.+)(?::(?<line>\d+)(?::(?<col>\d+))?)?)/,/^(?:PS\s+)?(?<link>(?<path>[^>]+))>/],Pb=[/^(?<link>(?<path>.+)\((?<line>\d+)(?:, ?(?<col>\d+))?\)) ?:/,/^(?<link>(?<path>.+):(?<line>\d+)(?::(?<col>\d+))?) ?:/],Fb=/^ *(?<link>(?<path>.+))/;function Ib(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function Lb(e){let t=c.computeLinks({getLineCount:()=>1,getLineContent:()=>e}),n=[];for(let e of t){let t=String(e.url||``);t.length>Tb||!Ib(t)||n.push({kind:`url`,startIndex:e.range.startColumn-1,length:e.range.endColumn-e.range.startColumn,text:t})}return n}function Rb(e){let t=e.split(/[\\/]/).filter(Boolean).pop()||e;return e.includes(`/`)||e.includes(`\\`)||/^[A-Za-z]:/.test(e)||t.includes(`.`)||Mb.has(t)||/^[A-Z][A-Za-z0-9_-]*file$/.test(t)}function zb(e){return!e||e.length>Db||e===`.`||e===`..`?!1:Rb(e)}function Bb(e){if(!e.startsWith(`file://`))return e;try{let t=new URL(e),n=decodeURIComponent(t.pathname);return t.hostname&&(n=`//${t.hostname}${n}`),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1)),n}catch{return e}}function Vb(e,t){let n=Bb(e).replace(/^\.\/+/,``);return(/^\s*(?:---|\+\+\+)\s+[ab]\//.test(t)||/^\s*diff --git\s+(?:a|b)\//.test(t))&&(n=n.replace(/^[ab]\//,``)),n}function Hb(e,t){let n=Vb(t.path.text,e);if(!zb(n))return null;let r=t.prefix?.index??t.path.index,i=t.suffix?t.suffix.range.index+t.suffix.range.text.length:t.path.index+t.path.text.length;return{kind:`path`,startIndex:r,length:i-r,text:e.slice(r,i),pathTarget:{path:n,...t.suffix?.lineNumber===void 0?{}:{lineNumber:t.suffix.lineNumber},...t.suffix?.column===void 0?{}:{column:t.suffix.column},...t.suffix?.endLineNumber===void 0?{}:{endLineNumber:t.suffix.endLineNumber},...t.suffix?.endColumn===void 0?{}:{endColumn:t.suffix.endColumn}}}}function Ub(e,t){for(let n of t){let t=e.match(n),r=t?.groups,i=r?.link,a=r?.path;if(!t||!i||!a||i.length>Db)continue;let o=Vb(a,e);if(!zb(o))continue;let s=r?.line?Number.parseInt(r.line,10):void 0,c=r?.col?Number.parseInt(r.col,10):void 0;if(!(s!==void 0&&s<=0)&&!(c!==void 0&&c<=0))return{kind:`path`,startIndex:t.index===void 0?e.indexOf(i):t.index+t[0].indexOf(i),length:i.length,text:i,pathTarget:{path:o,...s===void 0?{}:{lineNumber:s},...c===void 0?{}:{column:c}}}}return null}function Wb(e){if(!e||e.length>Eb)return[];let t=Ub(e,Nb);if(t)return[t];let n=Ub(e,Pb);if(n?.pathTarget?.path.match(/\s/))return[n];let r=[];for(let t of wb(e)){if(r.length>=Ob)break;let n=Hb(e,t);n&&(r.some(e=>Jb(n.startIndex,n.length,e.startIndex,e.length))||r.push(n))}if(r.length>0)return r.sort((e,t)=>e.startIndex-t.startIndex);let i=Ub(e,[Fb]);return i?[i]:[]}function Gb(e,t){if(!e||e.length>Eb)return[];let n=e.match(/^ *(?<link>(?<line>\d+):(?<col>\d+)?)/);if(n?.groups?.link&&n.groups.line){let r=t.slice(0,kb).find(e=>!/^\s*\d/.test(e))?.trim(),i=r?Vb(r,r):``;if(zb(i)){let t=Number.parseInt(n.groups.line,10),r=n.groups.col?Number.parseInt(n.groups.col,10):1;if(t>0&&r>0)return[{kind:`path`,startIndex:n.index===void 0?e.indexOf(n.groups.link):n.index+n[0].indexOf(n.groups.link),length:n.groups.link.length,text:n.groups.link,pathTarget:{path:i,lineNumber:t,column:r}}]}}let r=e.match(/^(?<link>@@ .+ \+(?<line>\d+),(?<count>\d+) @@)/);if(!r?.groups?.link||!r.groups.line)return[];let i=t.slice(0,kb).map(e=>e.match(/\+\+\+ b\/(?<path>.+)/)).find(Boolean),a=i?.groups?.path?Vb(i.groups.path,i.groups.path):``;if(!zb(a))return[];let o=Number.parseInt(r.groups.line,10),s=r.groups.count?Number.parseInt(r.groups.count,10):0;return o<=0||s<0?[]:[{kind:`path`,startIndex:r.index??0,length:r.groups.link.length,text:r.groups.link,pathTarget:{path:a,lineNumber:o,column:1,...s>0?{endLineNumber:o+s}:{}}}]}function Kb(e,t){return Wb(e).find(e=>t>=e.startIndex&&t<e.startIndex+e.length)??null}function qb(e,t,n){if(!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)||t<=0||n<=0)return null;let r=Math.floor(e/t);return r>=0&&r<n?r:null}function Jb(e,t,n,r){let i=e+t;return e<n+r&&n<i}function Yb(e){let t=e.trim();return Lb(t).find(e=>e.startIndex===0)?.text??t}function Xb(e,t){return Lb(e).find(e=>t>=e.startIndex&&t<e.startIndex+e.length)?.text??null}function Zb(e){return Lb(e)}function Qb(e){if(!e||e.length>Eb)return[];let t=[],n=0;for(jb.lastIndex=0;;){let r=jb.exec(e),i=r?.index??e.length,a=e.slice(n,i),o=a.length;if(a.endsWith(`:`)&&(a=a.slice(0,-1),--o),a&&a.length<=Ab&&t.push({kind:`search`,startIndex:n,length:o,text:a}),!r)break;n=r.index+r[0].length}return t}function $b(e,t){return Qb(e).find(e=>t>=e.startIndex&&t<e.startIndex+e.length)?.text??null}function ex(e,t,n=!1){let r=Zb(e),i=t?Wb(e).filter(e=>!r.some(t=>Jb(e.startIndex,e.length,t.startIndex,t.length))):[],a=[...r,...i],o=n?Qb(e).filter(e=>!a.some(t=>Jb(e.startIndex,e.length,t.startIndex,t.length))):[];return[...a,...o].sort((e,t)=>e.startIndex-t.startIndex)}function tx(e,t){let n=Math.max(0,e.startIndex),r=Math.max(n,e.startIndex+e.length-1),i=t.startRow+Math.floor(n/t.cols),a=t.startRow+Math.floor(r/t.cols);return{start:{x:n%t.cols+1,y:i+1},end:{x:r%t.cols+1,y:a+1}}}function nx(e){let t={...e.start},n={...e.end};return t.y>n.y||t.y===n.y&&t.x>n.x?{start:n,end:t}:{start:t,end:n}}function rx(e){if(!e||(typeof e.getWidth==`function`?e.getWidth():1)===0)return``;if(typeof e.getChars==`function`)return e.getChars();let t=typeof e.getCode==`function`?e.getCode():0;return t>0?String.fromCodePoint(t):``}function ix(e){return!!(e&&typeof e.getWidth==`function`&&e.getWidth()===0)}function ax(e,t,n){if(!e||typeof e.getCell!=`function`)return null;let r=``,i=Math.max(t,n);for(let n=Math.max(0,t);n<=i;n+=1){let t=e.getCell(n);t&&(r+=rx(t))}return r.trimEnd()}function ox(e,t){if(typeof t.getLine!=`function`)return null;let{start:n,end:r}=nx(e),i=[];for(let e=n.y;e<=r.y;e+=1){let a=t.getLine(e),o=e===n.y?n.x:0,s=typeof a?.length==`number`?a.length-1:r.x,c=ax(a,o,e===r.y?r.x:s);if(c===null)return null;let l=e===n.y||a?.isWrapped?``:`
151
+ `;i.push(`${l}${c}`)}return i.join(``)}function sx(e,t,n){if(!e.includes(`
152
+ `))return e;let{start:r}=nx(t),i=e.split(`
153
+ `);return i.length<=1?e:i.reduce((e,t,i)=>{if(i===0)return t;let a=r.y+i;return`${e}${n.getLine?.(a)?.isWrapped?``:`
154
+ `}${t}`},``)}function cx(e){let t=e.getSelection?.()||``,n=e.getSelectionPosition?.(),r=e.buffer?.active;if(!n||!r||typeof r.getLine!=`function`)return t;let i=ox(n,r);return i===null?sx(t,n,r):i}function lx(e){if(!e.includes(`
155
+ `))return e;let t=Yb(e.split(/\r?\n/).map((e,t)=>t===0?e.trimEnd():e.trim()).join(``));return Ib(t)?t:e}function ux(e){return e.length>0&&!/\s/u.test(e)}function dx(e,t,n){return Math.max(1,(t.row-e.row)*n+(t.col-e.col)+1)}function fx(e){let t=e.getScrollbackLength?.();return Number.isFinite(t)?Math.max(0,Number(t)):0}function px(e){let t=Number(e.viewportY||0);return Number.isFinite(t)?Math.max(0,t):0}function mx(e){let t=e.getVisibleBufferBase?.();return Number.isFinite(t)?Math.max(0,Number(t)):px(e)}function hx(e){return px(e.terminal)<=0}function gx(e){e.followOutputHandler?.({following:e.followOutput,hasUnreadOutput:e.hasUnreadOutput})}function _x(e,t,n,r={}){e.preserveUnreadOutputUntilJump&&!n&&r.allowClearUnread!==!0&&(n=!0),!n&&r.allowClearUnread===!0&&(e.preserveUnreadOutputUntilJump=!1),!(e.followOutput===t&&e.hasUnreadOutput===n)&&(e.followOutput=t,e.hasUnreadOutput=n,gx(e))}function vx(e){e.preserveUnreadOutputUntilJump=!0,_x(e,!1,!0)}function yx(e,t,n){let r=fx(e),i=px(e),a=Math.max(1,Math.floor((e.rows||n)*.9));return t===`PageUp`?Math.min(r,i+a):Math.max(0,i-a)}function bx(e,t,n){let r=fx(e)-n;return Math.max(0,t+r)}function xx(e,t){let n=Math.floor(Number(e)),r=Math.floor(Number(t));return!Number.isFinite(n)||!Number.isFinite(r)||n<40||r<10?null:{cols:n,rows:r}}function Sx(e,t){let n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;let r=t.proposeDimensions();return r?xx(r.cols,r.rows):null}function Cx(e,t,n,r,i={}){let a=xx(t,n);return!a||!i.force&&e.lastNotifiedResize&&e.lastNotifiedResize.cols===a.cols&&e.lastNotifiedResize.rows===a.rows||r(a.cols,a.rows)===!1?!1:(e.lastNotifiedResize=a,e.resizeNotificationCount+=1,!0)}function wx(e){e.lastNotifiedResize=null}function Tx(e,t,n={}){return n.force!==!0&&(e.cols!==t.cols||e.rows!==t.rows)}function Ex(e,t){return!!(e&&t&&e.cols===t.cols&&e.rows===t.rows)}function Dx(e,t,n,r){let i=xx(t,n);return i?e.resizeRequestInFlight?(e.pendingResizeRequest=i,!0):r(i.cols,i.rows)===!1?!1:(e.resizeRequestInFlight=i,!0):!1}function Ox(e,t,n){let r=xx(t,n);if(!Ex(e.resizeRequestInFlight,r))return{matched:!1,preserveLocalGeometry:e.resizeRequestInFlight!==null,next:null};let i=e.pendingResizeRequest;return e.resizeRequestInFlight=null,e.pendingResizeRequest=null,!i||Ex(i,r)?{matched:!0,preserveLocalGeometry:!1,next:null}:{matched:!0,preserveLocalGeometry:!0,next:i}}function kx(e){e.resizeRequestInFlight=null,e.pendingResizeRequest=null}function Ax(e){let t=e.pendingResizeRequest;return kx(e),t}var jx=512;function Mx(e){if($y(e.terminal)){e.terminal.refresh?.(0,Math.max(0,(e.terminal.rows||1)-1));return}let{renderer:t,wasmTerm:n}=e.terminal;!t?.render||!n||(Nx(e),t.render(n,!0,e.terminal.viewportY||0,e.terminal))}function Nx(e){let t=e.terminal.renderer?.getCanvas?.()||e.hostEl.querySelector(`canvas`);if(!(t instanceof HTMLCanvasElement))return;let n=t.getContext(`2d`);n&&(n.save(),n.setTransform(1,0,0,1,0,0),n.fillStyle=Br.background,n.fillRect(0,0,t.width,t.height),n.restore())}function Px(e){return e===void 0?e:+(e>0)}function Fx(e){Mx(e),requestAnimationFrame(()=>{e.disposed||Mx(e)})}function Ix(e,t){let n=fx(e.terminal),r=Math.max(0,Math.min(n,t));typeof e.terminal.scrollToLine==`function`?e.terminal.scrollToLine(r):e.terminal.viewportY=r,Mx(e)}function Lx(e,t){let n=fx(e.terminal);Ix(e,n-Math.max(0,Math.min(n,t)))}function Rx(e,t={}){if(!e.disposed){if(fx(e.terminal)<=0){Mx(e),_x(e,!0,!1,t);return}typeof e.terminal.scrollToBottom==`function`?(e.terminal.scrollToBottom(),Mx(e)):Ix(e,0),_x(e,!0,!1,t)}}function zx(e,t,n,r){e.disposed||(Ix(e,bx(e.terminal,t,n)),_x(e,!1,r))}function Bx(e,t,n){zx(e,t,n,!0),vx(e)}function Vx(e,t,n,r,i){if(!e.disposed){if(r){Rx(e,{allowClearUnread:!e.preserveUnreadOutputUntilJump});return}zx(e,t,n,i)}}function Hx(e,t,n){e.terminalWriteBatchCount+=1,e.terminal.write(t,n)}function Ux(e){$y(e.terminal)||Mx(e)}function Wx(e,t,n){return e.terminalWriteQueue=e.terminalWriteQueue.catch(()=>{}).then(()=>new Promise(r=>{let i=!1,a=(t=!1)=>i?!1:(i=!0,e.terminalWriteResolvers.delete(a),t&&n?.(),r(),!0);e.terminalWriteResolvers.add(a),t(a)})),e.terminalWriteQueue}function Gx(e){let t=Array.from(e.terminalWriteResolvers);e.terminalWriteResolvers.clear(),t.forEach(e=>e(!0))}function Kx(e,t){e()&&t?.()}function qx(e,t,n,r={}){if(!t){n?.();return}Wx(e,i=>{if(e.disposed){Kx(i,n);return}let a=px(e.terminal),o=fx(e.terminal),s=e.followOutput,c=r.quiet===!0||t.length>=jx,l=r.isOutputObserved?.()??!0;c&&(e.suspendRendering=!0),Hx(e,t,()=>{if(e.disposed){Kx(i,n);return}e.suspendRendering=!1,s?l?c?Rx(e,{allowClearUnread:!e.preserveUnreadOutputUntilJump}):_x(e,!0,!1,{allowClearUnread:!e.preserveUnreadOutputUntilJump}):vx(e):l?(Bx(e,a,o),requestAnimationFrame(()=>{e.disposed||(Bx(e,a,o),Mx(e))})):vx(e),l&&Ux(e),Kx(i,n)})},n)}function Jx(e,t,n){Wx(e,r=>{if(e.disposed){Kx(r,n);return}let i=px(e.terminal),a=fx(e.terminal),o=e.followOutput;if(e.suspendRendering=!0,e.terminal.reset(),!t){e.suspendRendering=!1,Mx(e),Kx(r,n);return}Hx(e,t,()=>{if(e.disposed){Kx(r,n);return}e.suspendRendering=!1,o?Rx(e,{allowClearUnread:!e.preserveUnreadOutputUntilJump}):Bx(e,i,a),!o&&a===fx(e.terminal)&&Mx(e),Mx(e),Kx(r,n)})},n)}function Yx(e=queueMicrotask){let t=null,n=0,r=n=>{let r=n.revision,i=!1;return{release:()=>{i||(i=!0,!(t!==n||n.revision!==r)&&(n.releasePending=!0,e(()=>{t!==n||n.revision!==r||!n.releasePending||(t=null,n.releasePending=!1,n.teardown())})))}}};return{acquire(e,i,a){if(t?.agentId===e&&t.mountEl===i)return t.releasePending=!1,t.revision=++n,r(t);if(t){let e=t;t=null,e.releasePending=!1,e.teardown()}let o={agentId:e,mountEl:i,revision:++n,releasePending:!1,teardown:a()};return t=o,r(o)}}}function Xx(){let e=document.getElementById(`terminal-session-parking-lot`);return e||(e=document.createElement(`div`),e.id=`terminal-session-parking-lot`,e.setAttribute(`aria-hidden`,`true`),e.style.display=`none`,document.body.appendChild(e),e)}function Zx(e){return!e.disposed&&e.attachedMount!==null&&e.hostEl.parentElement===e.attachedMount}function Qx(e,t){return e.attachGeneration===t&&Zx(e)}function $x(e){return e.attachGeneration+=1,e.attachGeneration}function eS(e,t,n){return e.disposed?!1:(n?.(),e.hostEl.parentElement===t?Array.from(t.children).forEach(t=>{t!==e.hostEl&&t.remove()}):t.replaceChildren(e.hostEl),e.attachedMount=t,!0)}function tS(e,t){return!(e.disposed||t&&e.attachedMount!==t||t&&e.hostEl.parentElement!==t)}function nS(e){return e.disposed?!1:(e.attachedMount=null,e.attachGeneration+=1,Xx().appendChild(e.hostEl),!0)}function rS(e,t){let n=t.target;return n instanceof Node&&e.contains(n)}function iS(e,t,n){return!n&&rS(e,t)}function aS(e,t,n){return n&&rS(e,t)}function oS(e){return e.session&&typeof e.session==`object`?e.session.renderOutput??e.session.output??``:typeof e.session==`string`?e.session:typeof e.renderOutput==`string`?e.renderOutput:e.output??``}function sS(e){let t=e.session&&typeof e.session==`object`?e.session.outputSeq:e.outputSeq,n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function cS(e){let t=e.session&&typeof e.session==`object`?e.session.runtimeEpoch:e.runtimeEpoch;return typeof t==`string`?t:``}function lS(e){let t=e.session&&typeof e.session==`object`?e.session.stateRevision:e.stateRevision,n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function uS(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:null}function dS(e){let t=e.session&&typeof e.session==`object`?e.session:null;return{cols:uS(t?.previewCols??t?.cols??e.previewCols??e.cols),rows:uS(t?.previewRows??t?.rows??e.previewRows??e.rows)}}function fS(e){let t=oS(e),n=dS(e);return{runtimeEpoch:cS(e),output:t,outputSeq:sS(e),stateRevision:lS(e),cols:n.cols,rows:n.rows}}var pS=null;function mS(){let e=(document.documentElement.lang||navigator.language||``).toLowerCase().startsWith(`zh`);return{farming:e?`在 Farming 浏览器中打开`:`Open in Farming browser`,external:e?`在外部浏览器中打开`:`Open in external browser`,copy:e?`复制链接`:`Copy link`}}function hS(e,t){return{x:Math.max(8,Math.min(e,window.innerWidth-220-8)),y:Math.max(8,Math.min(t,window.innerHeight-110-8))}}function gS(e,t,n=!1){let r=document.createElement(`button`);return r.type=`button`,r.className=`terminal-context-menu-item`,r.setAttribute(`role`,`menuitem`),r.textContent=e,r.disabled=n,r.addEventListener(`click`,()=>{r.disabled||t()}),r}function _S(e){window.open(e,`_blank`,`noopener,noreferrer`)}function vS({event:e,url:t,onOpenInFarming:n}){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),pS?.();let r=mS(),i=hS(e.clientX,e.clientY),a=document.createElement(`div`);a.className=`terminal-context-menu terminal-context-menu-pooled`,a.dataset.testid=`code-url-context-menu`,a.setAttribute(`role`,`menu`),a.style.left=`${i.x}px`,a.style.top=`${i.y}px`;let o=()=>{document.removeEventListener(`mousedown`,c,!0),document.removeEventListener(`pointerdown`,c,!0),document.removeEventListener(`keydown`,l,!0),window.removeEventListener(`resize`,o),window.removeEventListener(`scroll`,o,!0),a.remove(),pS===o&&(pS=null)},s=e=>{o(),e()},c=e=>{e.target instanceof Node&&a.contains(e.target)||o()},l=e=>{e.key===`Escape`&&(e.preventDefault(),o())};n&&a.append(gS(r.farming,()=>s(n))),a.append(gS(r.external,()=>s(()=>_S(t))),gS(r.copy,()=>s(()=>{Se(t)}))),a.addEventListener(`mousedown`,e=>e.stopPropagation()),a.addEventListener(`pointerdown`,e=>e.stopPropagation()),document.body.appendChild(a),pS=o,document.addEventListener(`mousedown`,c,!0),document.addEventListener(`pointerdown`,c,!0),document.addEventListener(`keydown`,l,!0),window.addEventListener(`resize`,o),window.addEventListener(`scroll`,o,!0),requestAnimationFrame(()=>a.querySelector(`button:not(:disabled)`)?.focus())}var yS=5e3,bS=250,xS=1500,SS=50,CS=300,wS=FarmingTerminalReplay,TS=new Map,ES=0,DS=6,OS=520,kS=.025,AS=3.2,jS=.972,MS=90,NS=.28,PS=30,FS=240,IS=3e4;function LS(e,t){eS(e,t,()=>XS(e.hostEl,t)),JS(e)}function RS(e){for(let t of TS.values())if(!(t instanceof Promise)&&t.hostEl===e)return t;return null}function zS(e){e.reconnectSnapshotSeq+=1,e.replayInProgress=!1,SC(e),e.bootstrapRequestControllers.forEach(e=>e.abort()),e.bootstrapRequestControllers.clear(),e.checkpointRequestInFlight=!1}function BS(e){e.resizeDeliveryTimeout!==null&&(window.clearTimeout(e.resizeDeliveryTimeout),e.resizeDeliveryTimeout=null)}function VS(e){e.fitResizeTimer!==null&&(window.clearTimeout(e.fitResizeTimer),e.fitResizeTimer=null),e.pendingFitResize=null}function HS(e){e.resizeRedrawTimer!==null&&(window.clearTimeout(e.resizeRedrawTimer),e.resizeRedrawTimer=null),e.resizeRedrawStartedAt=null}function US(e,t=!1){let n=Date.now();(t||e.resizeRedrawStartedAt===null)&&(e.resizeRedrawStartedAt=n),e.resizeRedrawTimer!==null&&window.clearTimeout(e.resizeRedrawTimer);let r=e.resizeRedrawStartedAt+CS,i=Math.max(0,Math.min(SS,r-n));e.resizeRedrawTimer=window.setTimeout(()=>{e.resizeRedrawTimer=null,e.resizeRedrawStartedAt=null,e.disposed||IC(e)},i)}function WS(e,t){e.fitResizeTimer!==null&&window.clearTimeout(e.fitResizeTimer),e.pendingFitResize=t,e.fitResizeTimer=window.setTimeout(()=>{e.fitResizeTimer=null;let t=e.pendingFitResize;e.pendingFitResize=null,!(!t||e.disposed)&&ew(e,t.cols,t.rows)},bS)}function GS(e){VS(e),HS(e),BS(e),kx(e)}function KS(e){BS(e),e.resizeDeliveryTimeout=window.setTimeout(()=>{e.resizeDeliveryTimeout=null;let t=Ax(e);!t||e.disposed||$C(e,t.cols,t.rows)},xS)}function qS(e){e.disposed||(e.parkedViewportState={viewportY:px(e.terminal),scrollbackLength:fx(e.terminal),following:e.followOutput,hasUnreadOutput:e.hasUnreadOutput,preserveUnreadOutputUntilJump:e.preserveUnreadOutputUntilJump,readingAnchor:Ew(e)},zS(e),GS(e),e.followOutputHandler=null,e.recoveryStatusHandler=null,e.pathOpenHandler=null,e.pathResolveHandler=null,e.searchOpenHandler=null,YS(e),rT(e),nS(e))}function JS(e){e.disposed||!e.resizeObserver||e.resizeObserver.observe(e.hostEl)}function YS(e){e.resizeObserver?.disconnect()}function XS(e,t){let n=t.closest(`.code-terminal-grid.panes-1`);n&&n.querySelectorAll(`.terminal-session-host`).forEach(t=>{if(t===e||!(t instanceof HTMLDivElement))return;let n=RS(t);n?qS(n):Xx().appendChild(t)})}function ZS(e){let t=e.dataset.terminalFontSize,n=t?Number(t):NaN;return Number.isFinite(n)&&n>0?n:12}function QS(e,t,n={}){let r=t!==`ready`&&t!==`failed`,i={phase:t,attempt:r?Math.max(1,n.attempt??e.recoveryStatus.attempt):0,startedAt:r?n.restart||e.recoveryStatus.startedAt===null?Date.now():e.recoveryStatus.startedAt:null,retryDelayMs:t===`retrying`?n.retryDelayMs??null:null},a=e.recoveryStatus;a.phase===i.phase&&a.attempt===i.attempt&&a.startedAt===i.startedAt&&a.retryDelayMs===i.retryDelayMs||(e.recoveryStatus=i,e.recoveryStatusHandler?.(i))}async function $S(e,t){let n=await fetch(r(`/api/agents/${e}/session-view`),{signal:t});if(!n.ok)throw Error(`Terminal session view failed: ${n.status}`);return fS(await n.json())}async function eC(e){let t=new AbortController;e.bootstrapRequestControllers.add(t);let n=window.setTimeout(()=>t.abort(new DOMException(`Terminal checkpoint request timed out`,`TimeoutError`)),yS);try{return await $S(e.agentId,t.signal)}finally{window.clearTimeout(n),e.bootstrapRequestControllers.delete(t)}}function tC(e,t){if($y(t))return t.focus(),!0;let n=e.querySelector(`textarea`);return n instanceof HTMLTextAreaElement?(gC(e,t),n.focus(),!0):(t.focus(),!1)}function nC(e){return e.disposed||e.attachedMount===null?!1:(ES+=1,tC(e.hostEl,e.terminal))}function rC(e,t,n){if(e.disposed||e.attachedMount===null||ES!==n)return!1;let r=document.activeElement;return r===document.body||t.contains(r)||e.hostEl.contains(r)}function iC(e){let t=document.activeElement;return document.querySelector(`.code-composer.menu-open, .code-composer-menu`)?!1:!(t instanceof Element)||t===document.body||e.contains(t)?!0:!t.closest([`.code-composer`,`.code-composer-menu`,`.code-context-menu`,`.input-dialog-overlay`,`.code-overlay-dialog`,`.code-file-editor`,`.code-files-section`,`input`,`textarea`,`select`,`[contenteditable="true"]`,`[role="dialog"]`,`[role="menu"]`].join(`,`))}function aC(e){return e instanceof Element?!!e.closest([`.code-composer`,`.code-terminal-search`,`.code-file-editor`,`.monaco-editor`,`input`,`textarea`,`select`,`[contenteditable="true"]`,`[role="dialog"]`,`[role="menu"]`].join(`,`)):!1}function oC(e,t){if(e.disposed||e.attachedMount===null)return!1;let n=t.target;if(n instanceof Node&&e.hostEl.contains(n))return!0;if(aC(n))return!1;let r=window.getSelection?.();if(!r||r.isCollapsed)return!0;let i=r.anchorNode,a=r.focusNode;return!!(i&&e.hostEl.contains(i)||a&&e.hostEl.contains(a))}function sC(e){return e.key.toLowerCase()!==`c`||e.altKey||e.shiftKey?!1:e.metaKey&&!e.ctrlKey?!0:!navigator.platform.toLowerCase().includes(`mac`)&&e.ctrlKey&&!e.metaKey}function cC(e,t){if(!sC(t)||e.disposed||e.attachedMount===null)return!1;let n=t.target;if(n instanceof Node&&e.hostEl.contains(n))return!0;if(aC(n))return!1;let r=window.getSelection?.();if(!r||r.isCollapsed)return!0;let i=r.anchorNode,a=r.focusNode;return!!(i&&e.hostEl.contains(i)||a&&e.hostEl.contains(a))}function lC(e){return e.key.toLowerCase()!==`k`||e.altKey||e.shiftKey||e.ctrlKey?!1:navigator.platform.toLowerCase().includes(`mac`)&&e.metaKey}function uC(e,t){if(!lC(t)||e.disposed||e.attachedMount===null)return!1;let n=t.target;return n instanceof Node&&e.hostEl.contains(n)}function dC(e,t){return uC(e,t)?(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),$w(e),!0):!1}function fC(e){return Zx(e)}function pC(e){return fC(e)}function mC(e,t){if(t.type!==`keydown`||![`PageUp`,`PageDown`].includes(t.key)||e.disposed||e.attachedMount===null)return!1;let n=t.target;return n instanceof Node&&e.hostEl.contains(n)}function hC(e,t){if(!mC(e,t))return!1;t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let n=yx(e.terminal,t.key===`PageUp`?`PageUp`:`PageDown`,10);return Ix(e,n),_x(e,n<=0,n<=0?!1:e.hasUnreadOutput,{allowClearUnread:n<=0}),gx(e),!0}function gC(e,t){let n=e.querySelector(`textarea`),r=t.renderer?.getMetrics?.(),i=t.wasmTerm?.getCursor?.();if(!(n instanceof HTMLTextAreaElement)||!r||!i)return;let a=ZS(e),o=Math.max(0,i.x*r.width),s=Math.max(0,i.y*r.height),c=Math.max(a+2,r.height),l=Math.max(r.width*8,120);n.classList.add(`terminal-ime-input`),n.style.position=`absolute`,n.style.left=`${o}px`,n.style.top=`${s}px`,n.style.width=`${l}px`,n.style.height=`${c}px`,n.style.lineHeight=`${c}px`,n.style.fontSize=`${a}px`,n.style.fontFamily=Vr,n.style.padding=`0`,n.style.margin=`0`,n.style.border=`0`,n.style.outline=`0`,n.style.background=`transparent`,n.style.clipPath=`none`,n.style.overflow=`hidden`,n.style.whiteSpace=`pre`,n.style.resize=`none`}function _C(e,t){return Qx(e,t)}function vC(e,t=e.attachGeneration){if(!(e.fixtureOverrideActive||e.disposed||!e.pendingSnapshotReplay||!_C(e,t))){if(e.pendingSnapshotReplay=!1,!e.snapshotRuntimeEpoch||e.snapshotOutputSeq===null||e.snapshotStateRevision===null||e.snapshotCols===null||e.snapshotRows===null){AC(e,t);return}kC(e,{runtimeEpoch:e.snapshotRuntimeEpoch,output:e.snapshotOutput,outputSeq:e.snapshotOutputSeq,stateRevision:e.snapshotStateRevision,cols:e.snapshotCols,rows:e.snapshotRows},t)}}function yC(e,t){if(!t||e.fixtureOverrideActive)return!1;let n=bC(t);return wS.evaluateCheckpoint(e.replayState,n).action!==`install`||t.runtimeEpoch===e.snapshotRuntimeEpoch&&e.snapshotStateRevision!==null&&t.stateRevision<=e.snapshotStateRevision?!1:(e.snapshotOutput=t.output,e.snapshotRuntimeEpoch=t.runtimeEpoch,e.snapshotOutputSeq=t.outputSeq,e.snapshotStateRevision=t.stateRevision,e.snapshotCols=t.cols,e.snapshotRows=t.rows,e.pendingSnapshotReplay=!0,e.bootstrappingSnapshot=!0,e.needsReconnectOutputSync=!0,!0)}function bC(e){return{runtimeEpoch:e.runtimeEpoch,outputSeq:e.outputSeq,stateRevision:e.stateRevision,cols:e.cols,rows:e.rows}}function xC(e,t){wS.queueTransition(e.replayState,t).queued||(e.needsReconnectOutputSync=!0,e.bootstrappingSnapshot=!0,AC(e,e.attachGeneration))}function SC(e){e.checkpointRetryTimer!==null&&(window.clearTimeout(e.checkpointRetryTimer),e.checkpointRetryTimer=null)}function CC(e,t,n=e.attachGeneration){e.disposed||e.replayState.halted||e.checkpointRetryTimer!==null||(e.checkpointRetryTimer=window.setTimeout(()=>{e.checkpointRetryTimer=null,!(e.disposed||!_C(e,n))&&AC(e,n)},t))}function wC(e,t,n){if(e.checkpointRequestInFlight=!1,e.needsReconnectOutputSync=!0,e.bootstrappingSnapshot=!0,t.halted){TC(e,t.message);return}QS(e,`retrying`,{attempt:e.replayState.failureCount+1,retryDelayMs:t.delay}),CC(e,t.delay,n)}function TC(e,t){SC(e),e.checkpointRequestInFlight=!1,e.replayInProgress=!1,e.bootstrappingSnapshot=!1,e.pendingSnapshotReplay=!1,wS.clearQueuedTransitions(e.replayState),e.hostEl.classList.add(`terminal-checkpoint-installing`),QS(e,`failed`),XC(e,t)}function EC(e,t){if(e.disposed||!_C(e,t)||e.replayInProgress||e.checkpointRequestInFlight||e.pendingSnapshotReplay||e.liveWriteInProgress||e.replayState.queuedTransitions.length>0&&(IC(e),e.replayState.queuedTransitions.length>0||e.liveWriteInProgress||e.checkpointRequestInFlight))return;if(e.needsReconnectOutputSync||wS.isReplayTargetPending(e.replayState)){AC(e,t);return}e.bootstrappingSnapshot=!1,GS(e);let n=e.resizeAfterReplayRequired||e.lastNotifiedResize===null;e.resizeAfterReplayRequired=!1,requestAnimationFrame(()=>{!_C(e,t)||e.disposed||(e.hostEl.classList.remove(`terminal-checkpoint-installing`),QC(e,{force:n}),dT(e,t))})}function DC(e){if(e.parkedViewportState)return{...e.parkedViewportState,hasUnreadOutput:e.parkedViewportState.hasUnreadOutput||e.hasUnreadOutput,preserveUnreadOutputUntilJump:e.parkedViewportState.preserveUnreadOutputUntilJump||e.preserveUnreadOutputUntilJump};let t=L(I(e.agentId,`terminal`)),n=t?.surface===`terminal`?t:Ew(e);return{viewportY:px(e.terminal),scrollbackLength:fx(e.terminal),following:n?!1:e.followOutput,hasUnreadOutput:e.hasUnreadOutput,preserveUnreadOutputUntilJump:e.preserveUnreadOutputUntilJump,readingAnchor:n}}function OC(e,t){if(e.followOutput=t.following,e.hasUnreadOutput=t.hasUnreadOutput,e.preserveUnreadOutputUntilJump=t.preserveUnreadOutputUntilJump,t.following){Vx(e,t.viewportY,t.scrollbackLength,!0,t.hasUnreadOutput);return}t.readingAnchor&&Dw(e,t.readingAnchor)||(ee(I(e.agentId,`terminal`)),Rx(e,{allowClearUnread:!0}))}function kC(e,t,n){if(e.disposed||!_C(e,n))return!1;QS(e,`installing`,{attempt:e.replayState.failureCount+1}),e.checkpointRequestInFlight=!1;let r=bC(t),i=wS.evaluateCheckpoint(e.replayState,r);if(i.action===`reject`)return wC(e,wS.recordInvariantFailure(e.replayState,i.signature||`invalid-checkpoint`,i.message||`Terminal replay returned an invalid screen state`),n),!1;if(i.action===`current`&&e.terminal.cols===t.cols&&e.terminal.rows===t.rows){let t=DC(e);return wS.commitCheckpoint(e.replayState,r),e.needsReconnectOutputSync=!1,e.bootstrappingSnapshot=!1,OC(e,t),IC(e),EC(e,n),!0}let a=e.reconnectSnapshotSeq+1;e.reconnectSnapshotSeq=a;let o=DC(e);if(e.replayInProgress=!0,e.bootstrappingSnapshot=!0,e.hostEl.classList.add(`terminal-checkpoint-installing`),e.terminal.cols!==t.cols||e.terminal.rows!==t.rows){e.applyingLocalResize=!0;try{e.terminal.resize?.(t.cols,t.rows)}finally{e.applyingLocalResize=!1}}return Jx(e,t.output,()=>{let t=()=>{e.disposed||!_C(e,n)||e.reconnectSnapshotSeq!==a||(wS.commitCheckpoint(e.replayState,r),e.followOutput=o.following,e.hasUnreadOutput=o.hasUnreadOutput,e.preserveUnreadOutputUntilJump=o.preserveUnreadOutputUntilJump,OC(e,o),e.replayInProgress=!1,e.needsReconnectOutputSync=!1,e.bootstrappingSnapshot=!1,HC(e),IC(e),EC(e,n))};if(e.holdCheckpointInstallCompletionForTest){e.heldCheckpointInstallCompletionForTest=t;return}t()}),!0}function AC(e,t=e.attachGeneration){if(e.disposed||e.fixtureOverrideActive||e.pageOutputSuspended||e.checkpointRequestInFlight||e.checkpointRetryTimer!==null||e.replayInProgress||e.replayState.halted||!_C(e,t))return;QS(e,`requesting`,{attempt:e.replayState.failureCount+1}),wS.beginRecovery(e.replayState);let n=e.reconnectSnapshotSeq+1;e.reconnectSnapshotSeq=n,e.checkpointRequestInFlight=!0,e.bootstrappingSnapshot=!0,e.needsReconnectOutputSync=!0,eC(e).then(r=>{e.disposed||e.reconnectSnapshotSeq!==n||e.pageOutputSuspended||!_C(e,t)||(e.checkpointRequestInFlight=!1,kC(e,r,t))}).catch(r=>{e.disposed||e.reconnectSnapshotSeq!==n||(wC(e,wS.recordTransportFailure(e.replayState),t),r instanceof Error&&r.name!==`AbortError`&&console.warn(`Terminal replay request failed; retrying:`,r))})}function jC(e,t,n,r,i=``,a,o,s,c=`output`){if(n){if(e.fixtureOverrideActive||e.pageOutputSuspended)return;zS(e),kC(e,{runtimeEpoch:i,output:t,outputSeq:Number.isFinite(r)?r:null,stateRevision:Number.isFinite(a)?a:null,cols:Number.isFinite(o)?o:null,rows:Number.isFinite(s)?s:null},e.attachGeneration);return}let l={kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s},u=wS.classifyTransition(e.replayState,l);if(u.action===`drop`)return;if(u.action===`recover`){xC(e,l),e.needsReconnectOutputSync=!0,e.bootstrappingSnapshot=!0,AC(e);return}if(c===`resize`){let t=Math.floor(o),n=Math.floor(s),r=Ox(e,t,n);if(r.matched&&BS(e),!r.preserveLocalGeometry&&(e.terminal.cols!==t||e.terminal.rows!==n)){e.applyingLocalResize=!0;try{e.terminal.resize?.(t,n)}finally{e.applyingLocalResize=!1}}wS.commitTransition(e.replayState,l),US(e,!0),r.next&&$C(e,r.next.cols,r.next.rows),HC(e),IC(e),dT(e,e.attachGeneration);return}let d=c===`clear`?`\x1B[2J\x1B[3J\x1B[H`:t;if(!d){wS.commitTransition(e.replayState,l),IC(e);return}e.liveWriteInProgress=!0,qx(e,d,()=>{e.disposed||(wS.commitTransition(e.replayState,l),c===`clear`&&e.terminal.clearTerminalSelection?.(),e.liveWriteInProgress=!1,e.followOutput&&!e.hasUnreadOutput&&gx(e),HC(e),IC(e),e.hostEl.classList.contains(`terminal-checkpoint-installing`)?EC(e,e.attachGeneration):dT(e,e.attachGeneration))},{isOutputObserved:()=>fC(e)})}function MC(e,t,n,r,i=``,a,o,s,c=`output`){if(e.disposed||Date.now()<e.suppressOutputUntil)return;if(e.pageOutputSuspended||document.visibilityState===`hidden`){wS.clearQueuedTransitions(e.replayState),wS.beginRecovery(e.replayState,{kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s}),e.needsReconnectOutputSync=!0;return}let l=e.needsReconnectOutputSync||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.replayInProgress||e.checkpointRequestInFlight||e.replayState.recovering;if(e.liveWriteInProgress&&!l){xC(e,{kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s});return}if(l){if(n){jC(e,t,!0,r,i,a,o,s,c);return}xC(e,{kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s}),e.bootstrappingSnapshot=!0,AC(e);return}if(n){jC(e,t,!0,r,i,a,o,s,c);return}xC(e,{kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s}),NC(e)}function NC(e){if(e.resizeRedrawTimer!==null){US(e);return}e.liveTransitionFlushScheduled||(e.liveTransitionFlushScheduled=!0,queueMicrotask(()=>{e.liveTransitionFlushScheduled=!1,e.disposed||IC(e)}))}function PC(e){let t=[],n=wS.createState();n.runtimeEpoch=e.replayState.runtimeEpoch,n.outputSeq=e.replayState.outputSeq,n.stateRevision=e.replayState.stateRevision,n.retiredRuntimeEpochs=new Set(e.replayState.retiredRuntimeEpochs);for(let r of e.replayState.queuedTransitions){if(r.kind===`resize`)break;if(wS.classifyTransition(n,r).action!==`apply`)return null;wS.commitTransition(n,r),t.push(r)}return t.length>0?t:null}function FC(e,t){for(let n=0;n<t.length;n+=1)wS.takeQueuedTransition(e.replayState);let n=t.map(e=>e.kind===`clear`?`\x1B[2J\x1B[3J\x1B[H`:e.data).join(``);e.liveWriteInProgress=!0,qx(e,n,()=>{e.disposed||(t.forEach(t=>wS.commitTransition(e.replayState,t)),t.some(e=>e.kind===`clear`)&&e.terminal.clearTerminalSelection?.(),e.liveWriteInProgress=!1,e.followOutput&&!e.hasUnreadOutput&&gx(e),HC(e),IC(e),dT(e,e.attachGeneration))},{isOutputObserved:()=>fC(e)})}function IC(e){if(!(e.disposed||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.replayInProgress||e.checkpointRequestInFlight||e.liveWriteInProgress||e.resizeRedrawTimer!==null))for(;!e.bootstrappingSnapshot&&!e.replayInProgress&&!e.checkpointRequestInFlight&&!e.liveWriteInProgress&&e.resizeRedrawTimer===null;){let t=PC(e);if(t){FC(e,t);continue}let n=wS.takeQueuedTransition(e.replayState);if(!n)break;jC(e,n.data||``,!1,n.outputSeq,n.runtimeEpoch,n.stateRevision,n.cols,n.rows,n.kind)}}function LC(e){return e.terminal.getCellMetrics?.()??e.terminal.renderer?.getMetrics?.()}function RC(e){let t=e.terminal.getScreenElement?.();if(t instanceof HTMLElement)return t.getBoundingClientRect();let n=e.terminal.renderer?.getCanvas?.()||e.hostEl.querySelector(`canvas`);return n instanceof HTMLCanvasElement?n.getBoundingClientRect():null}function zC(e,t={}){let n=hx(e);_x(e,n,n?!1:e.hasUnreadOutput,{allowClearUnread:n&&t.allowClearUnread===!0})}function BC(e){wS.clearQueuedTransitions(e.replayState),e.bootstrappingSnapshot=!1,e.pendingSnapshotReplay=!1}function VC(e,t={}){e.followCheckFrame!==null&&cancelAnimationFrame(e.followCheckFrame),e.followCheckFrame=requestAnimationFrame(()=>{if(e.followCheckFrame=null,e.disposed||!fC(e))return;let n=hx(e);_x(e,n,n?!1:e.hasUnreadOutput,{allowClearUnread:n&&t.allowClearUnread===!0})})}function HC(e){e.imeComposing&&requestAnimationFrame(()=>{!e.disposed&&e.imeComposing&&gC(e.hostEl,e.terminal)})}function UC(e){return $y(e.terminal)?!1:e.imeComposing||e.suppressRendererCursor}function WC(e,t=!0){let n=e.terminal.renderer;if(!e.disposed){if(e.hostEl.classList.toggle(`terminal-renderer-cursor-suppressed`,UC(e)),!n){t&&Mx(e);return}UC(e)?n.cursorVisible=!1:!e.imeComposing&&e.rendererCursorWasVisible!==void 0&&(n.cursorVisible=e.rendererCursorWasVisible,e.rendererCursorWasVisible=void 0),t&&Mx(e)}}function GC(e,t){if(e.suppressRendererCursor===t){e.hostEl.classList.toggle(`terminal-renderer-cursor-suppressed`,UC(e));return}e.suppressRendererCursor=t,WC(e)}function KC(e,t){let n=e.terminal.renderer;if(!(e.disposed||!n)){if(t){e.imeComposing||(e.rendererCursorWasVisible=n.cursorVisible===void 0?void 0:!!n.cursorVisible),e.imeComposing=!0,WC(e);return}if(e.imeComposing){if(e.imeComposing=!1,e.suppressRendererCursor){n.cursorVisible=!1,Mx(e);return}n.cursorVisible=e.rendererCursorWasVisible??!0,e.rendererCursorWasVisible=void 0,Mx(e)}}}function qC(e){let t=e.terminal.renderer;if(!t?.render||e.originalRender)return;let n=t.render.bind(t);e.originalRender=n,t.render=(r,i,a,o,s)=>{let c=Px(s);if(!e.suspendRendering){if(!UC(e)){n(r,i,a,o,c);return}t.cursorVisible=!1,n(r,!0,a,o,c),t.cursorVisible=!1}}}function JC(e){if($y(e.terminal))return;let t=e.hostEl.querySelector(`textarea`);if(!(t instanceof HTMLTextAreaElement))return;let n=()=>{e.disposed||gC(e.hostEl,e.terminal)},r=()=>requestAnimationFrame(n),i=()=>{e.imeComposing&&r()},a=()=>{n(),e.hostEl.classList.add(`terminal-ime-active`),t.classList.add(`terminal-ime-composing`),KC(e,!0)},o=()=>{KC(e,!1),requestAnimationFrame(()=>{e.hostEl.classList.remove(`terminal-ime-active`),t.classList.remove(`terminal-ime-composing`),t.value=``,n()})},s=()=>{KC(e,!1),e.hostEl.classList.remove(`terminal-ime-active`),t.classList.remove(`terminal-ime-composing`)},c=e=>{(e.isComposing||e.keyCode===229)&&a()};t.addEventListener(`focus`,n),e.hostEl.addEventListener(`keydown`,c,!0),e.hostEl.addEventListener(`compositionstart`,a,!0),e.hostEl.addEventListener(`compositionupdate`,n,!0),e.hostEl.addEventListener(`compositionend`,o,!0),t.addEventListener(`input`,i),t.addEventListener(`blur`,s),e.imeKeydownHandler=c;let l=e.terminal.onCursorMove?.(i),u=e.terminal.onKey?.(i);e.imeOverlayDisposables.push(()=>t.removeEventListener(`focus`,n),()=>e.hostEl.removeEventListener(`keydown`,c,!0),()=>e.hostEl.removeEventListener(`compositionstart`,a,!0),()=>e.hostEl.removeEventListener(`compositionupdate`,n,!0),()=>e.hostEl.removeEventListener(`compositionend`,o,!0),()=>t.removeEventListener(`input`,i),()=>t.removeEventListener(`blur`,s),s),l&&e.imeOverlayDisposables.push(()=>l.dispose()),u&&e.imeOverlayDisposables.push(()=>u.dispose()),n()}function YC(e,t,n=12){if(_C(e,t)&&iC(e.hostEl)){if(e.replayInProgress||e.bootstrappingSnapshot||e.pendingSnapshotReplay){if(n<=0)return;requestAnimationFrame(()=>{YC(e,t,n-1)});return}nC(e)||n<=0||requestAnimationFrame(()=>{YC(e,t,n-1)})}}function XC(e,t){e.errorHandler?.(Error(t))}function ZC(e,t){return e.disposed||e.attachedMount===null||e.inputDisabled||!Ht({type:`input`,agentId:e.agentId,...Array.isArray(t)?{inputParts:t}:{input:t}})?!1:(e.fixtureOverrideActive=!1,e.inputCount+=1,e.contextMenuSelection=``,e.lastNonEmptySelection=``,!0)}function QC(e,t={}){try{let n=Sx(e.hostEl,e.fitAddon);if(!n)return;let r={cols:e.terminal.cols||n.cols,rows:e.terminal.rows||n.rows};if(r.cols===n.cols&&r.rows===n.rows){VS(e);return}if(!t.force&&e.lastNotifiedResize?.cols===n.cols&&e.lastNotifiedResize.rows===n.rows){VS(e);return}if(e.replayInProgress||e.bootstrappingSnapshot){e.resizeAfterReplayRequired=!0,VS(e);return}if(Tx(r,n,t)){WS(e,n);return}VS(e),ew(e,n.cols,n.rows,t)}catch{}}function $C(e,t,n){if(!fC(e)||e.replayInProgress||e.bootstrappingSnapshot||e.pageOutputSuspended)return!1;let r=e.resizeRequestInFlight!==null,i=Dx(e,t,n,(t,n)=>Ht({type:`resize-agent`,agentId:e.agentId,cols:t,rows:n}));return i&&!r&&e.resizeRequestInFlight&&KS(e),i}function ew(e,t,n,r={}){!fC(e)||e.replayInProgress||e.bootstrappingSnapshot||Cx(e,t,n,(t,n)=>{if(typeof e.terminal.resize!=`function`)return!1;if(e.terminal.cols!==t||e.terminal.rows!==n){e.applyingLocalResize=!0;try{e.terminal.resize(t,n)}finally{e.applyingLocalResize=!1}}return $C(e,t,n)},r)}function tw(e){(e.resizeRequestInFlight||e.pendingResizeRequest)&&(e.resizeAfterReplayRequired=!0),GS(e),wS.resetRecovery(e.replayState),wS.beginRecovery(e.replayState),e.needsReconnectOutputSync=!0,!(e.disposed||e.pageOutputSuspended)&&(!e.attachedMount||e.hostEl.parentElement!==e.attachedMount||(zS(e),AC(e,e.attachGeneration)))}function nw(e){wx(e),e.resizeAfterReplayRequired=!0,GS(e),wS.resetRecovery(e.replayState),wS.beginRecovery(e.replayState),e.needsReconnectOutputSync=!0,!(e.disposed||e.pageOutputSuspended)&&(!e.attachedMount||e.hostEl.parentElement!==e.attachedMount||(zS(e),AC(e,e.attachGeneration)))}function rw(e,t){return Math.max(0,(typeof e?.length==`number`?e.length:t)-1)}function iw(e,t,n){return rx(e.getLine(t)?.getCell?.(n))}function aw(e,t,n,r){if(n>0)return{row:t,col:n-1};let i=e.getLine(t);if(t<=0||!i?.isWrapped)return null;let a=e.getLine(t-1);return{row:t-1,col:rw(a,r)}}function ow(e,t,n,r){if(n<rw(e.getLine(t),r))return{row:t,col:n+1};let i=t+1;return e.getLine(i)?.isWrapped?{row:i,col:0}:null}function sw(e,t,n){let r=e.terminal.buffer?.active,i=e.terminal.cols||80;if(!r||typeof r.getLine!=`function`||typeof e.terminal.select!=`function`)return``;let a=mx(e.terminal)+n;if(!ux(iw(r,a,t)))return``;let o={row:a,col:t};for(;;){let e=aw(r,o.row,o.col,i);if(!e||!ux(iw(r,e.row,e.col)))break;o=e}if(/^[#$%>]$/u.test(iw(r,o.row,o.col))){let e=ow(r,o.row,o.col,i);e&&(o=e)}let s={row:a,col:t};for(;;){let e=ow(r,s.row,s.col,i);if(!e||!ux(iw(r,e.row,e.col)))break;s=e}return e.terminal.select(o.col,o.row,dx(o,s,i)),e.cachedSelection=cx(e.terminal),e.cachedSelection}function cw(e,t,n){let r=e.terminal.buffer?.active,i=e.terminal.cols||80;if(!r||typeof e.terminal.select!=`function`)return``;let a=mx(e.terminal),o={row:a+t.row,col:t.col},s={row:a+n.row,col:n.col},c=o.row<s.row||o.row===s.row&&o.col<=s.col?{start:o,end:s}:{start:s,end:o};return e.terminal.select(c.start.col,c.start.row,dx(c.start,c.end,i)),e.cachedSelection=cx(e.terminal),e.cachedSelection}function lw(e){let t=e.terminal.buffer?.active,n=e.terminal.cols||80;if(!t||typeof t.getLine!=`function`||typeof e.terminal.select!=`function`)return``;let r=typeof t.length==`number`?t.length:mx(e.terminal)+(e.terminal.rows||1),i=Math.max(0,r-1),a=rw(t.getLine(i),n);return e.terminal.select(0,0,dx({row:0,col:0},{row:i,col:a},n)),e.cachedSelection=cx(e.terminal),e.cachedSelection}function uw(e,t){let n=LC(e),r=RC(e);return!n||!r||t.clientX<r.left||t.clientX>r.right||t.clientY<r.top||t.clientY>r.bottom?null:{col:Math.max(0,Math.min(Math.floor((t.clientX-r.left)/n.width),(e.terminal.cols||1)-1)),row:Math.max(0,Math.min(Math.floor((t.clientY-r.top)/n.height),(e.terminal.rows||1)-1))}}function dw(e,t,n,r=!0){let i=e.getLine(t);if(!i||typeof i.getCell!=`function`)return``;let a=Math.max(0,typeof i.length==`number`?i.length:n),o=``;for(let e=0;e<a;e+=1)o+=rx(i.getCell(e))||` `;return r?o.trimEnd():o}function fw(e){return e.button===0&&(e.ctrlKey||e.metaKey)}function pw(e){return navigator.platform.toLowerCase().includes(`mac`)?e.metaKey:e.ctrlKey}function mw(e,t){return pw(t)||e.openModifierActive}function hw(e,t){if(!e.decorations){e.decorations=t;return}e.decorations.pointerCursor=t.pointerCursor,e.decorations.underline=t.underline}function gw(e){return[e.path,e.lineNumber??``,e.column??``,e.endLineNumber??``,e.endColumn??``].join(`\0`)}async function _w(e,t){if(!e.pathResolveHandler||t.globalRoot)return t;let n=gw(t),r=e.pathResolveCache.get(n);if(r&&Date.now()-r.resolvedAt<=IS)return r.promise?await r.promise:r.target;let i=Promise.resolve(e.pathResolveHandler(e.agentId,t)).catch(()=>null);e.pathResolveCache.set(n,{resolvedAt:Date.now(),target:null,promise:i});let a=await i;return e.pathResolveCache.set(n,{resolvedAt:Date.now(),target:a}),a}async function vw(e,t){return e.pathResolveHandler?(await Promise.all(t.map(async t=>{if(t.kind!==`path`||!t.pathTarget)return t;let n=await _w(e,t.pathTarget);return n?{...t,pathTarget:n}:null}))).filter(e=>!!e):t}function yw(e,t){if(!e.pathResolveHandler||t.kind!==`path`||!t.pathTarget)return t;let n=e.pathResolveCache.get(gw(t.pathTarget));return!n||n.promise||Date.now()-n.resolvedAt>IS?null:n.target?{...t,pathTarget:n.target}:null}function bw(e){if(!$y(e.terminal)||typeof e.terminal.registerLinkProvider!=`function`)return;let t=e.terminal.registerLinkProvider({provideLinks:(t,n)=>{if(e.disposed){n(void 0);return}let r=e.attachGeneration,i=Sw(e,t-1);if(!i?.text){n(void 0);return}let a=ex(i.text,!!e.pathOpenHandler,!!e.searchOpenHandler);if(e.pathOpenHandler){let t=Cw(e,i.startRow);for(let e of Gb(i.text,t))if(!a.some(t=>t.kind!==`search`&&e.startIndex<t.startIndex+t.length&&t.startIndex<e.startIndex+e.length)){for(let t=a.length-1;t>=0;--t){let n=a[t];n?.kind===`search`&&e.startIndex<n.startIndex+n.length&&n.startIndex<e.startIndex+e.length&&a.splice(t,1)}a.push(e)}a.sort((e,t)=>e.startIndex-t.startIndex)}if(a.length===0){n(void 0);return}(async()=>{let t=await vw(e,a);if(!_C(e,r)){n(void 0);return}if(t.length===0){n(void 0);return}n(t.map(t=>{let n=t.kind===`path`&&!!(t.pathTarget&&e.pathOpenHandler),a={range:tx(t,i),text:t.text,decorations:{pointerCursor:n,underline:n||t.kind===`url`},activate:i=>{if(i.button!==0||Date.now()<e.suppressClickUntil||!_C(e,r))return;let a=mw(e,i);t.kind===`url`&&Pw(e,i)!==t.text||t.kind===`path`&&jw(e,i)?.text!==t.text||t.kind===`search`&&Fw(e,i)!==t.text||t.kind===`url`&&!a||t.kind===`search`&&!a||t.kind===`path`&&!n||(i.preventDefault(),i.stopPropagation(),i.stopImmediatePropagation(),t.kind===`url`?Bw(e,t.text):t.kind===`search`?e.searchOpenHandler?.(e.agentId,t.text):t.pathTarget&&e.pathOpenHandler&&e.pathOpenHandler(e.agentId,t.pathTarget),e.suppressClickUntil=Date.now()+250)},hover:r=>{if(!pC(e)||ae())return;e.linkProviderHoverTarget={kind:t.kind,text:t.text,...t.pathTarget?{pathTarget:t.pathTarget}:{}},e.lastLinkHoverEvent=r;let i=n||mw(e,r);hw(a,{pointerCursor:i,underline:n||t.kind===`url`||i}),Kw(e,i)},leave:()=>{e.linkProviderHoverTarget?.text===t.text&&(e.linkProviderHoverTarget=null),hw(a,{pointerCursor:n,underline:n||t.kind===`url`}),Uw(e)},dispose:()=>{e.linkProviderHoverTarget?.text===t.text&&(e.linkProviderHoverTarget=null)}};return a}))})()}});e.linkProviderDisposable=()=>t.dispose()}function xw(e,t){let n=e.terminal.buffer?.active;if(!t||!n||typeof n.getLine!=`function`)return null;let r=mx(e.terminal)+t.row,i=e.terminal.cols||80,a=r;for(;a>0&&n.getLine(a)?.isWrapped;)--a;let o=r;for(;n.getLine(o+1)?.isWrapped;)o+=1;let s=[];for(let e=a;e<=o;e+=1)s.push(dw(n,e,i,e===o));let c=(r-a)*i+t.col;return{text:s.join(``).trimEnd(),col:c,startRow:a,endRow:o,bufferRow:r,cols:i,buffer:n}}function Sw(e,t){let n=e.terminal.buffer?.active;if(!n||typeof n.getLine!=`function`||!Number.isFinite(t)||t<0)return null;let r=e.terminal.cols||80,i=t;for(;i>0&&n.getLine(i)?.isWrapped;)--i;let a=t;for(;n.getLine(a+1)?.isWrapped;)a+=1;let o=[];for(let e=i;e<=a;e+=1)o.push(dw(n,e,r,e===a));return{text:o.join(``).trimEnd(),col:0,startRow:i,endRow:a,bufferRow:t,cols:r,buffer:n}}function Cw(e,t,n=100){let r=[],i=t-1;for(;i>=0&&r.length<n;){let t=Sw(e,i);if(!t)break;r.push(t.text),i=t.startRow-1}return r}function ww(e,t){let n=xw(e,t);return n?Kb(n.text,n.col)||(Gb(n.text,Cw(e,n.startRow)).find(e=>n.col>=e.startIndex&&n.col<e.startIndex+e.length)??null):null}var Tw=3;function Ew(e){let t=I(e.agentId,`terminal`);if(e.followOutput)return ee(t),null;let n=mx(e.terminal),r=Sw(e,n);if(!r)return null;let i=[],a=r.startRow;for(let t=0;t<Tw;t+=1){let t=Sw(e,a);if(!t)break;i.push(t.text),a=t.endRow+1}if(i.length===0)return null;let o={version:1,surface:`terminal`,resource:{kind:`agent`,id:e.agentId},locator:{kind:`terminal-lines`,id:P(i),lineCount:i.length},position:{unit:`row`,value:Math.max(0,n-r.startRow)}};return me(o),o}function Dw(e,t){let n=e.terminal.buffer?.active;if(!n||typeof n.getLine!=`function`)return!1;let r=Math.max(0,fx(e.terminal)+Math.max(1,e.terminal.rows||1)),i=Math.max(1,t.locator.lineCount||1),a=null,o=1/0;for(let n=0;n<=r;){let r=Sw(e,n);if(!r){n+=1;continue}let s=[r.text],c=r.endRow+1;for(let t=1;t<i;t+=1){let t=Sw(e,c);if(!t)break;s.push(t.text),c=t.endRow+1}if(s.length===i&&P(s)===t.locator.id){let t=Math.abs(r.startRow-mx(e.terminal));t<o&&(a=r,o=t)}n=Math.max(n+1,r.endRow+1)}return a?(Lx(e,Math.min(a.endRow,a.startRow+Math.max(0,t.position.value))),_x(e,!1,e.hasUnreadOutput),!0):!1}function Ow(e,t){let n=xw(e,t);return n?{text:n.text,col:n.col}:null}function kw(e,t){let n=document.elementFromPoint(t.clientX,t.clientY);if(!(n instanceof HTMLElement))return null;let r=n.closest(`.xterm-rows > div`);if(!r||!e.hostEl.contains(r))return null;let i=LC(e),a=r.getBoundingClientRect();if(!i||i.width<=0||a.width<=0)return null;let o=(r.textContent||``).trimEnd();if(!o)return null;let s=qb(t.clientX-a.left,i.width,o.length);return s===null?null:{text:o,col:s}}function Aw(e,t){return Ow(e,t)}function jw(e,t){let n=uw(e,t);if(n){let t=ww(e,n);if(t)return t}let r=kw(e,t);return r?Kb(r.text,r.col):null}function Mw(e,t){let n=jw(e,t);return n?yw(e,n):null}function Nw(e,t){return Mw(e,t)?.pathTarget??null}function Pw(e,t){let n=uw(e,t);if(n){let t=Aw(e,n),r=t?Xb(t.text,t.col):null;if(r)return r}let r=kw(e,t);return r?Xb(r.text,r.col):null}function Fw(e,t){if(Pw(e,t)||e.pathOpenHandler&&jw(e,t))return null;let n=uw(e,t);if(n){let t=Ow(e,n),r=t?$b(t.text,t.col):null;if(r)return r}let r=kw(e,t);return r?$b(r.text,r.col):null}function Iw(e){return lx(e.terminal.getSelection()||``)}function Lw(e,t){return($y(e.terminal)?Iw(e):lx(cx(e.terminal)))||(!$y(e.terminal)&&t?.includeNativeFallback?lx(zw(e.hostEl)):``)}function Rw(e,t){let n=e.terminal.getSelectionPosition?.();if(!n||!e.terminal.getSelection?.())return!1;let r=uw(e,t);if(!r)return!1;let{start:i,end:a}=nx(n),o={x:r.col,y:mx(e.terminal)+r.row};return!(o.y<i.y||o.y>a.y||o.y===i.y&&o.x<i.x||o.y===a.y&&o.x>a.x)}function zw(e){let t=window.getSelection?.();if(!t||t.isCollapsed)return``;let n=t.anchorNode,r=t.focusNode;return n&&!e.contains(n)||r&&!e.contains(r)?``:t.toString()}function Bw(e,t){_S(t)}function Vw(e){let t=navigator.platform.toLowerCase().includes(`mac`)?`Cmd`:`Ctrl`;return(document.documentElement.lang||navigator.language||``).toLowerCase().startsWith(`zh`)?e===`url`?`按住 ${t} 点击打开链接`:e===`search`?`按住 ${t} 点击在工作区中搜索`:`点击打开文件或文件夹`:e===`url`?`${t}-click to open link`:e===`search`?`${t}-click to search the workspace`:`Click to open file or folder`}function Hw(e,t){e.hostEl.classList.toggle(`terminal-open-target-hover`,t!==null),e.hostEl.classList.toggle(`terminal-open-target-url`,t===`url`),e.hostEl.classList.toggle(`terminal-open-target-path`,t===`path`),e.hostEl.classList.toggle(`terminal-open-target-search`,t===`search`),t?(e.hostEl.dataset.terminalOpenTarget=t,e.hostEl.title=Vw(t)):(delete e.hostEl.dataset.terminalOpenTarget,e.hostEl.removeAttribute(`title`))}function Uw(e){e.openModifierActive=!1,e.lastLinkHoverEvent=null,e.linkProviderHoverTarget=null,Hw(e,null)}function Ww(e,t,n=mw(e,t)){return e.pathOpenHandler&&Nw(e,t)?`path`:n?Pw(e,t)?`url`:e.searchOpenHandler&&Fw(e,t)?`search`:null:null}async function Gw(e,t){if(!e.pathOpenHandler)return null;let n=jw(e,t);if(!n?.pathTarget)return null;let r=await _w(e,n.pathTarget);return r?{...n,pathTarget:r}:null}function Kw(e,t){if(!pC(e)||ae()){Hw(e,null);return}let n=e.linkProviderHoverTarget,r=t??e.openModifierActive;if(n){Hw(e,n.kind===`path`||r?n.kind:null);return}if(!e.lastLinkHoverEvent){Hw(e,null);return}Hw(e,Ww(e,e.lastLinkHoverEvent,r))}function qw(e){e.contextMenuCleanup?.(),e.contextMenuCleanup=null,e.contextMenuEl?.remove(),e.contextMenuEl=null,e.contextMenuSelection=``}function Jw(e){let t=(document.documentElement.lang||navigator.language||``).toLowerCase().startsWith(`zh`);return e===`copy`?t?`复制`:`Copy`:e===`paste`?t?`粘贴`:`Paste`:e===`clear`?t?`清除`:`Clear`:t?`全选`:`Select All`}function Yw(e,t,n=160,r=148){return{x:Math.max(8,Math.min(e,window.innerWidth-n-8)),y:Math.max(8,Math.min(t,window.innerHeight-r-8))}}function Xw(e){e.querySelector(`button:not(:disabled)`)?.focus()}function Zw(e,t,n={}){let r=document.createElement(`button`);return r.type=`button`,r.className=`terminal-context-menu-item`,r.setAttribute(`role`,`menuitem`),r.textContent=e,r.disabled=n.disabled===!0,r.addEventListener(`click`,()=>{r.disabled||t()}),r}function Qw(e,t){return!(!t||e.disposed||e.attachedMount===null||(Rx(e,{allowClearUnread:!0}),!ZC(e,t)))}function $w(e){e.disposed||e.attachedMount===null||(nT(e),e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.terminal.clearSearch?.(),_x(e,!0,!1,{allowClearUnread:!0}),Ht({type:`clear-terminal`,agentId:e.agentId}))}function eT(e,t,n){qw(e);let r=Yw(t.clientX,t.clientY),i=document.createElement(`div`);i.className=`terminal-context-menu terminal-context-menu-pooled`,i.setAttribute(`data-testid`,`code-terminal-context-menu`),i.setAttribute(`role`,`menu`),i.style.left=`${r.x}px`,i.style.top=`${r.y}px`;let a=Zw(Jw(`copy`),()=>{let t=ES;Se(n).finally(()=>{let n=rC(e,i,t);qw(e),!ae()&&n&&nC(e)})},{disabled:!n}),o=Zw(Jw(`paste`),()=>{let t=ES;ye().then(t=>{Qw(e,t)}).finally(()=>{let n=rC(e,i,t);qw(e),!ae()&&n&&nC(e)})}),s=Zw(Jw(`selectAll`),()=>{qw(e),nT(e),requestAnimationFrame(()=>{if(e.disposed)return;let t=lw(e);e.contextMenuSelection=t,e.lastNonEmptySelection=t||e.lastNonEmptySelection,ae()||nC(e)})},{disabled:typeof e.terminal.select!=`function`||!e.terminal.buffer?.active}),c=Zw(Jw(`clear`),()=>{qw(e),$w(e),ae()||nC(e)});i.addEventListener(`mousedown`,e=>e.stopPropagation()),i.addEventListener(`pointerdown`,e=>e.stopPropagation()),i.addEventListener(`keydown`,e=>{if(!(e.target instanceof HTMLButtonElement)||e.key!==`ArrowDown`&&e.key!==`ArrowUp`)return;let t=Array.from(i.querySelectorAll(`button:not(:disabled)`)),n=t.indexOf(e.target);n<0||t.length===0||(e.preventDefault(),t[(n+(e.key===`ArrowDown`?1:-1)+t.length)%t.length]?.focus())}),i.appendChild(a),i.appendChild(o),i.appendChild(s),i.appendChild(c),document.body.appendChild(i),e.contextMenuEl=i;let l=t=>{let n=t.target;n instanceof Node&&i.contains(n)||qw(e)},u=t=>{t.key===`Escape`&&(t.preventDefault(),qw(e),ae()||nC(e))},d=()=>qw(e);document.addEventListener(`mousedown`,l,!0),document.addEventListener(`pointerdown`,l,!0),document.addEventListener(`keydown`,u,!0),window.addEventListener(`resize`,d),window.addEventListener(`scroll`,d,!0),e.contextMenuCleanup=()=>{document.removeEventListener(`mousedown`,l,!0),document.removeEventListener(`pointerdown`,l,!0),document.removeEventListener(`keydown`,u,!0),window.removeEventListener(`resize`,d),window.removeEventListener(`scroll`,d,!0)},requestAnimationFrame(()=>Xw(i))}function tT(e){let t=window.getSelection?.();if(!t||t.rangeCount===0)return;let n=t.anchorNode,r=t.focusNode;n&&!e.contains(n)||r&&!e.contains(r)||t.removeAllRanges()}function nT(e){e.cachedSelection=``,e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.dragSelection=null,e.terminal.clearTerminalSelection?.(),tT(e.hostEl)}function rT(e){qw(e),Uw(e),nT(e)}function iT(e){rT(e),$y(e.terminal)&&(e.terminal.reattach?.(),e.terminal.syncAppearanceTheme?.(),e.terminal.forceRedraw?.()),Fx(e),requestAnimationFrame(()=>{e.disposed||e.attachedMount===null||($y(e.terminal)&&e.terminal.forceRedraw?.(),Mx(e))})}function aT(e,t){let n=Lw(e)||e.contextMenuSelection||e.lastNonEmptySelection,r=Pw(e,t),i=e.pathOpenHandler?Mw(e,t):null,a=!!n&&Rw(e,t),o=n.replace(/\s+/g,``);if(r&&(!a||r.includes(o)))return r;if(i?.text&&(!a||i.text.includes(o)))return i.text;if(n)return n;let s=uw(e,t);return s?sw(e,s.col,s.row):``}function oT(e,t){let n=n=>{if(!(n.target instanceof Node)||!e.hostEl.contains(n.target))return;let r=Pw(e,n);if(r){vS({event:n,url:r,onOpenInFarming:e.farmingUrlOpenHandler?()=>e.farmingUrlOpenHandler?.(t,r):void 0});return}let i=e.pathOpenHandler?jw(e,n):null;if(i?.pathTarget){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),_w(e,i.pathTarget).then(t=>{if(!e.disposed){if(t){eT(e,n,i.text);return}eT(e,n,aT(e,n))}});return}if(e.pathOpenHandler&&fw(n)){let r=Nw(e,n);if(r){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),e.pathOpenHandler(t,r);return}}let a=aT(e,n);n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),eT(e,n,a)},r=t=>{if(!(!(t.target instanceof Node)||!e.hostEl.contains(t.target))){if(t.button===0){e.contextMenuSelection=``,e.lastNonEmptySelection=``;return}t.button===2&&(e.contextMenuSelection=Lw(e)||lx(e.cachedSelection)||e.lastNonEmptySelection)}};window.addEventListener(`mousedown`,r,!0),window.addEventListener(`contextmenu`,n,!0),e.hostEl.addEventListener(`mousedown`,r,!0),e.hostEl.addEventListener(`contextmenu`,n,!0),e.contextMenuMouseDownHandler=r,e.contextMenuHandler=n}function sT(e){let t=null,n=0,r=0,i=0,a=0,o=0,s=0,c=!1,l=null,u=0,d=[],f=0,p=null,m=null,h=null,g=e=>Math.max(-AS,Math.min(AS,e)),_=()=>{m!==null&&(window.clearTimeout(m),m=null),h=null},v=()=>e.hostEl.querySelector(`.xterm-screen`),y=()=>{p!==null&&(window.clearTimeout(p),p=null)},b=(e,t=!1)=>{let n=v();f=e,n&&(y(),n.style.transition=t?`transform ${FS}ms cubic-bezier(0.22, 0.75, 0.28, 1)`:`none`,n.style.transform=e===0?``:`translate3d(0, ${e}px, 0)`,t&&(p=window.setTimeout(()=>{n.style.transition=``,n.style.transform=``,p=null},FS)))},x=e=>{b(Math.max(-PS,Math.min(PS,f+e*NS)))},S=(e=!0)=>{f===0&&p===null||b(0,e)},C=(e,t)=>{d.push({y:e,at:t});let n=t-MS;for(;d.length>2&&d[0].at<n;)d.shift()},w=()=>{let e=d[0],t=d[d.length-1];return!e||!t||t.at<=e.at?o:g((t.y-e.y)/(t.at-e.at))},T=()=>{let t=h;if(_(),!t||e.disposed||c)return;let n=aT(e,t);n&&eT(e,t,n)},E=t=>{let n=Math.max(8,LC(e)?.height||16);s+=t;let r=Math.trunc(s/n);if(r===0)return!1;s-=r*n;let i=px(e.terminal);Ix(e,i+r);let a=px(e.terminal)!==i;return a&&(zC(e,{allowClearUnread:!0}),qw(e)),a},D=()=>{l!==null&&(window.cancelAnimationFrame(l),l=null),u=0,o=0,s=0},O=t=>{if(e.disposed){l=null;return}let n=u===0?16:Math.min(48,Math.max(1,t-u));u=t;let r=o*n,i=E(r);if(o*=jS**(n/16),!i||Math.abs(o)<kS){i||x(r),D(),S();return}l=window.requestAnimationFrame(O)},k=()=>{if(Math.abs(o)<kS){o=0;return}u=0,l=window.requestAnimationFrame(O)},A=o=>{if(o.pointerType===`touch`){D(),S(!1),t=o.pointerId,n=o.clientX,r=o.clientY,i=o.clientY,a=o.timeStamp||performance.now(),d=[],C(o.clientY,a),s=0,c=!1,h=o,m=window.setTimeout(T,OS);try{e.hostEl.setPointerCapture(o.pointerId)}catch{}}},j=e=>{if(t===null||e.pointerId!==t)return;Math.hypot(e.clientX-n,e.clientY-r)>DS&&(c=!0,_());let s=e.clientY-i,l=e.timeStamp||performance.now(),u=Math.max(1,l-a);if(i=e.clientY,a=l,Math.abs(s)<.5)return;C(e.clientY,l);let d=s/u;o=g(w()*.72+d*.28);let p=E(s);!p&&c?x(s):p&&f!==0&&S(!1),(c||p)&&(e.preventDefault(),e.stopPropagation())},M=n=>{if(t===null||n.pointerId!==t)return;let r=c;t=null,_(),r?(n.preventDefault(),n.stopPropagation(),zC(e,{allowClearUnread:!0}),o=w(),n.type===`pointerup`&&f===0?k():(D(),S())):(o=0,s=0,S()),d=[];try{e.hostEl.releasePointerCapture(n.pointerId)}catch{}};e.hostEl.addEventListener(`pointerdown`,A,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointermove`,j,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointerup`,M,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointercancel`,M,{capture:!0,passive:!1}),e.hostEl.addEventListener(`lostpointercapture`,M,{capture:!0,passive:!1}),e.touchInteraction={pointerDownHandler:A,pointerMoveHandler:j,pointerUpHandler:M,stopTouchMomentum:D}}function cT(){typeof window>`u`||!window.__FARMING_E2E__||window.__farmingTerminalTest||(window.__farmingTerminalTest={async writeFixture(e,t){let n=TS.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);r.bootstrapRefreshSeq+=1,zS(r),r.snapshotOutput=``,r.snapshotRuntimeEpoch=``,r.snapshotOutputSeq=null,r.snapshotStateRevision=null,r.snapshotCols=null,r.snapshotRows=null,wS.resetRecovery(r.replayState,{keepCursor:!1}),r.replayInProgress=!1,r.liveWriteInProgress=!1,r.pendingSnapshotReplay=!1,r.bootstrappingSnapshot=!1,r.needsReconnectOutputSync=!1,r.fixtureOverrideActive=!0,r.suppressOutputUntil=Date.now()+1500,rT(r),r.openTargetMouseDown=null,r.suppressClickUntil=0,r.terminal.reset(),r.terminal.viewportY=0,r.terminal.scrollToLine?.(0),await new Promise(e=>r.terminal.write(t,e)),r.terminal.viewportY=0,r.terminal.scrollToLine?.(0),_x(r,hx(r),!1,{allowClearUnread:!0}),Mx(r),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async resumeLive(e){let t=TS.get(e),n=t instanceof Promise?await t:t;if(!n||n.disposed)throw Error(`Terminal session not found: ${e}`);n.fixtureOverrideActive=!1,n.suppressOutputUntil=0,zS(n),wS.resetRecovery(n.replayState),wS.beginRecovery(n.replayState),n.needsReconnectOutputSync=!0,AC(n,n.attachGeneration)},getSelection(e){return xT(e)},getCellCenter(e,t,n){let r=TS.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=LC(r),a=RC(r);return!i||!a?null:{x:a.left+(t+.5)*i.width,y:a.top+(n+.5)*i.height}},getRows(e,t=6){let n=TS.get(e);if(!n||n instanceof Promise||n.disposed)return[];let r=n.terminal.buffer?.active;if(!r||typeof r.getLine!=`function`)return[];let i=[],a=mx(n.terminal);for(let e=0;e<t;e+=1){let t=r.getLine(a+e),o=[],s=n.terminal.cols||t?.length||0;for(let e=0;e<s;e+=1){let n=t?.getCell?.(e);ix(n)||o.push(rx(n)||` `)}i.push(o.join(``).trimEnd())}return i},getHostDiagnostics(){return Array.from(document.querySelectorAll(`.terminal-session-host`)).map(e=>{let t=e,n=RS(t),r=t.getBoundingClientRect(),i=t.parentElement,a=i?.classList.contains(`terminal-container`)?i:null;return{agentId:t.dataset.agentId||``,paneAgentId:t.closest(`[data-testid="code-terminal-pane"]`)?.getAttribute(`data-agent-id`)||``,inParkingLot:t.closest(`#terminal-session-parking-lot`)!==null,recordAttached:n?fC(n):!1,attachedMountMatchesParent:n?n.attachedMount!==null&&n.hostEl.parentElement===n.attachedMount:!1,visible:r.width>0&&r.height>0&&getComputedStyle(t).display!==`none`,hostCountInMount:a?a.querySelectorAll(`.terminal-session-host`).length:0}})},doubleClickCell(e,t,n){let r=TS.get(e);return!r||r instanceof Promise||r.disposed?``:sw(r,t,n)},getUrlAtCell(e,t,n){let r=TS.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=Aw(r,{col:t,row:n});return i?Xb(i.text,i.col):null},isReady(e){let t=TS.get(e);return!!(t&&!(t instanceof Promise)&&!t.disposed&&!t.bootstrappingSnapshot&&!t.pendingSnapshotReplay)},getPathAtCell(e,t,n){let r=TS.get(e);return!r||r instanceof Promise||r.disposed?null:ww(r,{col:t,row:n})?.pathTarget??null},openPathAtCell(e,t,n){let r=TS.get(e);if(!r||r instanceof Promise||r.disposed||!r.pathOpenHandler)return!1;let i=ww(r,{col:t,row:n})?.pathTarget??null;return i?(r.pathOpenHandler(e,i),!0):!1},getCursor(e){let t=TS.get(e);return!t||t instanceof Promise||t.disposed?null:t.terminal.wasmTerm?.getCursor?.()??null},getCursorVisible(e){let t=TS.get(e);if(!t||t instanceof Promise||t.disposed)return;let n=t.terminal.wasmTerm?.getCursor?.().visible;return n===void 0?void 0:!!n},getRendererCursorVisible(e){let t=TS.get(e);if(!t||t instanceof Promise||t.disposed)return;let n=t.terminal.renderer?.cursorVisible;return n===void 0?void 0:!!n},getCursorCellPixel(e){let t=TS.get(e);if(!t||t instanceof Promise||t.disposed)return null;let n=t.terminal.renderer?.getCanvas?.()||t.hostEl.querySelector(`canvas`),r=LC(t),i=t.terminal.wasmTerm?.getCursor?.();if(!(n instanceof HTMLCanvasElement)||!r||!i){let e=t.hostEl.querySelector(`.xterm-cursor`);if(!(e instanceof HTMLElement))return null;let n=(getComputedStyle(e).backgroundColor||Br.cursor).match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([0-9.]+))?\)/);return n?{r:Number(n[1]??36),g:Number(n[2]??41),b:Number(n[3]??47),a:Math.round(Number(n[4]??1)*255)}:{r:36,g:41,b:47,a:255}}let a=n.width/Math.max(1,n.getBoundingClientRect().width),o=n.height/Math.max(1,n.getBoundingClientRect().height),s=Math.min(n.width-1,Math.max(0,Math.floor((i.x+.5)*r.width*a))),c=Math.min(n.height-1,Math.max(0,Math.floor((i.y+.5)*r.height*o))),l=n.getContext(`2d`)?.getImageData(s,c,1,1).data;return l?{r:l[0]??0,g:l[1]??0,b:l[2]??0,a:l[3]??0}:null},getCanvasInkPixelCount(e){let t=TS.get(e);if(!t||t instanceof Promise||t.disposed)return 0;let n=t.terminal.renderer?.getCanvas?.(),r=[...new Set([...n instanceof HTMLCanvasElement?[n]:[],...t.hostEl.querySelectorAll(`canvas`)])];if(r.length===0)return(t.hostEl.querySelector(`.xterm-rows`)?.textContent?.trim()??``).length*8;let i=0;for(let e of r){let t=null,n=e.getContext(`2d`);if(n)t=n.getImageData(0,0,e.width,e.height).data;else{let n=e.getContext(`webgl2`)||e.getContext(`webgl`);n&&(t=new Uint8Array(e.width*e.height*4),n.readPixels(0,0,e.width,e.height,n.RGBA,n.UNSIGNED_BYTE,t))}if(t)for(let e=0;e<t.length;e+=4){let n=t[e]??255,r=t[e+1]??255,a=t[e+2]??255;(t[e+3]??0)>0&&!(n>248&&r>248&&a>245)&&(i+=1)}}return i},async writeRaw(e,t){let n=TS.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);await new Promise(e=>qx(r,t,e,{isOutputObserved:()=>fC(r)})),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async writeSequenced(e,t,n,r=``,i){let a=TS.get(e),o=a instanceof Promise?await a:a;if(!o||o.disposed)throw Error(`Terminal session not found: ${e}`);jC(o,t,!1,n,r,i??(o.replayState.stateRevision??0)+1),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async streamSequenced(e,t,n,r=``,i,a=`output`,o,s){let c=TS.get(e),l=c instanceof Promise?await c:c;if(!l||l.disposed)throw Error(`Terminal session not found: ${e}`);MC(l,t,!1,n,r,i??(l.replayState.stateRevision??0)+1,o,s,a)},async writeRawAndSampleViewport(e,t){let n=TS.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);let i=px(r.terminal),a=fx(r.terminal),o=i;return await new Promise(e=>{qx(r,t,e,{isOutputObserved:()=>fC(r)}),o=px(r.terminal)}),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),{before:i,during:o,after:px(r.terminal),beforeScrollbackLength:a,afterScrollbackLength:fx(r.terminal),following:r.followOutput,hasUnreadOutput:r.hasUnreadOutput}},getViewport(e){let t=TS.get(e);return!t||t instanceof Promise||t.disposed?null:{viewportY:px(t.terminal),scrollbackLength:fx(t.terminal),following:t.followOutput,hasUnreadOutput:t.hasUnreadOutput}},getInputCount(e){let t=TS.get(e);return!t||t instanceof Promise||t.disposed?0:t.inputCount},getLastNotifiedResize(e){let t=TS.get(e);return!t||t instanceof Promise||t.disposed?null:t.lastNotifiedResize},getResizeNotificationCount(e){let t=TS.get(e);return!t||t instanceof Promise||t.disposed?0:t.resizeNotificationCount},notifyResizeForTest(e,t,n){let r=TS.get(e);return!r||r instanceof Promise||r.disposed?0:(ew(r,t,n),r.resizeNotificationCount)},getLastOutputSeq(e){let t=TS.get(e);return!t||t instanceof Promise||t.disposed?null:t.replayState.outputSeq},getRuntimeEpoch(e){let t=TS.get(e);return!t||t instanceof Promise||t.disposed?``:t.replayState.runtimeEpoch},getStateRevision(e){let t=TS.get(e);return!t||t instanceof Promise||t.disposed?null:t.replayState.stateRevision},setCheckpointAckSuppressed(e){let t=TS.get(e);return!!(t&&!(t instanceof Promise)&&!t.disposed)},setCheckpointInstallCompletionHeld(e,t){let n=TS.get(e);if(!n||n instanceof Promise||n.disposed)return!1;if(n.holdCheckpointInstallCompletionForTest=t,!t){let e=n.heldCheckpointInstallCompletionForTest;n.heldCheckpointInstallCompletionForTest=null,e?.()}return!0},getBufferDiagnostics(e){let t=TS.get(e);if(!t||t instanceof Promise||t.disposed)return null;let n=t.terminal.buffer?.active;return{engine:t.terminal.__farmingTerminalEngine,renderer:t.terminal.getRendererType?.(),cols:t.terminal.cols||0,rows:t.terminal.rows||0,viewportY:px(t.terminal),scrollbackLength:fx(t.terminal),visibleBufferBase:mx(t.terminal),bufferViewportY:typeof n?.viewportY==`number`?n.viewportY:void 0,bufferBaseY:typeof n?.baseY==`number`?n.baseY:void 0,bufferLength:typeof n?.length==`number`?n.length:void 0,queuedTransitions:t.replayState.queuedTransitions.length,queuedBytes:t.replayState.queuedBytes,terminalWriteBatchCount:t.terminalWriteBatchCount,resizeRedrawTimerPending:t.resizeRedrawTimer!==null,replayTargetEpoch:t.replayState.replayTargetEpoch,replayTargetRevision:t.replayState.replayTargetRevision,checkpointHalted:t.replayState.halted,checkpointFailureCount:t.replayState.failureCount,checkpointRequestInFlight:t.checkpointRequestInFlight,replayInProgress:t.replayInProgress,bootstrappingSnapshot:t.bootstrappingSnapshot,pendingSnapshotReplay:t.pendingSnapshotReplay,runtimeEpoch:t.replayState.runtimeEpoch,stateRevision:t.replayState.stateRevision,lastOutputSeq:t.replayState.outputSeq,reconnectSnapshotSeq:t.reconnectSnapshotSeq,bootstrapRefreshSeq:t.bootstrapRefreshSeq,attachGeneration:t.attachGeneration,currentAttachment:_C(t,t.attachGeneration),attachedMount:t.attachedMount!==null,fixtureOverrideActive:t.fixtureOverrideActive,pageOutputSuspended:t.pageOutputSuspended,suppressOutputForMs:Math.max(0,t.suppressOutputUntil-Date.now()),needsReconnectOutputSync:t.needsReconnectOutputSync,lastNotifiedResize:t.lastNotifiedResize,resizeNotificationCount:t.resizeNotificationCount,resizeRequestInFlight:t.resizeRequestInFlight,pendingResizeRequest:t.pendingResizeRequest,resizeDeliveryTimeoutPending:t.resizeDeliveryTimeout!==null,pendingFitResize:t.pendingFitResize,fitResizeTimerPending:t.fitResizeTimer!==null}},async scrollToLine(e,t){let n=TS.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);r.touchInteraction?.stopTouchMomentum(),Lx(r,t);let i=hx(r);_x(r,i,i?!1:r.hasUnreadOutput,{allowClearUnread:i}),await new Promise(e=>requestAnimationFrame(()=>e()))},async scrollToBottom(e){let t=TS.get(e),n=t instanceof Promise?await t:t;if(!n||n.disposed)throw Error(`Terminal session not found: ${e}`);n.touchInteraction?.stopTouchMomentum(),Rx(n,{allowClearUnread:!0}),await new Promise(e=>requestAnimationFrame(()=>e()))},async search(e,t,n=`next`,r={}){return kT(e,t,n,r)},async clearSearch(e){await AT(e)},dispatchPasteToTextarea(e,t){let n=TS.get(e);if(!n||n instanceof Promise||n.disposed)return{prevented:!1};let r=n.hostEl.querySelector(`textarea`);if(!(r instanceof HTMLTextAreaElement))return{prevented:!1};let i=new window.DataTransfer;i.setData(`text/plain`,t);let a=new window.ClipboardEvent(`paste`,{clipboardData:i,bubbles:!0,cancelable:!0});return r.dispatchEvent(a),{prevented:a.defaultPrevented}},dispatchCopyFromTextarea(e){let t=TS.get(e);if(!t||t instanceof Promise||t.disposed)return{prevented:!1,text:``};let n=t.hostEl.querySelector(`textarea`);if(!(n instanceof HTMLTextAreaElement))return{prevented:!1,text:``};let r=new window.DataTransfer,i=new window.ClipboardEvent(`copy`,{clipboardData:r,bubbles:!0,cancelable:!0});return n.dispatchEvent(i),{prevented:i.defaultPrevented,text:r.getData(`text/plain`)}}})}async function lT(e,t){let n=Nt(jt(),de()),r=await tb({fontSize:n});if(!r)throw Error(`Failed to create terminal for ${e}`);let i=document.createElement(`div`);i.className=`terminal-session-host`,i.dataset.agentId=e,i.dataset.terminalFontSize=String(n),i.style.width=`100%`,i.style.height=`100%`,i.style.position=`relative`,i.style.overflow=`hidden`;let{terminal:a,fitAddon:o}=r;a.loadAddon(o);let s={agentId:e,hostEl:i,attachedMount:null,attachGeneration:0,attachReadyHandler:null,attachReadyGeneration:null,attachReadyNotified:!1,terminal:a,fitAddon:o,unsubscribeOutput:null,selectionChangeDisposable:null,imeOverlayDisposables:[],resizeObserver:null,applyingLocalResize:!1,parkedViewportState:null,inputDisabled:!!t.inputDisabled,errorHandler:t.onError??null,recoveryStatusHandler:t.onRecoveryStatusChange??null,recoveryStatus:{phase:`requesting`,attempt:1,startedAt:Date.now(),retryDelayMs:null},rendererFailureDisposable:null,scrollChangeDisposable:null,backendConnectedHandler:null,clickHandler:null,pointerDownSelectionHandler:null,pointerMoveSelectionHandler:null,pointerUpSelectionHandler:null,mouseDownOpenTargetHandler:null,mouseDownSelectionHandler:null,mouseMoveSelectionHandler:null,mouseUpSelectionHandler:null,mouseUpOpenTargetHandler:null,doubleClickHandler:null,copyHandler:null,copyKeyHandler:null,clearKeyHandler:null,pasteHandler:null,lastLinkHoverEvent:null,openModifierActive:!1,linkHoverHandler:null,linkHoverLeaveHandler:null,linkHoverKeyHandler:null,linkHoverBlurHandler:null,linkProviderDisposable:null,linkProviderHoverTarget:null,contextMenuHandler:null,contextMenuMouseDownHandler:null,contextMenuEl:null,contextMenuCleanup:null,contextMenuSelection:``,imeKeydownHandler:null,scrollIntentHandler:null,scrollKeyHandler:null,touchInteraction:null,lastNotifiedResize:null,resizeNotificationCount:0,resizeRequestInFlight:null,pendingResizeRequest:null,resizeDeliveryTimeout:null,pendingFitResize:null,fitResizeTimer:null,resizeAfterReplayRequired:!1,followOutputHandler:t.onFollowOutputChange??null,pathOpenHandler:t.onPathOpen??null,pathResolveHandler:t.onPathResolve??null,searchOpenHandler:t.onSearchOpen??null,farmingUrlOpenHandler:t.onOpenUrlInFarming??null,pathResolveCache:new Map,originalRender:null,snapshotOutput:``,snapshotRuntimeEpoch:``,snapshotOutputSeq:null,snapshotStateRevision:null,snapshotCols:null,snapshotRows:null,replayState:wS.createState(),replayInProgress:!1,liveWriteInProgress:!1,liveTransitionFlushScheduled:!1,resizeRedrawStartedAt:null,resizeRedrawTimer:null,terminalWriteQueue:Promise.resolve(),terminalWriteResolvers:new Set,terminalWriteBatchCount:0,holdCheckpointInstallCompletionForTest:!1,heldCheckpointInstallCompletionForTest:null,bootstrapRefreshSeq:0,reconnectSnapshotSeq:0,checkpointRequestInFlight:!1,checkpointRetryTimer:null,bootstrapRequestControllers:new Set,needsReconnectOutputSync:!1,pageOutputSuspended:document.visibilityState===`hidden`,pageLifecycleHandler:null,pendingSnapshotReplay:!1,bootstrappingSnapshot:!0,fixtureOverrideActive:!1,suspendRendering:!1,cachedSelection:``,lastNonEmptySelection:``,openTargetMouseDown:null,dragSelection:null,suppressClickUntil:0,suppressOutputUntil:0,imeComposing:!1,suppressRendererCursor:!!t.suppressRendererCursor,rendererCursorWasVisible:void 0,inputCount:0,followOutput:!0,hasUnreadOutput:!1,preserveUnreadOutputUntilJump:!1,followCheckFrame:null,disposed:!1,bootstrapped:!0};yC(s,t.bootstrapState),a.onData(e=>{s.inputDisabled||ZC(s,e)}),a.onResize(({cols:e,rows:t})=>{s.applyingLocalResize||s.replayInProgress||s.bootstrappingSnapshot||ew(s,e,t)}),oT(s,e);let c=a.onRendererFailure?.(e=>{s.disposed||(s.inputDisabled=!0,GS(s),QS(s,`failed`),s.errorHandler?.(e),CT(s.agentId).catch(e=>{console.error(`Failed to dispose terminal after renderer failure:`,e)}))});s.rendererFailureDisposable=c?()=>c.dispose():null,a.open(i),bw(s),a.syncAppearanceTheme?.(),requestAnimationFrame(()=>{s.disposed||a.syncAppearanceTheme?.()}),qC(s),WC(s,!1);let l=a.onSelectionChange?.(()=>{s.cachedSelection=cx(a),s.cachedSelection&&(s.lastNonEmptySelection=lx(s.cachedSelection))});s.selectionChangeDisposable=l?()=>l.dispose():null;let u=a.onScroll?.(()=>{VC(s),Ew(s)}),d=a.onRender?.(()=>{VC(s)});s.scrollChangeDisposable=u||d?()=>{u?.dispose(),d?.dispose()}:null;let f=()=>tw(s);window.addEventListener(`farming:backend-connected`,f),s.backendConnectedHandler=f;let p=e=>{let t=e.type===`pagehide`||document.visibilityState===`hidden`;if(s.pageOutputSuspended=t,t){GS(s),s.needsReconnectOutputSync=!0;return}nw(s)};document.addEventListener(`visibilitychange`,p),window.addEventListener(`pagehide`,p),window.addEventListener(`pageshow`,p),s.pageLifecycleHandler=p,JC(s);let m=t=>{let n=mw(s,t),r=t.button===0&&n?Pw(s,t):null;if(r)return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),Bw(s,r),s.suppressClickUntil=Date.now()+250,!0;let i=t.button===0&&n&&s.searchOpenHandler?Fw(s,t):null;if(i)return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),nT(s),s.searchOpenHandler?.(e,i),s.suppressClickUntil=Date.now()+250,!0;if(s.pathOpenHandler&&t.button===0){let n=Nw(s,t);if(n){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),nT(s);let r=s.attachGeneration;return _w(s,n).then(t=>{if(_C(s,r)){if(!t){nC(s);return}s.pathOpenHandler?.(e,t)}}),s.suppressClickUntil=Date.now()+250,!0}}return!1},h=(e,t)=>{if(ae()||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return!1;let n=uw(s,e);return n?(s.dragSelection={start:n,active:!0,moved:!1,pointerId:t},!0):!1},g=e=>{let t=s.dragSelection;if(!t?.active||`pointerId`in e&&t.pointerId!==void 0&&e.pointerId!==t.pointerId)return!1;let n=uw(s,e);return!n||n.col===t.start.col&&n.row===t.start.row&&!t.moved?!1:(t.moved=!0,cw(s,t.start,n),e.preventDefault(),e.stopPropagation(),!0)},_=e=>{let t=s.dragSelection;return!t?.active||`pointerId`in e&&t.pointerId!==void 0&&e.pointerId!==t.pointerId||(s.dragSelection=null,!t.moved)?!1:(s.suppressClickUntil=Date.now()+250,s.cachedSelection=cx(a),e.preventDefault(),e.stopPropagation(),!0)},v=e=>{if(s.openTargetMouseDown=null,ae()||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return;let t=s.pathOpenHandler?jw(s,e):null;t?.pathTarget&&(s.openTargetMouseDown={x:e.clientX,y:e.clientY,pathTarget:t.pathTarget})};i.addEventListener(`mousedown`,v,!0),s.mouseDownOpenTargetHandler=v;let y=t=>{if(ae()||t.button!==0)return;if(Date.now()<s.suppressClickUntil){s.openTargetMouseDown=null;return}if(mw(s,t)){let n=Pw(s,t);if(n){t.preventDefault(),$y(a)||(t.stopPropagation(),t.stopImmediatePropagation()),Bw(s,n),s.suppressClickUntil=Date.now()+250;return}let r=s.searchOpenHandler?Fw(s,t):null;if(r){t.preventDefault(),$y(a)||(t.stopPropagation(),t.stopImmediatePropagation()),nT(s),s.searchOpenHandler?.(e,r),s.suppressClickUntil=Date.now()+250;return}}let n=s.openTargetMouseDown;if(s.openTargetMouseDown=null,!n)return;if(Math.hypot(t.clientX-n.x,t.clientY-n.y)>4){s.suppressClickUntil=Date.now()+250;return}if(m(t))return;t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),nT(s),s.suppressClickUntil=Date.now()+250;let r=s.attachGeneration;_w(s,n.pathTarget).then(t=>{if(_C(s,r)){if(!t){nC(s);return}s.pathOpenHandler?.(e,t),s.suppressClickUntil=Date.now()+250}})};i.addEventListener(`mouseup`,y,!0),s.mouseUpOpenTargetHandler=y;let b=e=>{if(e.pointerType!==`touch`&&h(e,e.pointerId))try{s.hostEl.setPointerCapture(e.pointerId)}catch{}};if(!$y(a)){i.addEventListener(`pointerdown`,b,!0),s.pointerDownSelectionHandler=b;let e=e=>{e.pointerType!==`touch`&&g(e)};window.addEventListener(`pointermove`,e,!0),s.pointerMoveSelectionHandler=e;let t=e=>{if(e.pointerType===`touch`)return;let t=_(e);if(t||m(e),t||Date.now()<s.suppressClickUntil)try{s.hostEl.releasePointerCapture(e.pointerId)}catch{}};window.addEventListener(`pointerup`,t,!0),window.addEventListener(`pointercancel`,t,!0),s.pointerUpSelectionHandler=t;let n=e=>{s.dragSelection||h(e)};i.addEventListener(`mousedown`,n,!0),s.mouseDownSelectionHandler=n;let r=e=>{g(e)};window.addEventListener(`mousemove`,r,!0),s.mouseMoveSelectionHandler=r;let a=e=>{_(e)};window.addEventListener(`mouseup`,a,!0),s.mouseUpSelectionHandler=a}let x=e=>{if(!ae()){if(Date.now()<s.suppressClickUntil){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();return}m(e)||nC(s)}};i.addEventListener(`click`,x,!0),s.clickHandler=x;let S=e=>{if($y(a)||ae())return;let t=uw(s,e);t&&sw(s,t.col,t.row)&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation())};i.addEventListener(`dblclick`,S,!0),s.doubleClickHandler=S;let C=e=>{if(!oC(s,e))return;let t=Lw(s,{includeNativeFallback:!0});t&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),e.clipboardData?.setData(`text/plain`,t))};i.addEventListener(`copy`,C,!0),document.addEventListener(`copy`,C,!0),s.copyHandler=C;let w=e=>{if(!cC(s,e))return;let t=Lw(s,{includeNativeFallback:!0});t&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),Se(t))};document.addEventListener(`keydown`,w,!0),s.copyKeyHandler=w;let T=e=>{dC(s,e)};a.attachCustomKeyEventHandler||(document.addEventListener(`keydown`,T,!0),s.clearKeyHandler=T);let E=e=>{let t=fC(s);if(iS(s.hostEl,e,t)){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();return}aS(s.hostEl,e,t)&&($y(s.terminal)||Qw(s,e.clipboardData?.getData(`text/plain`)||``)&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()))};window.addEventListener(`paste`,E,!0),i.addEventListener(`paste`,E,!0),s.pasteHandler=E;let D=e=>{if(!pC(s)){Uw(s);return}s.lastLinkHoverEvent=e,Ww(s,e)||(s.linkProviderHoverTarget=null,Hw(s,null)),Kw(s),Gw(s,e).then(t=>{!t||s.disposed||s.lastLinkHoverEvent!==e||(s.linkProviderHoverTarget={kind:`path`,text:t.text,...t.pathTarget?{pathTarget:t.pathTarget}:{}},Hw(s,`path`))})};i.addEventListener(`mousemove`,D,!0),s.linkHoverHandler=D;let O=()=>{Uw(s)};i.addEventListener(`mouseleave`,O,!0),s.linkHoverLeaveHandler=O;let k=e=>{if(!pC(s)){Uw(s);return}e.type===`keydown`&&[`Control`,`Meta`].includes(e.key)?s.openModifierActive=!0:s.openModifierActive=pw(e),s.lastLinkHoverEvent&&(![`Control`,`Meta`].includes(e.key)&&!s.openModifierActive||Kw(s,s.openModifierActive))};window.addEventListener(`keydown`,k,!0),window.addEventListener(`keyup`,k,!0),s.linkHoverKeyHandler=k;let A=()=>{Uw(s)};window.addEventListener(`blur`,A),s.linkHoverBlurHandler=A;let j=e=>{e instanceof WheelEvent&&e.deltaY<0&&_x(s,!1,s.hasUnreadOutput),Ew(s),VC(s,{allowClearUnread:!0}),window.setTimeout(()=>VC(s,{allowClearUnread:!0}),80)};i.addEventListener(`wheel`,j,!0),i.addEventListener(`pointerup`,j,!0),s.scrollIntentHandler=j;let M=e=>{hC(s,e)};return a.attachCustomKeyEventHandler?a.attachCustomKeyEventHandler(e=>!(dC(s,e)||hC(s,e))):(document.addEventListener(`keydown`,M,!0),i.addEventListener(`keydown`,M,!0),s.scrollKeyHandler=M),sT(s),s.resizeObserver=new ResizeObserver(()=>{requestAnimationFrame(()=>{if(!s.disposed)try{QC(s)}catch{}})}),s.unsubscribeOutput=t.onSessionOutput(e,(e,t,n,r,i,a,o,c)=>{s.disposed||MC(s,e,t,n,r,i,a,o,c)}),cT(),s}async function uT(e,t){let n=TS.get(e);if(n)return n instanceof Promise?n:Promise.resolve(n);let r=lT(e,t).then(t=>(TS.set(e,t),t)).catch(n=>{throw TS.delete(e),t.onError?.(n instanceof Error?n:Error(String(n))),n});return TS.set(e,r),r}function dT(e,t){if(e.attachReadyGeneration!==t||!_C(e,t)||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.needsReconnectOutputSync||e.replayInProgress||e.liveWriteInProgress||e.replayState.queuedTransitions.length>0||!e.replayState.runtimeEpoch||e.replayState.outputSeq===null||e.replayState.stateRevision===null)return!1;if(e.hostEl.classList.remove(`terminal-checkpoint-installing`),QS(e,`ready`),e.attachReadyNotified)return!0;e.attachReadyNotified=!0;let n=!!(e.parkedViewportState?.following&&hx(e));return e.parkedViewportState=null,n&&_x(e,!0,!1,{allowClearUnread:!0}),e.attachReadyHandler?.(),!0}function fT(e,t){if(_C(e,t)){if(e.pendingSnapshotReplay&&e.snapshotRuntimeEpoch&&e.snapshotOutputSeq!==null&&e.snapshotStateRevision!==null&&e.snapshotCols!==null&&e.snapshotRows!==null&&Date.now()>=e.suppressOutputUntil){vC(e,t);return}dT(e,t)||e.replayInProgress||e.checkpointRequestInFlight||(e.needsReconnectOutputSync=!0,AC(e,t))}}function pT(e,t,n){let r=e.followOutput,i=px(e.terminal),a=fx(e.terminal),o=e.hasUnreadOutput;requestAnimationFrame(()=>{_C(e,n)&&(QC(e,{force:!0}),Vx(e,i,a,r,o),Fx(e),t.autoFocus&&!ae()&&iC(e.hostEl)&&YC(e,n),requestAnimationFrame(()=>{_C(e,n)&&(QC(e,{force:!0}),Vx(e,i,a,r,o),Fx(e),fT(e,n))}))})}function mT(e,t){e.errorHandler=t.onError??null,e.inputDisabled=!!t.inputDisabled,e.followOutputHandler=t.onFollowOutputChange??null,e.pathOpenHandler=t.onPathOpen??null,e.pathResolveHandler=t.onPathResolve??null,e.searchOpenHandler=t.onSearchOpen??null,e.farmingUrlOpenHandler=t.onOpenUrlInFarming??null,e.recoveryStatusHandler=t.onRecoveryStatusChange??null,GC(e,!!t.suppressRendererCursor)}async function hT(e,t){if(t.signal?.aborted)return;let n=await uT(e,t);if(n.disposed||t.signal?.aborted||TS.get(e)!==n)return;if(n.attachedMount===t.mountEl&&fC(n)){mT(n,t);return}let r=$x(n);n.attachReadyHandler=t.onReady??null,n.attachReadyGeneration=r,n.attachReadyNotified=!1,n.recoveryStatusHandler=t.onRecoveryStatusChange??null,QS(n,`requesting`,{attempt:1,restart:!0}),zS(n),wS.resetRecovery(n.replayState),wS.beginRecovery(n.replayState),n.needsReconnectOutputSync=!0,n.bootstrappingSnapshot=!0,n.hostEl.classList.add(`terminal-checkpoint-installing`),LS(n,t.mountEl),n.parkedViewportState&&(n.followOutput=n.parkedViewportState.following,n.hasUnreadOutput=n.hasUnreadOutput||n.parkedViewportState.hasUnreadOutput,n.preserveUnreadOutputUntilJump=n.preserveUnreadOutputUntilJump||n.parkedViewportState.preserveUnreadOutputUntilJump),iT(n),mT(n,t),yC(n,t.bootstrapState),gx(n),pT(n,t,r)}async function gT(e,t){let n=TS.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed||!r.bootstrappingSnapshot&&!r.needsReconnectOutputSync)return!1;zS(r);let i=yC(r,t);return!i&&!r.pendingSnapshotReplay?!1:(fC(r)&&requestAnimationFrame(()=>{!r.disposed&&r.pendingSnapshotReplay&&vC(r,r.attachGeneration)}),i)}async function _T(e,t){let n=TS.get(e);if(!n)return!1;let r=n instanceof Promise?await n:n;return r.disposed||TS.get(e)!==r?!1:(r.inputDisabled=t.inputDisabled,r.farmingUrlOpenHandler=t.onOpenUrlInFarming??null,GC(r,t.suppressRendererCursor),!0)}async function vT(e,t){let n=TS.get(e);if(!n)return;let r=await n;r.disposed||TS.get(e)===r&&tS(r,t)&&qS(r)}function yT(e,t){let n=TS.get(e);return!n||n instanceof Promise?!1:ZC(n,t)}async function bT(e){let t=TS.get(e);if(!t)return``;let n=await t;return n.disposed?``:(n.cachedSelection=cx(n.terminal),n.cachedSelection&&(n.lastNonEmptySelection=lx(n.cachedSelection)),n.cachedSelection)}function xT(e){let t=TS.get(e);return!t||t instanceof Promise||t.disposed?``:(t.cachedSelection=cx(t.terminal),t.cachedSelection&&(t.lastNonEmptySelection=lx(t.cachedSelection)),t.cachedSelection)}function ST(e){let t=TS.get(e);return!t||t instanceof Promise||t.disposed||!t.replayState.runtimeEpoch||t.replayState.outputSeq===null?null:{runtimeEpoch:t.replayState.runtimeEpoch,outputSeq:t.replayState.outputSeq}}async function CT(e){let t=TS.get(e);if(!t)return;TS.delete(e);let n=await t;n.disposed||(n.disposed=!0,zS(n),GS(n),BC(n),Gx(n),n.unsubscribeOutput?.(),n.rendererFailureDisposable?.(),n.selectionChangeDisposable?.(),n.scrollChangeDisposable?.(),n.backendConnectedHandler&&window.removeEventListener(`farming:backend-connected`,n.backendConnectedHandler),n.pageLifecycleHandler&&(document.removeEventListener(`visibilitychange`,n.pageLifecycleHandler),window.removeEventListener(`pagehide`,n.pageLifecycleHandler),window.removeEventListener(`pageshow`,n.pageLifecycleHandler)),n.imeOverlayDisposables.forEach(e=>e()),n.resizeObserver?.disconnect(),n.followCheckFrame!==null&&cancelAnimationFrame(n.followCheckFrame),n.clickHandler&&n.hostEl.removeEventListener(`click`,n.clickHandler,!0),n.pointerDownSelectionHandler&&n.hostEl.removeEventListener(`pointerdown`,n.pointerDownSelectionHandler,!0),n.pointerMoveSelectionHandler&&window.removeEventListener(`pointermove`,n.pointerMoveSelectionHandler,!0),n.pointerUpSelectionHandler&&(window.removeEventListener(`pointerup`,n.pointerUpSelectionHandler,!0),window.removeEventListener(`pointercancel`,n.pointerUpSelectionHandler,!0)),n.mouseDownOpenTargetHandler&&n.hostEl.removeEventListener(`mousedown`,n.mouseDownOpenTargetHandler,!0),n.mouseDownSelectionHandler&&n.hostEl.removeEventListener(`mousedown`,n.mouseDownSelectionHandler,!0),n.mouseMoveSelectionHandler&&window.removeEventListener(`mousemove`,n.mouseMoveSelectionHandler,!0),n.mouseUpSelectionHandler&&window.removeEventListener(`mouseup`,n.mouseUpSelectionHandler,!0),n.mouseUpOpenTargetHandler&&n.hostEl.removeEventListener(`mouseup`,n.mouseUpOpenTargetHandler,!0),n.doubleClickHandler&&n.hostEl.removeEventListener(`dblclick`,n.doubleClickHandler,!0),n.copyHandler&&(n.hostEl.removeEventListener(`copy`,n.copyHandler,!0),document.removeEventListener(`copy`,n.copyHandler,!0)),n.copyKeyHandler&&document.removeEventListener(`keydown`,n.copyKeyHandler,!0),n.clearKeyHandler&&document.removeEventListener(`keydown`,n.clearKeyHandler,!0),n.pasteHandler&&(window.removeEventListener(`paste`,n.pasteHandler,!0),n.hostEl.removeEventListener(`paste`,n.pasteHandler,!0)),n.linkHoverHandler&&n.hostEl.removeEventListener(`mousemove`,n.linkHoverHandler,!0),n.linkHoverLeaveHandler&&n.hostEl.removeEventListener(`mouseleave`,n.linkHoverLeaveHandler,!0),n.linkHoverKeyHandler&&(window.removeEventListener(`keydown`,n.linkHoverKeyHandler,!0),window.removeEventListener(`keyup`,n.linkHoverKeyHandler,!0)),n.linkHoverBlurHandler&&window.removeEventListener(`blur`,n.linkHoverBlurHandler),n.linkProviderDisposable?.(),n.contextMenuHandler&&(n.hostEl.removeEventListener(`contextmenu`,n.contextMenuHandler,!0),window.removeEventListener(`contextmenu`,n.contextMenuHandler,!0)),n.contextMenuMouseDownHandler&&(n.hostEl.removeEventListener(`mousedown`,n.contextMenuMouseDownHandler,!0),window.removeEventListener(`mousedown`,n.contextMenuMouseDownHandler,!0)),qw(n),n.scrollIntentHandler&&(n.hostEl.removeEventListener(`wheel`,n.scrollIntentHandler,!0),n.hostEl.removeEventListener(`pointerup`,n.scrollIntentHandler,!0)),n.scrollKeyHandler&&(document.removeEventListener(`keydown`,n.scrollKeyHandler,!0),n.hostEl.removeEventListener(`keydown`,n.scrollKeyHandler,!0)),n.touchInteraction&&(n.touchInteraction.stopTouchMomentum(),n.hostEl.removeEventListener(`pointerdown`,n.touchInteraction.pointerDownHandler,!0),n.hostEl.removeEventListener(`pointermove`,n.touchInteraction.pointerMoveHandler,!0),n.hostEl.removeEventListener(`pointerup`,n.touchInteraction.pointerUpHandler,!0),n.hostEl.removeEventListener(`pointercancel`,n.touchInteraction.pointerUpHandler,!0),n.hostEl.removeEventListener(`lostpointercapture`,n.touchInteraction.pointerUpHandler,!0)),n.originalRender&&n.terminal.renderer&&(n.terminal.renderer.render=n.originalRender),n.terminal.dispose(),n.hostEl.remove())}async function wT(e){let t=new Set(e),n=[...TS.keys()].filter(e=>!t.has(e));await Promise.all(n.map(e=>CT(e)))}function TT(e){let t=TS.get(e);if(!t)return Promise.resolve(!1);if(typeof t.then!=`function`){let e=t;return Promise.resolve(nC(e))}return t.then(e=>nC(e))}async function ET(e,t={}){let n=TS.get(e);if(!n)return!1;let r=await n;if(r.disposed||!fC(r))return!1;let i=r.followOutput,a=px(r.terminal),o=fx(r.terminal),s=r.hasUnreadOutput,c=()=>{r.disposed||!fC(r)||(QC(r,{force:!0}),Vx(r,a,o,i,s),Fx(r),t.autoFocus&&!ae()&&iC(r.hostEl)&&YC(r,r.attachGeneration))};return requestAnimationFrame(()=>{c(),requestAnimationFrame(c)}),!0}function DT(e){let t=Nt(e,de());TS.forEach(e=>{e instanceof Promise||e.disposed||e.hostEl.dataset.terminalFontSize!==String(t)&&(e.hostEl.dataset.terminalFontSize=String(t),e.terminal.options&&(e.terminal.options.fontSize=t),gC(e.hostEl,e.terminal),fC(e)&&requestAnimationFrame(()=>{e.disposed||!fC(e)||(QC(e,{force:!0}),Fx(e),requestAnimationFrame(()=>{e.disposed||!fC(e)||(QC(e,{force:!0}),Fx(e))}))}))})}async function OT(e){let t=TS.get(e);if(!t)return;let n=await t;n.disposed||(n.touchInteraction?.stopTouchMomentum(),Rx(n,{allowClearUnread:!0}))}async function kT(e,t,n=`next`,r={}){let i=TS.get(e);if(!i)return{found:!1,resultIndex:0,resultCount:0};let a=await i;return a.disposed||typeof a.terminal.search!=`function`?{found:!1,resultIndex:0,resultCount:0}:a.terminal.search(t,n,r)}async function AT(e){let t=TS.get(e);if(!t)return;let n=await t;n.disposed||n.terminal.clearSearch?.()}function jT(e){let t=new URL(r(`/api/browsers/${encodeURIComponent(e.id)}/viewer`),window.location.href);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.href}function MT(e){let t=e===`zh`;return{close:t?`隐藏浏览器预览`:`Hide browser preview`,open:t?`打开完整浏览器`:`Open full browser`,waiting:t?`正在连接浏览器画面…`:`Connecting to browser…`}}function NT({resource:e,language:t,onOpen:n,onDismiss:r}){let i=MT(t),[a,o]=(0,G.useState)(``);return(0,G.useEffect)(()=>{if(e.status!==`running`){o(``);return}let t=!1,n=0,r=null,i=()=>{t||(r=new WebSocket(jT(e)),r.onmessage=e=>{let t=JSON.parse(String(e.data));t.type!==`browser-frame`||!t.data||o(`data:image/${t.format===`png`?`png`:`jpeg`};base64,${t.data}`)},r.onclose=()=>{t||(n=window.setTimeout(i,1e3))})};return i(),()=>{t=!0,window.clearTimeout(n),r?.close()}},[e.generation,e.id,e.status]),(0,K.jsxs)(`aside`,{className:`farming-browser-activity-preview`,"data-testid":`farming-browser-activity-preview`,"aria-label":i.open,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`span`,{className:`farming-browser-activity-dot`,"aria-hidden":`true`}),(0,K.jsx)(`strong`,{title:e.title||e.name,children:e.title||e.name}),(0,K.jsx)(`button`,{type:`button`,"aria-label":i.close,title:i.close,onClick:r,children:`×`})]}),(0,K.jsx)(`button`,{type:`button`,className:`farming-browser-activity-frame`,"aria-label":i.open,title:i.open,onClick:n,children:a?(0,K.jsx)(`img`,{src:a,alt:``,draggable:!1}):(0,K.jsx)(`span`,{children:i.waiting})})]})}function PT(e){let t=new URL(r(`/api/browsers/${encodeURIComponent(e.id)}/viewer`),window.location.href);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.href}function FT(e){let t=e===`zh`;return{back:t?`后退`:`Back`,backToAgent:t?`返回 Agent`:`Back to Agent`,forward:t?`前进`:`Forward`,reload:t?`重新加载`:`Reload`,address:t?`浏览器地址`:`Browser address`,connected:t?`Viewer 已连接`:`Viewer connected`,disconnected:t?`Viewer 未连接`:`Viewer disconnected`,copyLink:t?`复制链接`:`Copy link`,more:t?`更多`:`More`,start:t?`启动`:`Start`,stop:t?`停止`:`Stop`,startBrowser:t?`启动标签页`:`Start Tab`,stoppedTitle:t?`标签页已停止`:`Tab stopped`,failedTitle:t?`标签页失败`:`Tab failed`,stoppedHint:t?`启动后,用户和 Agent 将操作同一个标签页。`:`Start it to share one tab between the user and Agent.`,pageLabel:e=>t?`${e} 浏览器页面`:`${e} browser page`,textInput:t?`浏览器文本输入`:`Browser text input`,viewerFailed:t?`Browser Viewer 失败`:`Browser Viewer failed`,connectionFailed:t?`Browser Viewer 连接失败`:`Browser Viewer connection failed`,navigationFailed:t?`导航失败`:`Navigation failed`,transitionFailed:t?`浏览器状态切换失败`:`Browser transition failed`}}function IT(){return(0,K.jsx)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M12.8 3.8V1.5a.5.5 0 0 1 1 0v3.6a.5.5 0 0 1-.5.5H9.7a.5.5 0 0 1 0-1h2.36A5.5 5.5 0 1 0 13.5 8a.5.5 0 0 1 1 0 6.5 6.5 0 1 1-1.7-4.2Z`})})}function LT(){return(0,K.jsx)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M4.5 2.6a.75.75 0 0 1 1.15-.63l7 4.9a.75.75 0 0 1 0 1.23l-7 4.9A.75.75 0 0 1 4.5 12.4V2.6Z`})})}function RT(){return(0,K.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:[(0,K.jsx)(`circle`,{cx:`3`,cy:`8`,r:`1.1`}),(0,K.jsx)(`circle`,{cx:`8`,cy:`8`,r:`1.1`}),(0,K.jsx)(`circle`,{cx:`13`,cy:`8`,r:`1.1`})]})}function zT({resource:e,controller:t,language:n,onResource:i,onOpenResource:a,onBackToAgent:o}){let s=FT(n),c=(0,G.useRef)(null),l=(0,G.useRef)(null),u=(0,G.useRef)(null),d=(0,G.useRef)(!1),f=(0,G.useRef)(null),p=(0,G.useRef)(!1),m=(0,G.useRef)(null),h=(0,G.useRef)(null),g=(0,G.useRef)(null),_=(0,G.useRef)(0),v=(0,G.useRef)(null),y=(0,G.useRef)(null),b=(0,G.useRef)(null),[x,S]=(0,G.useState)(e.url),[C,w]=(0,G.useState)(!1),[T,E]=(0,G.useState)(!1),[D,O]=(0,G.useState)(``),[k,A]=(0,G.useState)(!1);(0,G.useEffect)(()=>{d.current||S(e.url)},[e.url]),(0,G.useEffect)(()=>{if(!k)return;let e=e=>{e.target instanceof Node&&(g.current?.contains(e.target)||h.current?.contains(e.target))||A(!1)},t=e=>{e.key===`Escape`&&(e.preventDefault(),A(!1),h.current?.focus())};return window.addEventListener(`pointerdown`,e,!0),window.addEventListener(`keydown`,t,!0),()=>{window.removeEventListener(`pointerdown`,e,!0),window.removeEventListener(`keydown`,t,!0)}},[k]);let j=(0,G.useCallback)((t=m.current,n=!1)=>{let r=c.current;if(!r||!t||t.readyState!==WebSocket.OPEN)return;let i=Math.round(r.clientWidth),a=Math.round(r.clientHeight);i<=0||a<=0||t.send(JSON.stringify({type:`resize`,generation:e.generation,width:i,height:a,deviceScaleFactor:Math.max(1,Math.min(2,window.devicePixelRatio||1)),claim:n}))},[e.generation]);(0,G.useEffect)(()=>{let e=c.current;if(!e)return;let t=new ResizeObserver(()=>{y.current!==null&&window.cancelAnimationFrame(y.current),y.current=window.requestAnimationFrame(()=>{y.current=null,j()})});return t.observe(e),()=>{t.disconnect(),y.current!==null&&window.cancelAnimationFrame(y.current),y.current=null}},[j]),(0,G.useEffect)(()=>{let e=()=>{document.visibilityState===`visible`&&document.hasFocus()&&j(void 0,!0)};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[j]),(0,G.useEffect)(()=>{if(e.status!==`running`){w(!1),m.current?.close(),m.current=null;return}let t=!1,n=0,r=()=>{if(t)return;let o=new WebSocket(PT(e));m.current=o,o.onopen=()=>{w(!0),O(``),j(o,document.visibilityState===`visible`&&document.hasFocus())},o.onmessage=e=>{let t=JSON.parse(String(e.data));if(t.type===`browser-tab-opened`&&t.resource){i(t.resource),a(t.resource);return}if(t.type===`browser-state`&&t.resource){i(t.resource);return}if(t.type===`browser-error`){O(t.message||s.viewerFailed);return}if(t.type!==`browser-frame`||!t.data)return;let n=++_.current,r=new Image;r.onload=()=>{n===_.current&&(v.current!==null&&window.cancelAnimationFrame(v.current),v.current=window.requestAnimationFrame(()=>{if(v.current=null,n!==_.current)return;let e=l.current,i=e?.getContext(`2d`);if(!e||!i)return;let a=t.viewport&&Number.isFinite(t.viewport.width)&&Number.isFinite(t.viewport.height)?t.viewport:{width:r.naturalWidth,height:r.naturalHeight};b.current=a,e.width=r.naturalWidth,e.height=r.naturalHeight,e.style.width=`${a.width}px`,e.style.height=`${a.height}px`,i.drawImage(r,0,0)}))},r.src=`data:image/${t.format===`png`?`png`:`jpeg`};base64,${t.data}`},o.onclose=()=>{m.current===o&&(m.current=null),w(!1),t||(n=window.setTimeout(r,1e3))},o.onerror=()=>O(s.connectionFailed)};return r(),()=>{t=!0,window.clearTimeout(n),v.current!==null&&window.cancelAnimationFrame(v.current),v.current=null,m.current?.close(),m.current=null}},[s.connectionFailed,s.viewerFailed,a,i,e.id,e.status,j]);let M=(0,G.useCallback)(t=>{let n=m.current;!n||n.readyState!==WebSocket.OPEN||n.send(JSON.stringify({...t,generation:e.generation}))},[e.generation]),N=e=>{let t=e.currentTarget,n=t.getBoundingClientRect(),r=b.current;return{x:(e.clientX-n.left)*(r?.width||t.width)/Math.max(1,n.width),y:(e.clientY-n.top)*(r?.height||t.height)/Math.max(1,n.height)}},P=async()=>{let n=(u.current?.value??x).trim();E(!0),O(``);try{(e.status===`stopped`||e.status===`failed`)&&i(await t.start(e.id));let a=await fetch(r(`/api/browsers/${encodeURIComponent(e.id)}/navigate`),{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({url:n})}),o=await a.json();if(!a.ok)throw Error(o.error||s.navigationFailed);d.current=!1,S(o.url),O(``),i(o)}catch(e){O(e instanceof Error?e.message:s.navigationFailed)}finally{E(!1)}},F=async t=>{E(!0),O(``);try{let n=await fetch(r(`/api/browsers/${encodeURIComponent(e.id)}/action`),{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({kind:t})}),a=await n.json();if(!n.ok)throw Error(a.error||`Browser ${t} failed`);O(``),i(a)}catch(e){O(e instanceof Error?e.message:`Browser ${t} failed`)}finally{E(!1)}};return(0,K.jsxs)(`section`,{className:`farming-browser-viewer`,"data-testid":`farming-browser-viewer`,children:[(0,K.jsxs)(`header`,{className:`farming-browser-toolbar`,children:[(0,K.jsx)(`button`,{type:`button`,className:`farming-browser-toolbar-icon farming-browser-agent-return`,"aria-label":s.backToAgent,title:s.backToAgent,onClick:o,children:(0,K.jsx)(Xe,{})}),(0,K.jsx)(`span`,{className:`farming-browser-toolbar-separator`,"aria-hidden":`true`}),(0,K.jsx)(`button`,{type:`button`,className:`farming-browser-toolbar-icon`,"aria-label":s.back,title:s.back,disabled:e.status!==`running`,onClick:()=>void F(`back`),children:(0,K.jsx)(nt,{})}),(0,K.jsx)(`button`,{type:`button`,className:`farming-browser-toolbar-icon`,"aria-label":s.forward,title:s.forward,disabled:e.status!==`running`,onClick:()=>void F(`forward`),children:(0,K.jsx)(ut,{})}),(0,K.jsx)(`button`,{type:`button`,className:`farming-browser-toolbar-icon`,"aria-label":s.reload,title:s.reload,disabled:e.status!==`running`,onClick:()=>void F(`reload`),children:(0,K.jsx)(IT,{})}),(0,K.jsxs)(`form`,{"aria-busy":T,onSubmit:e=>{e.preventDefault(),P()},children:[(0,K.jsx)(`input`,{ref:u,value:x,"aria-label":s.address,disabled:e.status===`starting`||e.status===`stopping`,onChange:e=>{d.current=!0,S(e.currentTarget.value)},onKeyDown:e=>{e.key!==`Enter`||e.nativeEvent.isComposing||(e.preventDefault(),P())},onBlur:()=>{d.current=!1,S(e.url)}}),(0,K.jsx)(`span`,{className:`farming-browser-connection ${C?`connected`:``} ${T?`navigating`:``}`,title:C?s.connected:s.disconnected})]}),(0,K.jsxs)(`div`,{className:`farming-browser-more-wrap`,children:[(0,K.jsx)(`button`,{ref:h,type:`button`,className:`farming-browser-toolbar-icon`,"aria-label":s.more,title:s.more,"aria-haspopup":`menu`,"aria-expanded":k,onClick:()=>A(e=>!e),children:(0,K.jsx)(RT,{})}),k?(0,K.jsxs)(`div`,{ref:g,className:`farming-browser-more-menu`,role:`menu`,children:[(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{A(!1);let t=new URL(window.location.href);t.searchParams.set(`browser`,e.id),navigator.clipboard.writeText(t.href)},children:[(0,K.jsx)(ft,{}),(0,K.jsx)(`span`,{children:s.copyLink})]}),(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,disabled:e.status===`starting`||e.status===`stopping`,onClick:()=>{A(!1),(e.status===`running`?t.stop(e.id):t.start(e.id)).catch(e=>O(e instanceof Error?e.message:s.transitionFailed))},children:[e.status===`running`?(0,K.jsx)(je,{}):(0,K.jsx)(LT,{}),(0,K.jsx)(`span`,{children:e.status===`running`?s.stop:s.start})]})]}):null]})]}),(0,K.jsxs)(`div`,{ref:c,className:`farming-browser-viewport`,children:[e.status===`running`?(0,K.jsx)(`canvas`,{ref:l,tabIndex:0,"aria-label":s.pageLabel(e.name),onPointerMove:e=>{M({type:`pointer`,action:`move`,...N(e)})},onPointerDown:e=>{e.currentTarget.focus(),e.currentTarget.setPointerCapture(e.pointerId);let t=N(e);M({type:`pointer`,action:`down`,button:e.button===2?`right`:e.button===1?`middle`:`left`,...t}),window.requestAnimationFrame(()=>f.current?.focus({preventScroll:!0}))},onPointerUp:e=>{let t=N(e);M({type:`pointer`,action:`up`,button:e.button===2?`right`:e.button===1?`middle`:`left`,...t})},onContextMenu:e=>e.preventDefault(),onWheel:e=>{e.preventDefault();let t=N(e);M({type:`wheel`,deltaX:e.deltaX,deltaY:e.deltaY,...t})},onKeyDown:e=>{e.preventDefault();let t=!!e.altKey|(e.ctrlKey?2:0)|(e.metaKey?4:0)|(e.shiftKey?8:0);e.key.length===1&&!(t&-9)?M({type:`text`,text:e.key}):M({type:`key`,key:e.key,code:e.code,modifiers:t})},onPaste:e=>{let t=e.clipboardData.getData(`text/plain`);t&&(e.preventDefault(),M({type:`text`,text:t}))}}):(0,K.jsxs)(`div`,{className:`farming-browser-placeholder`,children:[(0,K.jsx)(`strong`,{children:e.status===`failed`?s.failedTitle:s.stoppedTitle}),(0,K.jsx)(`p`,{children:e.error||s.stoppedHint}),(0,K.jsxs)(`button`,{type:`button`,onClick:()=>void t.start(e.id).catch(e=>O(e.message)),children:[(0,K.jsx)(LT,{}),(0,K.jsx)(`span`,{children:s.startBrowser})]})]}),(0,K.jsx)(`textarea`,{ref:f,className:`farming-browser-text-input-proxy`,"aria-label":s.textInput,autoCapitalize:`none`,autoCorrect:`off`,spellCheck:!1,onCompositionStart:()=>{p.current=!0},onCompositionEnd:e=>{p.current=!1;let t=e.currentTarget.value;t&&M({type:`text`,text:t}),e.currentTarget.value=``},onInput:e=>{if(p.current)return;let t=e.currentTarget.value;t&&M({type:`text`,text:t}),e.currentTarget.value=``},onKeyDown:e=>{p.current||[`Backspace`,`Delete`,`Enter`,`Tab`,`Escape`,`ArrowLeft`,`ArrowUp`,`ArrowRight`,`ArrowDown`].includes(e.key)&&(e.preventDefault(),M({type:`key`,key:e.key,code:e.code}))}})]}),D&&(0,K.jsx)(`div`,{className:`farming-browser-viewer-error`,role:`alert`,children:D})]})}function BT(e){let t=e===`zh`;return{back:t?`返回 Agent`:`Back to Agent`,takeControl:t?`接管`:`Take control`,returnControl:t?`交还 Agent`:`Return to Agent`,stop:t?`停止`:`Stop`,start:t?`启动桌面`:`Start Desktop`,agentControls:t?`Agent 正在控制;当前为只读观察。`:`The Agent controls this Desktop; the Viewer is read-only.`,humanControls:t?`你正在控制这个桌面。`:`You control this Desktop.`,stopped:t?`桌面已停止`:`Desktop stopped`,failed:t?`桌面启动失败`:`Desktop failed`,viewerFailed:t?`桌面 Viewer 加载失败`:`Desktop Viewer failed`}}async function VT(e){let t=await fetch(r(`/api/computers/${encodeURIComponent(e.id)}/viewer-config`),{headers:{Accept:`application/json`}}),n=await t.json().catch(()=>({}));if(!t.ok)throw Error(n.error||`Desktop Viewer failed (${t.status})`);return n}function HT(e,t){let n=r(`/api/computers/${encodeURIComponent(e.id)}/viewer-websocket`).replace(/^\/+/,``),i=new URL(r(`/api/computers/${encodeURIComponent(e.id)}/viewer/vnc.html`),window.location.href);return i.searchParams.set(`autoconnect`,`1`),i.searchParams.set(`resize`,`scale`),i.searchParams.set(`shared`,`1`),i.searchParams.set(`view_only`,t.viewOnly?`1`:`0`),i.searchParams.set(`password`,t.password),i.searchParams.set(`path`,n),i.href}function UT({resource:e,controller:t,language:n,onBackToAgent:r}){let i=BT(n),[a,o]=(0,G.useState)(null),[s,c]=(0,G.useState)(``),[l,u]=(0,G.useState)(!1),d=l||e.status===`starting`||e.status===`stopping`;(0,G.useEffect)(()=>{if(e.status!==`running`){o(null),c(``);return}let t=!0;return VT(e).then(e=>{t&&(o(e),c(``))}).catch(e=>{t&&c(e instanceof Error?e.message:i.viewerFailed)}),()=>{t=!1}},[i.viewerFailed,e.controlEpoch,e.generation,e.id,e.status]);let f=(0,G.useMemo)(()=>a?HT(e,a):``,[a,e]),p=async()=>{u(!0),c(``);try{await t.takeControl(e.id,e.controlOwner===`human`?`agent`:`human`)}catch(e){c(e instanceof Error?e.message:i.viewerFailed)}finally{u(!1)}},m=async n=>{u(!0),c(``);try{n===`start`?await t.start(e.id):await t.stop(e.id)}catch(e){c(e instanceof Error?e.message:i.viewerFailed)}finally{u(!1)}};return(0,K.jsxs)(`section`,{className:`farming-computer-viewer`,"data-testid":`farming-computer-viewer`,children:[(0,K.jsxs)(`header`,{className:`farming-computer-toolbar`,children:[(0,K.jsx)(`button`,{type:`button`,title:i.back,"aria-label":i.back,onClick:r,children:(0,K.jsx)(Xe,{})}),(0,K.jsx)(`span`,{className:`farming-computer-toolbar-title`,children:e.name}),e.status===`running`&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{className:`farming-computer-control-status ${e.controlOwner}`,children:e.controlOwner===`human`?i.humanControls:i.agentControls}),(0,K.jsx)(`button`,{type:`button`,className:`farming-computer-control-button`,disabled:d,onClick:()=>void p(),children:e.controlOwner===`human`?i.returnControl:i.takeControl}),(0,K.jsx)(`button`,{type:`button`,title:i.stop,"aria-label":i.stop,disabled:d,onClick:()=>void m(`stop`),children:(0,K.jsx)(je,{})})]})]}),(0,K.jsxs)(`div`,{className:`farming-computer-viewport`,children:[e.status===`running`&&f?(0,K.jsx)(`iframe`,{src:f,title:e.name,allow:`clipboard-read; clipboard-write`},`${e.generation}:${e.controlEpoch}`):e.status===`failed`?(0,K.jsxs)(`div`,{className:`farming-computer-empty-state`,children:[(0,K.jsx)(`strong`,{children:i.failed}),(0,K.jsx)(`span`,{children:e.error}),(0,K.jsx)(`button`,{type:`button`,disabled:d,onClick:()=>void m(`start`),children:i.start})]}):(0,K.jsxs)(`div`,{className:`farming-computer-empty-state`,children:[(0,K.jsx)(`strong`,{children:i.stopped}),(0,K.jsx)(`button`,{type:`button`,disabled:d,onClick:()=>void m(`start`),children:i.start})]}),s&&(0,K.jsx)(`div`,{className:`farming-computer-error`,children:s})]})]})}function WT({agentId:e,containerRef:t,onSessionOutput:n,suppressRendererCursor:r=!1,inputDisabled:i=!1,onFollowOutputChange:a,onPathOpen:o,onPathResolve:s,onSearchOpen:c,onOpenUrlInFarming:l,onRecoveryStatusChange:u,onReady:d,onError:f,bootstrapState:p}){let m=(0,G.useRef)({onSessionOutput:n,onFollowOutputChange:a,onPathOpen:o,onPathResolve:s,onSearchOpen:c,onOpenUrlInFarming:l,onRecoveryStatusChange:u,onReady:d,onError:f,bootstrapState:p});m.current={onSessionOutput:n,onFollowOutputChange:a,onPathOpen:o,onPathResolve:s,onSearchOpen:c,onOpenUrlInFarming:l,onRecoveryStatusChange:u,onReady:d,onError:f,bootstrapState:p};let h=(0,G.useRef)(null);h.current||={onSessionOutput:(e,t)=>m.current.onSessionOutput(e,t),onFollowOutputChange:e=>{m.current.onFollowOutputChange?.(e)},onPathOpen:(e,t)=>{m.current.onPathOpen?.(e,t)},onPathResolve:(e,t)=>m.current.onPathResolve?.(e,t)??null,onSearchOpen:(e,t)=>{m.current.onSearchOpen?.(e,t)},onOpenUrlInFarming:(e,t)=>{m.current.onOpenUrlInFarming?.(e,t)},onRecoveryStatusChange:e=>{m.current.onRecoveryStatusChange?.(e)},onReady:()=>{m.current.onReady?.()},onError:e=>{m.current.onError?.(e)}};let g=h.current,_=!!l,v=(0,G.useRef)({inputDisabled:i,suppressRendererCursor:r,farmingUrlOpenEnabled:_});v.current={inputDisabled:i,suppressRendererCursor:r,farmingUrlOpenEnabled:_};let y=(0,G.useRef)(null);y.current||=Yx();let b=y.current;return(0,G.useEffect)(()=>{if(!e||!t.current)return;let n=t.current,r=b.acquire(e,n,()=>{let t=new AbortController;return n.replaceChildren(),hT(e,{mountEl:n,onSessionOutput:g.onSessionOutput,suppressRendererCursor:v.current.suppressRendererCursor,inputDisabled:v.current.inputDisabled,onFollowOutputChange:g.onFollowOutputChange,onPathOpen:g.onPathOpen,onPathResolve:g.onPathResolve,onSearchOpen:g.onSearchOpen,onOpenUrlInFarming:v.current.farmingUrlOpenEnabled?g.onOpenUrlInFarming:void 0,onRecoveryStatusChange:g.onRecoveryStatusChange,onError:g.onError,bootstrapState:m.current.bootstrapState,signal:t.signal,onReady:g.onReady}).catch(e=>{t.signal.aborted||(console.error(`Failed to attach terminal session:`,e),g.onError(e instanceof Error?e:Error(String(e))))}),()=>{t.abort(),vT(e,n).catch(e=>{console.error(`Failed to detach terminal session:`,e)})}});return()=>{r.release()}},[e,g,b,t]),(0,G.useEffect)(()=>{e&&_T(e,{inputDisabled:i,suppressRendererCursor:r,onOpenUrlInFarming:_?g.onOpenUrlInFarming:void 0}).catch(e=>{console.error(`Failed to update terminal live options:`,e)})},[e,g,_,i,r]),(0,G.useEffect)(()=>{!e||!p?.runtimeEpoch||p.stateRevision===null||gT(e,p).catch(e=>{console.error(`Failed to apply terminal bootstrap state:`,e)})},[e,p?.runtimeEpoch,p?.outputSeq,p?.stateRevision,p?.output,p?.cols,p?.rows]),{focus:(0,G.useCallback)(()=>{let n=t.current;!e||!n||TT(e).then(t=>{if(!t)return hT(e,{mountEl:n,onSessionOutput:g.onSessionOutput,autoFocus:!0,suppressRendererCursor:v.current.suppressRendererCursor,inputDisabled:v.current.inputDisabled,onFollowOutputChange:g.onFollowOutputChange,onPathOpen:g.onPathOpen,onPathResolve:g.onPathResolve,onSearchOpen:g.onSearchOpen,onOpenUrlInFarming:v.current.farmingUrlOpenEnabled?g.onOpenUrlInFarming:void 0,onRecoveryStatusChange:g.onRecoveryStatusChange,onError:g.onError,bootstrapState:m.current.bootstrapState,onReady:g.onReady})}).catch(e=>{console.error(`Failed to focus terminal session:`,e),g.onError(e instanceof Error?e:Error(String(e)))})},[e,g,t]),refreshLayout:(0,G.useCallback)((t={})=>{e&&ET(e,t).catch(e=>{console.error(`Failed to refresh terminal layout:`,e)})},[e]),getSelection:(0,G.useCallback)(async()=>e?bT(e):``,[e]),getSelectionNow:(0,G.useCallback)(()=>e?xT(e):``,[e]),getReadCutNow:(0,G.useCallback)(()=>e?ST(e):null,[e]),scrollToBottom:(0,G.useCallback)(()=>{e&&OT(e).catch(e=>{console.error(`Failed to scroll terminal session to bottom:`,e)})},[e]),search:(0,G.useCallback)((t,n=`next`,r)=>e?kT(e,t,n,r):Promise.resolve({found:!1,resultIndex:0,resultCount:0}),[e]),clearSearch:(0,G.useCallback)(()=>e?AT(e):Promise.resolve(),[e])}}var GT=500;function KT(e){let t=String(e||``).trim().split(/\s+/)[0]||``;return[`claude`,`codex`,`qwen`,`opencode`,`qodercli`,`aider`,`github-copilot-cli`,`amazon-q`].includes(t)}function qT(e){return(e.metaKey&&!e.ctrlKey||e.ctrlKey&&!e.metaKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`}function JT(e){return e.key===`F3`&&!e.metaKey&&!e.ctrlKey&&!e.altKey}function YT(e){if(!e.altKey||e.metaKey||e.ctrlKey||e.shiftKey)return null;let t=e.code||`Key${e.key.toUpperCase()}`;return t===`KeyC`?`caseSensitive`:t===`KeyW`?`wholeWord`:t===`KeyR`?`regex`:null}function XT(e,t){return!(e instanceof Node)||t?.contains(e)?!0:e===document.body||e===document.documentElement}function ZT(e,t,n){return!e.trim()||!t?``:t.found?typeof t.resultCount==`number`&&t.resultCount>0&&typeof t.resultIndex==`number`&&t.resultIndex>=0?n.terminalSearchResults(t.resultIndex+1,t.resultCount):``:n.terminalSearchNoResults}function QT(e){let t=e.replace(/\r/g,``).trim();if(!t)return``;let n=t.split(`
156
+ `).map(e=>e.trim()).filter(Boolean);if(n.length!==1)return``;let r=n[0];return r?r.slice(0,240):``}function $T(e){return`code-terminal-search-button option${e?` active`:``}`}function eE(){return{phase:`requesting`,attempt:1,startedAt:Date.now(),retryDelayMs:null}}function tE({agent:e,active:t,focusSignal:n,onActivate:r,onSessionOutput:i,onOpenPath:a,onResolvePath:o,onSearchWord:s,onOpenUrlInFarming:c,onFollowOutputChange:l,onReadLatest:u,copy:d}){let f=(0,G.useRef)(null),p=(0,G.useRef)(null),m=(0,G.useRef)(null),[h,g]=(0,G.useState)({following:!0,hasUnreadOutput:!1}),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(!1),[x,S]=(0,G.useState)(``),[C,w]=(0,G.useState)({}),[T,E]=(0,G.useState)(null),[D,O]=(0,G.useState)(null),[k,A]=(0,G.useState)(eE),[j,M]=(0,G.useState)(!1),[N,P]=(0,G.useState)(Date.now),F=(0,G.useCallback)(t=>{v(!0),g(t),l?.(e.id,t)},[e.id,l]),ee=(0,G.useCallback)(()=>{O(null)},[]),I=(0,G.useCallback)(e=>{O(e.message||d.terminalSessionUnavailable)},[d.terminalSessionUnavailable]),L=(0,G.useCallback)(e=>{A(e),P(Date.now())},[]),{focus:te,refreshLayout:R,getSelectionNow:ne,getReadCutNow:re,scrollToBottom:z,search:ie,clearSearch:B}=WT({agentId:e.id,containerRef:p,onSessionOutput:i,inputDisabled:!1,suppressRendererCursor:KT(e.command),onFollowOutputChange:F,onPathOpen:a,onPathResolve:o,onSearchOpen:s,onOpenUrlInFarming:c,onRecoveryStatusChange:L,onReady:ee,onError:I});(0,G.useEffect)(()=>{if(k.phase===`ready`||k.phase===`failed`)return;let e=()=>P(Date.now());e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[k.phase,k.startedAt]),(0,G.useEffect)(()=>{if(!t||!_||e.unread!==!0||!h.following||h.hasUnreadOutput)return;let n=re();if(!n)return;let r=e.attentionOutputEpoch||``,i=Number(e.attentionOutputSeq);r&&(r!==n.runtimeEpoch||Number.isFinite(i)&&i>n.outputSeq)||u?.(e.id,n)},[t,e.attentionOutputEpoch,e.attentionOutputSeq,e.id,e.unread,h.following,h.hasUnreadOutput,_,re,u]);let oe=(0,G.useCallback)((e=!1)=>{window.requestAnimationFrame(()=>{R({autoFocus:e}),window.requestAnimationFrame(()=>R({autoFocus:e}))})},[R]);(0,G.useEffect)(()=>{t&&oe(!1)},[t,oe]),(0,G.useEffect)(()=>{!t||n<=0||ae()||(oe(!0),te())},[t,te,n,oe]),(0,G.useEffect)(()=>()=>{B()},[B]);let V=(0,G.useCallback)((e,t=`next`,n)=>{let r=e.trim();if(!r){E(null),B();return}ie(r,t,{...C,...n}).then(E).catch(e=>{console.error(`Failed to search terminal:`,e),E({found:!1,resultIndex:0,resultCount:0})})},[B,ie,C]),se=(0,G.useCallback)(e=>{w(t=>({...t,[e]:t[e]!==!0}))},[]),ce=(0,G.useCallback)(()=>{let e=QT(ne());e&&(S(e),V(e,`next`,{incremental:!0})),b(!0),window.requestAnimationFrame(()=>{let e=m.current;e?.focus(),e?.select()})},[ne,V]),le=(0,G.useCallback)(()=>{b(!1),E(null),B(),ae()||te()},[B,te]),ue=(0,G.useCallback)(e=>{let t=YT(e.nativeEvent);if(t){e.preventDefault(),e.stopPropagation(),se(t);return}e.target===m.current&&e.key===`Enter`&&(e.preventDefault(),V(x,e.shiftKey?`previous`:`next`)),e.key===`Escape`&&(e.preventDefault(),le())},[le,V,x,se]);(0,G.useEffect)(()=>{y&&V(x,`next`,{incremental:!0})},[V,y,x]);let de=(0,G.useCallback)(e=>{if(XT(e.target,f.current)){if(qT(e)){e.preventDefault(),e.stopPropagation(),ce();return}if(y&&JT(e)){e.preventDefault(),e.stopPropagation(),V(x,e.shiftKey?`previous`:`next`);return}y&&e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),le())}},[le,ce,V,y,x]);(0,G.useEffect)(()=>{if(!t)return;let e=e=>{de(e)};return window.addEventListener(`keydown`,e,!0),()=>{window.removeEventListener(`keydown`,e,!0)}},[t,de]);let fe=(0,G.useCallback)(n=>{let i=n?.target,a=i instanceof Element&&i.closest(`.xterm`),o=n&&`pointerType`in n?n.pointerType:``;if(n&&n.button!==0){t||r(e.id,{focusTerminal:!1});return}if(a){t||r(e.id,{focusTerminal:!1}),(!ae()||o&&o!==`touch`)&&te();return}r(e.id),!(ae()&&(!o||o===`touch`))&&te()},[t,e.id,te,r]),pe=(0,G.useCallback)(e=>{e.button!==0||ne()||R()},[ne,R]),me=(0,G.useCallback)(()=>{z(),u?.(e.id,re()),!ae()&&te()},[e.id,te,re,u,z]),he=(0,G.useCallback)(()=>{O(null),te()},[te]),ge=!h.following||h.hasUnreadOutput,H=ZT(x,T,d),_e=k.phase!==`ready`&&k.phase!==`failed`&&!D,ve=k.startedAt===null?0:Math.max(0,Math.floor((N-k.startedAt)/1e3)),ye=k.phase===`installing`?d.terminalRecoveryInstalling:k.phase===`retrying`?d.terminalRecoveryRetrying(Math.max(1,Math.ceil((k.retryDelayMs||0)/1e3))):d.terminalRecoveryRequesting,be=[ve>0?d.terminalRecoveryElapsed(ve):``,k.attempt>1?d.terminalRecoveryAttempt(k.attempt):``].filter(Boolean).join(` · `);return(0,G.useEffect)(()=>{if(!_e||k.startedAt===null){M(!1);return}let e=Math.max(0,GT-(Date.now()-k.startedAt));if(e===0){M(!0);return}M(!1);let t=window.setTimeout(()=>M(!0),e);return()=>window.clearTimeout(t)},[_e,k.startedAt]),(0,K.jsxs)(`section`,{className:`code-terminal-pane ${t?`active`:``}`,"data-testid":`code-terminal-pane`,"data-agent-id":e.id,ref:f,onKeyDownCapture:de,onPointerDown:fe,children:[(0,K.jsx)(`div`,{className:`code-terminal-container terminal-container`,"data-testid":`code-terminal-container`,ref:p,onClick:pe}),_e&&j?(0,K.jsxs)(`div`,{className:`code-terminal-recovery`,"data-testid":`code-terminal-recovery`,"data-phase":k.phase,"data-attempt":k.attempt,role:`status`,"aria-live":`polite`,children:[(0,K.jsx)(`span`,{className:`code-permission-switching-spinner`,"aria-hidden":`true`}),(0,K.jsxs)(`span`,{className:`code-terminal-recovery-copy`,children:[(0,K.jsx)(`strong`,{children:ye}),be?(0,K.jsx)(`span`,{children:be}):null]})]}):null,D?(0,K.jsxs)(`div`,{className:`code-terminal-status-card`,"data-testid":`code-terminal-status-card`,title:D,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`span`,{children:d.terminalSessionUnavailable}),(0,K.jsx)(`button`,{type:`button`,onClick:he,children:d.retry})]}):null,y?(0,K.jsxs)(`form`,{className:`code-terminal-search`,"data-testid":`code-terminal-search`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onSubmit:e=>{e.preventDefault(),V(x,`next`)},onKeyDown:ue,children:[(0,K.jsx)(`input`,{ref:m,type:`search`,name:`farming-terminal-search`,inputMode:`search`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,value:x,placeholder:d.terminalSearchPlaceholder,"aria-label":d.terminalSearchPlaceholder,"data-testid":`code-terminal-search-input`,spellCheck:!1,enterKeyHint:`search`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,onChange:e=>S(e.target.value)}),(0,K.jsx)(`span`,{className:`code-terminal-search-status ${T&&!T.found?`empty`:``}`,children:H}),(0,K.jsx)(`button`,{type:`button`,className:$T(C.caseSensitive),"aria-label":d.terminalSearchCaseSensitive,"aria-pressed":C.caseSensitive===!0,title:d.terminalSearchCaseSensitive,"data-testid":`code-terminal-search-case-sensitive`,onClick:()=>se(`caseSensitive`),children:(0,K.jsx)(W,{})}),(0,K.jsx)(`button`,{type:`button`,className:$T(C.wholeWord),"aria-label":d.terminalSearchWholeWord,"aria-pressed":C.wholeWord===!0,title:d.terminalSearchWholeWord,"data-testid":`code-terminal-search-whole-word`,onClick:()=>se(`wholeWord`),children:(0,K.jsx)(Ue,{})}),(0,K.jsx)(`button`,{type:`button`,className:$T(C.regex),"aria-label":d.terminalSearchRegex,"aria-pressed":C.regex===!0,title:d.terminalSearchRegex,"data-testid":`code-terminal-search-regex`,onClick:()=>se(`regex`),children:(0,K.jsx)(we,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button`,"aria-label":d.terminalSearchPrevious,title:d.terminalSearchPrevious,onClick:()=>V(x,`previous`),children:(0,K.jsx)(Ye,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button`,"aria-label":d.terminalSearchNext,title:d.terminalSearchNext,onClick:()=>V(x,`next`),children:(0,K.jsx)(Je,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button close`,"aria-label":d.terminalSearchClose,title:d.terminalSearchClose,onClick:le,children:(0,K.jsx)(pt,{})})]}):null,ge?(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-jump-bottom`,"data-testid":`code-terminal-jump-bottom`,"aria-label":`Jump to latest output`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),me()},children:(0,K.jsx)(Je,{})}):null]})}var nE=o();function rE(e){let t=String(e.status||``).trim().replace(/[_-]/g,``).toLowerCase();return[`running`,`inprogress`,`pending`,`started`,`active`].includes(t)}function iE(e){let t=e[e.length-1];if(String(t?.type||``).toLowerCase()===`thought`)return`thinking`;let n=t&&rE(t)?t:void 0;if(!n)for(let t=e.length-1;t>=0;--t){let r=e[t];if(r&&String(r.type||``).toLowerCase()!==`plan`&&rE(r)){n=r;break}}if(!n)return`processing`;let r=String(n.type||``).toLowerCase(),i=String(n.kind||``).toLowerCase();return i===`think`?`thinking`:r===`plan`?`plan`:r===`patch`||[`edit`,`delete`,`move`].includes(i)?`editing`:i===`execute`?`running`:i===`read`?`reading`:i===`search`?`searching`:i===`fetch`?`fetching`:r===`tool`?`tool`:`processing`}function aE(e,t){return e.filter(e=>[`tool`,`patch`,`subagent`].includes(String(e.type||``).toLowerCase())&&rE(e)).map(e=>{let n=t[iE([e])],r=String(e.title||``).trim().replace(/\s+/g,` `);return r?`${n}: ${r}`:n}).join(` · `)}function oE(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(!n||String(n.type||``).toLowerCase()!==`plan`||!rE(n))continue;let r=Number(n.completedSteps),i=Number(n.totalSteps);return!Number.isInteger(r)||!Number.isInteger(i)||r<0||i<=0||r>i?null:{completed:r,total:i}}return null}function sE(e,t=10){let n=oE(e);if(!n)return``;let r=[...e].reverse().find(e=>String(e.type||``).toLowerCase()===`plan`&&rE(e)),i=String(r?.currentStep||``).trim().replace(/\s+/g,` `);if(!i)return``;let a=`${n.completed}/${n.total} `,o=Math.max(0,t-[...a].length);if(o<=0)return a.trim();let s=[...i];return`${a}${s.length<=o?i:`${s.slice(0,Math.max(1,o-1)).join(``)}…`}`}function cE(e,t){let n=e.split(`/`).filter(Boolean),r=(n[n.length-1]||``).replace(/[_-]+/g,` `).replace(/\s+/g,` `).trim();if(r)return r.charAt(0).toUpperCase()+r.slice(1);let i=t.replace(/[^a-z0-9]/gi,``).slice(0,6);return i?`Agent ${i}`:`Subagent`}function lE(e){return e===`started`?`started`:e===`interacted`?`updated`:e===`interrupted`?`interrupted`:null}function uE(e,t){return t===`failed`?`failed`:e===`spawnagent`?`started`:[`sendinput`,`resumeagent`].includes(e)?`updated`:e===`closeagent`?`finished`:null}function dE(e){let t=0;for(let n of e)t=t*31+n.charCodeAt(0)>>>0;return t}function fE(e){return dE(e)%4}function pE(e){return Math.floor(dE(e)/4)%6}function mE(e){let t=new Map,n=new Set;for(let r of e){let e=r.collaboration;if(e?.kind!==`activity`||!e.threadId)continue;t.set(e.threadId,cE(e.agentPath||``,e.threadId));let i=lE(String(e.activity||``).toLowerCase());i&&n.add(`${e.threadId}:${i}`)}let r=[],i=new Set,a=(e,n,a,o=``)=>{let s=`${e.id}:${n}:${a}`;!n||i.has(s)||(i.add(s),r.push({id:s,processItemId:e.id,threadId:n,name:t.get(n)||cE(``,n),action:a,tone:fE(n),title:String(e.title||``).trim(),message:String(o||``).trim()}))};for(let t of e){let e=t.collaboration;if(!e)continue;if(e.kind===`activity`){let n=lE(String(e.activity||``).toLowerCase())||`recorded`;a(t,e.threadId||``,n);continue}let r=String(e.tool||``).toLowerCase(),i=String(t.status||``).toLowerCase(),o=[...new Set([...e.receiverThreadIds||[],...Object.keys(e.agentsStates||{})].filter(Boolean))];for(let s of o){let o=r===`wait`?i===`failed`?`failed`:`recorded`:uE(r,i)||`recorded`;r!==`wait`&&o!==`recorded`&&n.has(`${s}:${o}`)||a(t,s,o,e.agentsStates?.[s]?.message)}}return r}function hE(e){return e===`pendingInit`?`pending`:e===`running`?`running`:e===`completed`?`completed`:e===`interrupted`?`paused`:[`errored`,`notFound`].includes(e)?`failed`:e===`shutdown`?`closed`:`unknown`}function gE(e,t=[]){let n=new Map(t.map(e=>[e.threadId,e])),r=new Map;for(let t of mE(e)){let e=r.get(t.threadId);if(e){e.events.push(t),e.task=t.name;let n=e.activities[e.activities.length-1];t.action===`updated`&&n?.action===t.action&&n.title===t.title&&n.message===t.message?(n.processItemId=t.processItemId,n.processItemIds.push(t.processItemId),n.count+=1):e.activities.push({id:t.id,processItemId:t.processItemId,processItemIds:[t.processItemId],action:t.action,title:t.title,message:t.message,count:1});continue}r.set(t.threadId,{id:t.threadId,threadId:t.threadId,name:t.name,task:t.name,status:hE(n.get(t.threadId)?.status||``),parentThreadId:n.get(t.threadId)?.parentThreadId,tone:t.tone,icon:pE(t.threadId),events:[t],activities:[{id:t.id,processItemId:t.processItemId,processItemIds:[t.processItemId],action:t.action,title:t.title,message:t.message,count:1}]})}for(let e of r.values()){let t=n.get(e.threadId);t?.name?.trim()&&(e.name=t.name.trim()),e.status=hE(t?.status||``),e.parentThreadId=t?.parentThreadId}for(let e of t)r.has(e.threadId)||r.set(e.threadId,{id:e.threadId,threadId:e.threadId,name:e.name?.trim()||cE(``,e.threadId),status:hE(e.status),parentThreadId:e.parentThreadId,tone:fE(e.threadId),icon:pE(e.threadId),events:[],activities:[]});return[...r.values()]}function _E(e,t=[]){let n=mE(e);if(n.length===0)return[];let r=new Map(t.map(e=>[e.threadId,e])),i=new Set(n.map(e=>e.threadId));for(let e of n){let t=new Set,n=r.get(e.threadId)?.parentThreadId;for(;n&&!t.has(n);)t.add(n),i.add(n),n=r.get(n)?.parentThreadId}return gE(e,t.filter(e=>i.has(e.threadId)))}function vE({terminalId:e,output:t,interactive:n,onInput:r,onResize:i}){let a=(0,G.useRef)(null),o=(0,G.useRef)(null),s=(0,G.useRef)(null),c=(0,G.useRef)(``),l=(0,G.useRef)(t),u=(0,G.useRef)(n),d=(0,G.useRef)(r),f=(0,G.useRef)(i),p=(0,G.useRef)(``),[m,h]=(0,G.useState)(``),[g,_]=(0,G.useState)(()=>Nt(jt())),v=(0,G.useRef)(g),y=Math.max(1,t.replace(/\r/g,``).split(`
157
+ `).length),b=Math.min(8,Math.max(4,y+1))*Math.ceil(g*1.25)+16;return l.current=t,u.current=n,d.current=r,f.current=i,v.current=g,(0,G.useEffect)(()=>{let e=new MutationObserver(e=>{e.some(e=>e.attributeName===`data-code-content-font-size`)&&_(Nt(jt()))});return e.observe(document.body,{attributes:!0,attributeFilter:[`data-code-content-font-size`]}),()=>e.disconnect()},[]),(0,G.useEffect)(()=>{if(!n)return;let e=a.current;if(!e)return;let t=!1,r=null,i;return Qy({fontSize:v.current,theme:`dark`}).then(({terminal:n,fitAddon:a})=>{if(t){n.dispose(),a.dispose();return}n.loadAddon(a),n.open(e),n.options&&(n.options.fontSize=v.current),e.querySelector(`textarea`)?.setAttribute(`aria-label`,`Terminal input`),o.current=n;let m=l.current;m&&n.write(m),c.current=m;let g=n.onData(e=>{!u.current||!d.current||d.current(e).then(()=>h(``)).catch(e=>{h(e instanceof Error?e.message:`Failed to send terminal input`)})}),_=()=>{if(!e.isConnected||e.clientWidth<=0||e.clientHeight<=0)return;a.fit();let t=Number(n.cols||0),r=Number(n.rows||0),i=`${t}x${r}`;!f.current||t<40||r<3||i===p.current||(p.current=i,f.current(t,r).catch(()=>{}))};s.current=_,r=new ResizeObserver(_),r.observe(e),window.requestAnimationFrame(_),i=()=>{s.current=null,r?.disconnect(),g.dispose(),a.dispose(),n.dispose()}}).catch(e=>{t||h(e instanceof Error?e.message:`Failed to start terminal view`)}),()=>{t=!0,o.current=null,i?.()}},[n,e]),(0,G.useEffect)(()=>{let e=o.current;e&&(e.options&&(e.options.fontSize=g),window.requestAnimationFrame(()=>s.current?.()))},[g]),(0,G.useEffect)(()=>{let e=o.current;!e||t===c.current||(t.startsWith(c.current)?e.write(t.slice(c.current.length)):(e.clearBuffer?.(),e.write(t)),c.current=t)},[t]),n?(0,K.jsxs)(`div`,{className:`code-acp-embedded-terminal interactive`,"data-testid":`code-acp-embedded-terminal`,children:[(0,K.jsx)(`div`,{ref:a,className:`code-acp-embedded-terminal-host`,style:{height:`${b}px`},onClick:()=>o.current?.focus()}),(0,K.jsx)(`pre`,{className:`code-visually-hidden`,"aria-label":`Terminal output`,children:t}),m?(0,K.jsx)(`small`,{className:`code-agent-transcript-terminal-error`,role:`alert`,children:m}):null]}):t?(0,K.jsx)(`pre`,{className:`code-acp-terminal-output`,"data-testid":`code-acp-terminal-output`,"aria-label":`Terminal output`,children:t}):null}var yE=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends yE{};function bE(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function xE(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function SE(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function CE(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function wE(e,t){return SE(e,t,``)}function TE(e,t){return CE(e,t,``)}function EE(e,t){return t.slice(0,DE(e,t))}function DE(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function OE(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function kE(e,t){if(t)return jE(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function AE(e,t){if(t)return jE(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function jE(e,t){if(!t)return[AE(e),kE(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=OE(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var ME=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,NE=RegExp(`[${ME}]+|\\s+|[^${ME}]`,`ug`);new class extends yE{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=OE(e,r)}else n=e.match(NE)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&PE(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&PE(n,i,r,null,t.intlSegmenter),e}};function PE(e,t,n,r,i){if(t&&n){let[a,o]=jE(t.value,i),[s,c]=jE(n.value,i);if(e){let r=bE(a,s);e.value=CE(e.value,s,r),t.value=wE(t.value,r),n.value=wE(n.value,r)}if(r){let e=xE(o,c);r.value=SE(r.value,c,e),t.value=TE(t.value,e),n.value=TE(n.value,e)}}else if(n){if(e){let e=AE(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=AE(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=AE(r.value,i),[a,o]=jE(t.value,i),s=bE(n,a);t.value=wE(t.value,s);let c=xE(wE(n,s),o);t.value=TE(t.value,c),r.value=SE(r.value,n,c),e.value=CE(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=AE(r.value,i),n=EE(kE(t.value,i),e);t.value=TE(t.value,n)}else if(e){let n=EE(kE(e.value,i),AE(t.value,i));t.value=wE(t.value,n)}}new class extends yE{tokenize(e){let t=RegExp(`(\\r?\\n)|[${ME}]+|[^\\S\\n\\r]+|[^${ME}]`,`ug`);return e.match(t)||[]}};var FE=new class extends yE{constructor(){super(...arguments),this.tokenize=LE}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
158
+ `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
159
+ `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
160
+ `)&&(e=e.slice(0,-1)),t.endsWith(`
161
+ `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function IE(e,t,n){return FE.diff(e,t,n)}function LE(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
162
+ `));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function RE(e){return e==`.`||e==`!`||e==`?`}new class extends yE{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(RE(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}},new class extends yE{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends yE{constructor(){super(...arguments),this.tokenize=LE}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(zE(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};function zE(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=zE(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=zE(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends yE{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};function BE(e){for(let t=0;t<e.length;t++)if(e[t]<` `||e[t]>`~`||e[t]===`"`||e[t]===`\\`)return!0;return!1}function VE(e){if(!BE(e))return e;let t=`"`,n=new TextEncoder().encode(e),r=0;for(;r<n.length;){let e=n[r];e===7?t+=`\\a`:e===8?t+=`\\b`:e===9?t+=`\\t`:e===10?t+=`\\n`:e===11?t+=`\\v`:e===12?t+=`\\f`:e===13?t+=`\\r`:e===34?t+=`\\"`:e===92?t+=`\\\\`:e>=32&&e<=126?t+=String.fromCharCode(e):t+=`\\`+e.toString(8).padStart(3,`0`),r++}return t+=`"`,t}var HE={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function UE(e,t,n,r,i,a,o){let s;s=o?typeof o==`function`?{callback:o}:o:{},s.context===void 0&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(s.callback){let{callback:e}=s;IE(n,r,Object.assign(Object.assign({},s),{callback:t=>{e(l(t))}}))}else return l(IE(n,r,s));function l(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}let o=[],s=0,l=0,u=[],d=1,f=1;for(let e=0;e<n.length;e++){let t=n[e],i=t.lines||KE(t.value);if(t.lines=i,t.added||t.removed){if(!s){let t=n[e-1];s=d,l=f,t&&(u=c>0?r(t.lines.slice(-c)):[],s-=u.length,l-=u.length)}for(let e of i)u.push((t.added?`+`:`-`)+e);t.added?f+=i.length:d+=i.length}else{if(s)if(i.length<=c*2&&e<n.length-2)for(let e of r(i))u.push(e);else{let e=Math.min(i.length,c);for(let t of r(i.slice(0,e)))u.push(t);let t={oldStart:s,oldLines:d-s+e,newStart:l,newLines:f-l+e,lines:u};o.push(t),s=0,l=0,u=[]}d+=i.length,f+=i.length}}for(let e of o)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith(`
163
+ `)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function WE(e,t){if(t||=HE,Array.isArray(e)){if(e.length>1&&!t.includeFileHeaders&&!e.every(e=>e.isGit))throw Error(`Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)`);return e.map(e=>WE(e,t)).join(`
164
+ `)}let n=[];if(e.isGit){if(t=HE,!e.oldFileName)throw Error(`oldFileName must be specified for Git patches`);if(!e.newFileName)throw Error(`newFileName must be specified for Git patches`);let r=e.oldFileName,i=e.newFileName;e.isCreate&&r===`/dev/null`?r=i.replace(/^b\//,`a/`):e.isDelete&&i===`/dev/null`&&(i=r.replace(/^a\//,`b/`)),n.push(`diff --git `+VE(r)+` `+VE(i)),e.isDelete&&n.push(`deleted file mode `+(e.oldMode??`100644`)),e.isCreate&&n.push(`new file mode `+(e.newMode??`100644`)),e.oldMode&&e.newMode&&!e.isDelete&&!e.isCreate&&(n.push(`old mode `+e.oldMode),n.push(`new mode `+e.newMode)),e.isRename&&(n.push(`rename from `+VE((e.oldFileName??``).replace(/^a\//,``))),n.push(`rename to `+VE((e.newFileName??``).replace(/^b\//,``)))),e.isCopy&&(n.push(`copy from `+VE((e.oldFileName??``).replace(/^a\//,``))),n.push(`copy to `+VE((e.newFileName??``).replace(/^b\//,``))))}else t.includeIndex&&e.oldFileName==e.newFileName&&e.oldFileName!==void 0&&n.push(`Index: `+e.oldFileName),t.includeUnderline&&n.push(`===================================================================`);let r=e.hunks.length>0;t.includeFileHeaders&&e.oldFileName!==void 0&&e.newFileName!==void 0&&(!e.isGit||r)&&(n.push(`--- `+VE(e.oldFileName)+(e.oldHeader?` `+e.oldHeader:``)),n.push(`+++ `+VE(e.newFileName)+(e.newHeader?` `+e.newHeader:``)));for(let t=0;t<e.hunks.length;t++){let r=e.hunks[t],i=r.oldLines===0?r.oldStart-1:r.oldStart,a=r.newLines===0?r.newStart-1:r.newStart;n.push(`@@ -`+i+`,`+r.oldLines+` +`+a+`,`+r.newLines+` @@`);for(let e of r.lines)n.push(e)}return n.join(`
165
+ `)+`
166
+ `}function GE(e,t,n,r,i,a,o){if(typeof o==`function`&&(o={callback:o}),o?.callback){let{callback:s}=o;UE(e,t,n,r,i,a,Object.assign(Object.assign({},o),{callback:e=>{s(e?WE(e,o.headerOptions):void 0)}}))}else{let s=UE(e,t,n,r,i,a,o);return s?WE(s,o?.headerOptions):void 0}}function KE(e){let t=e.endsWith(`
167
+ `),n=e.split(`
168
+ `).map(e=>e+`
169
+ `);return t?n.pop():n.push(n.pop().slice(0,-1)),n}var qE=64*1024,JE=4*1024;function YE(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function XE(e){return Array.isArray(e)?e:[]}function $(e){return typeof e==`string`?e:e==null?``:String(e)}function ZE(e){return XE(e).map(YE).filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``).trim()}function QE(e){let t=e.trim();return/^(?:#{1,3}\s*)?(?:\*{1,2}|_{1,2})?Handoff Summary(?:\*{1,2}|_{1,2})?(?:[ \t]*:|[ \t]*(?:\r?\n|$))/i.test(t)||/^Another language model started to solve this problem and produced a summary\b/i.test(t)}function $E(e){return QE(e)?``:e.replace(/\s*\*?Context compacted(?: to fit the model's context window)?\.\*?\s*/gi,``).trim()}function eD(e){return $(YE(YE(e._meta).codex).phase).trim().toLowerCase()}function tD(e){return YE(YE(e._meta).codex).steer===!0}function nD(e){return XE(e).map(YE).filter(e=>e.type===`diff`&&typeof e.path==`string`&&e.path.trim())}function rD(e){let t=$(YE(e._meta).kind).trim().toLowerCase();return[`add`,`added`,`create`,`created`].includes(t)?`Added`:[`delete`,`deleted`,`remove`,`removed`].includes(t)?`Deleted`:[`move`,`moved`].includes(t)?`Moved`:[`rename`,`renamed`].includes(t)?`Renamed`:`Updated`}function iD(e){let t=$(e);return t.length<=qE?t:`${t.slice(0,qE)}\n\n[Diff detail truncated]`}function aD(e){let t=$(e.path).trim();return`File: ${t}\n${iD(GE(t,t,$(e.oldText),$(e.newText),`before`,`after`,{context:3}))}`.trim()}function oD(e){return nD(e).map(e=>`${rD(e)} ${$(e.path).trim()}`).join(`
170
+ `)}function sD(e,t){return IE(e,t).reduce((e,t)=>{let n=Number(t.count||0);return t.added&&(e.added+=n),t.removed&&(e.removed+=n),e},{added:0,removed:0})}function cD(e,t={}){return nD(e).map(e=>{let n=$(e.path).trim(),r=$(e.oldText),i=$(e.newText),a=sD(r,i);return{path:n,kind:rD(e).toLowerCase(),added:a.added,removed:a.removed,diff:iD(GE(n,n,r,i,`before`,`after`,{context:3})),...$(t[n])?{decision:$(t[n])}:{}}})}function lD(e){if(e==null)return``;if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function uD(e){return XE(e).map(e=>{let t=YE(e);if(t.type===`content`){let e=YE(t.content);return e.type===`text`?$(e.text):e.type===`resource_link`?[e.name,e.uri].filter(Boolean).join(` — `):e.type===`resource`?lD(e.resource):e.type===`image`?`[Image: ${$(e.mimeType)||`image`}]`:e.type===`audio`?`[Audio: ${$(e.mimeType)||`audio`}]`:lD(e)}return t.type===`diff`?aD(t):t.type===`text`?$(t.text):t.type===`image`||t.type===`audio`?``:t.type===`resource_link`?[t.name,t.uri].map($).filter(Boolean).join(` — `):t.type===`resource`?lD(t.resource):lD(t)}).filter(Boolean).join(`
171
+
172
+ `).trim()}function dD(e){let t=YE(e.rawOutput),n=YE(t.result);return Array.isArray(n.content)?n.content:Array.isArray(t.content)?t.content:[]}function fD(e){return e.replace(/<app_specific_instructions>[\s\S]*?<\/app_specific_instructions>\s*/gi,``).trim()}function pD(e){let t=new Set;return e.filter(e=>!e.url||t.has(e.url)?!1:(t.add(e.url),!0))}function mD(e,t){return XE(e).map(YE).filter(e=>e.type===`image`&&(typeof e.data==`string`&&e.data||typeof e.url==`string`&&e.url)).map((e,n)=>({id:`${t}-image-${n+1}`,url:typeof e.url==`string`&&e.url?e.url:`data:${$(e.mimeType)||`image/png`};base64,${e.data}`,alt:`Image`}))}function hD(e,t){return XE(e).map(YE).filter(e=>e.type===`audio`&&(typeof e.data==`string`&&e.data||typeof e.url==`string`&&e.url)).map((e,n)=>({id:`${t}-audio-${n+1}`,url:typeof e.url==`string`&&e.url?e.url:`data:${$(e.mimeType)||`audio/mpeg`};base64,${e.data}`,mimeType:$(e.mimeType)||`audio/mpeg`,name:$(e.name)||`Audio ${n+1}`}))}function gD(e,t){return XE(e).flatMap((e,n)=>{let r=YE(e);if(r.type===`resource_link`)return[{id:`${t}-resource-link-${n+1}`,name:$(r.name||r.uri)||`Resource`,content:$(r.uri),uri:$(r.uri),mimeType:$(r.mimeType),resourceKind:`link`}];if(r.type!==`resource`||!r.resource)return[];let i=YE(r.resource);return[{id:`${t}-resource-${n+1}`,name:$(i.name||i.uri)||`Resource`,content:$(i.text||i.uri),uri:$(i.uri),mimeType:$(i.mimeType),resourceKind:i.blob?`blob`:`embedded`,...i.blob?{error:`[Binary resource: ${$(i.mimeType)||`application/octet-stream`}]`}:{}}]})}function _D(e,t){let n=e.trim();if(!n||t==null)return!1;if(n===lD(t).trim())return!0;try{return JSON.stringify(JSON.parse(n))===JSON.stringify(t)}catch{return!1}}function vD(e){let t=e.rawOutput;if($(e.kind).toLowerCase()===`execute`&&t&&typeof t==`object`&&!Array.isArray(t)){let e=YE(t),n=typeof e.stdout==`string`?e.stdout.trimEnd():``,r=typeof e.stderr==`string`?e.stderr.trimEnd():``,i=[];if(n&&i.push(n),r&&i.push(`stderr\n${r}`),e.interrupted===!0&&i.push(`Interrupted`),i.length>0)return i.join(`
173
+
174
+ `)}let n=dD(e);if(n.length>0){let e=fD(uD(n)),r=YE(t).error;return[e,r?`Error\n${lD(r)}`:``].filter(Boolean).join(`
175
+
176
+ `)}return lD(t).trim()}function yD(e){let t=[],n=lD(e.rawInput).trim(),r=uD(XE(e.content).filter(e=>YE(e).type!==`terminal`)),i=vD(e);return _D(r,e.rawOutput)&&(r=``),n&&t.push(`Input\n${n}`),r&&t.push(r),i&&t.push(`Output\n${i}`),t.join(`
177
+
178
+ `)}function bD(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function xD(e){return XE(e.locations).slice(0,20).flatMap(e=>{let t=YE(e),n=YE(t.range),r=YE(n.start),i=YE(n.end),a=$(t.path||t.uri).trim().slice(0,1024);if(!a)return[];let o=bD(t.lineNumber??t.line??r.line),s=bD(t.column??r.column),c=bD(t.endLineNumber??t.endLine??i.line),l=bD(t.endColumn??i.column);return[{path:a,...o===void 0?{}:{lineNumber:o},...s===void 0?{}:{column:s},...c===void 0?{}:{endLineNumber:c},...l===void 0?{}:{endColumn:l}}]})}function SD(e){return e.length<=JE?{detail:e,detailTruncated:!1}:{detail:`${e.slice(0,JE)}\n\n[Open to load full detail]`,detailTruncated:!0}}function CD(e){let t=YE(e),n=XE(t.entries).map(YE);return n.length>0?n.map(e=>{let t=$(e.status).toLowerCase();return`[${t===`completed`?`x`:[`in_progress`,`in-progress`,`running`].includes(t)?`>`:` `}] ${$(e.content||e.title)}`}).join(`
179
+ `):t.type===`markdown`?$(t.content):t.type===`file`?$(t.uri):``}function wD(e){return e===`authentication`?`Authentication required`:e===`payment`?`Billing problem`:e===`context`?`Context limit reached`:e===`model`?`Model unavailable`:e===`rate-limit`?`Rate limit reached`:e===`network`?`Connection problem`:e===`protocol`?`ACP protocol error`:`Agent error`}function TD(e){let t=YE(YE(e._meta).codex),n=YE(t.collaboration);if(Object.keys(n).length>0){let e=Object.entries(YE(n.agentsStates)).reduce((e,[t,n])=>{let r=YE(n);return e[t]={status:$(r.status),...$(r.message)?{message:$(r.message)}:{}},e},{});return{kind:`tool`,tool:$(n.tool),senderThreadId:$(n.senderThreadId),receiverThreadIds:XE(n.receiverThreadIds).map($).filter(Boolean),agentsStates:e}}let r=YE(t.subagent);if(Object.keys(r).length>0)return{kind:`activity`,threadId:$(r.threadId),agentPath:$(r.path),activity:$(r.activity)}}function ED(e){if(e.type===`error`){let t=$(e.kind)||`unknown`;return{id:$(e.id),type:`error`,kind:t,title:wD(t),detail:$(e.message),status:`failed`}}if(e.type===`thought`){let t=ZE(e.content);return t?{id:$(e.id),type:`thought`,title:`Reasoning`,detail:t,status:`completed`}:null}if(e.type===`tool`){let t=YE(YE(e._meta).subagent_session_info),n=YE(e._meta).contextCompaction===!0,r=TD(e),i=XE(e.content).map(YE).filter(e=>e.type===`terminal`&&e.terminalId).map(e=>$(e.terminalId)),a=XE(e.content).map(YE).flatMap(e=>e.type===`content`&&e.content?[e.content]:[`image`,`audio`,`resource_link`,`resource`].includes($(e.type))?[e]:[]),o=dD(e),s=[...a,...o],c=$(e.id)||`tool`,l=pD(mD(s,c)),u=pD(hD(s,c)),d=gD(s,c),f=xD(e),p=$(e.transcriptPatchSummary)||oD(e.content),m=Array.isArray(e.transcriptChanges)?e.transcriptChanges.map(YE).map(e=>({path:$(e.path),kind:$(e.kind),added:Number(e.added||0),removed:Number(e.removed||0),...typeof e.diff==`string`?{diff:e.diff}:{},...$(e.decision)?{decision:$(e.decision)}:{}})):cD(e.content,YE(YE(e._meta).farming_patch_decisions)),h=typeof e.transcriptDetail==`string`?{detail:e.transcriptDetail,detailTruncated:e.transcriptDetailTruncated===!0}:SD([p,yD(e)].filter(Boolean).join(`
180
+
181
+ `)),g=$(t.session_id);return{id:$(e.id),type:n?`compaction`:g?`subagent`:p?`patch`:r?`collaboration`:`tool`,kind:$(e.kind)||`other`,title:n?$(e.status)===`completed`?`Context compacted`:`Compacting context`:$(e.title)||`Tool`,detail:[g?`Session ${g}`:``,h.detail].filter(Boolean).join(`
182
+
183
+ `),detailTruncated:h.detailTruncated,status:$(e.status),...i.length>0?{terminalIds:i}:{},...g?{subagentSessionId:g}:{},...r?{collaboration:r}:{},...l.length>0?{images:l}:{},...u.length>0?{audios:u}:{},...d.length>0?{files:d}:{},...f.length>0?{locations:f}:{},...m.length>0?{changes:m}:{}}}if(e.type===`plan`){let t=CD(e.plan);if(!t)return null;let n=XE(YE(e.plan).entries).map(YE),r=n.filter(e=>e.status===`completed`).length,i=n.find(e=>[`in_progress`,`running`].includes($(e.status)));return{id:$(e.id),type:`plan`,title:`Plan`,detail:t,status:n.length>0&&n.every(e=>e.status===`completed`)?`completed`:`running`,completedSteps:r,totalSteps:n.length,currentStep:$(i?.content||i?.title)}}return e.type===`compaction`?{id:$(e.id),type:`compaction`,title:e.status===`completed`?`Context compacted`:`Compacting context`,detail:$(e.summary),status:$(e.status)||`completed`}:null}function DD(e){if(e.type!==`tool`)return!1;if(e.generatedMedia===!0)return!0;let t=$(e.title).trim().toLowerCase(),n=$(e.id).trim().toLowerCase(),r=YE(e.rawOutput);return n.startsWith(`ig_`)||t===`image generation`||t===`audio generation`||!!$(r.savedPath).includes(`/generated_images/`)}function OD(e,t){return{id:e,internal:t,userMessage:``,userImages:[],userFiles:[],userAudios:[],resultImages:[],resultFiles:[],resultAudios:[],finalMessage:``,startedAt:null,completedAt:null,durationMs:null,status:`completed`,processItems:[],assistantMessages:[]}}function kD(e,t){if(!e)return null;let n=e.assistantMessages[e.assistantMessages.length-1],r=e.processItems[e.processItems.length-1];e.internal&&n?.text?e.finalMessage=n.text:!e.finalMessage&&!t&&n?.text&&n.processItemId&&n.phase!==`commentary`&&r?.id===n.processItemId&&(r.images||[]).length===0&&(r.audios||[]).length===0&&(r.files||[]).length===0&&(e.finalMessage=n.text,e.processItems.pop());let{internal:i,assistantMessages:a,...o}=e;return i&&(o.processItems=[]),o.userMessage||o.finalMessage||o.userImages.length>0||o.userAudios.length>0||o.userFiles.length>0||o.resultImages.length>0||o.resultAudios.length>0||o.resultFiles.length>0||o.processItems.length>0?o:null}function AD(e,t={}){let n=YE(e),r=XE(n.entries),i=[...r].reverse().map(YE).find(e=>e.type===`plan`),a=Object.prototype.hasOwnProperty.call(n,`plan`)?n.plan:i?.plan,o=a==null?void 0:ED({id:$(YE(a).planId)||$(i?.id)||`active-plan`,type:`plan`,plan:a})||void 0,s=[],c=null,l=0,u=[`working`,`waiting-for-permission`,`waiting-for-input`,`interrupting`].includes($(n.state)),d=(e=!1)=>{let t=kD(c,e);t&&s.push(t),c=null};for(let e of r){let t=YE(e);if(t.type===`message`&&t.role===`user`){if(tD(t)){c||=OD(`acp-segment-${++l}`,!1);let e=$(t.id)||String(++l);c.finalMessage&&(c.processItems.push({id:`acp-earlier-answer-${e}`,type:`progress`,title:`Earlier answer`,detail:c.finalMessage,status:`completed`}),c.assistantMessages.push({text:c.finalMessage,processItemId:`acp-earlier-answer-${e}`,phase:`commentary`}),c.finalMessage=``),c.processItems.push({id:`acp-steer-${e}`,type:`user-steer`,title:`Steering update`,...Number.isFinite(Number(t.createdAt))?{createdAt:Number(t.createdAt)}:{},detail:ZE(t.content),images:mD(t.content,e),audios:hD(t.content,e),files:gD(t.content,e),status:`completed`});continue}d();let e=$(t.id)||String(++l);c=OD(`acp-turn-${e}`,t.internal===!0),c.startedAt=t.turnStartedAt==null?null:Number(t.turnStartedAt),c.completedAt=t.turnCompletedAt==null?null:Number(t.turnCompletedAt),c.durationMs=Number.isFinite(Number(t.turnDurationMs))?Number(t.turnDurationMs):null,t.internal||(c.userMessage=ZE(t.content),c.userImages=mD(t.content,e),c.userAudios=hD(t.content,e),c.userFiles=gD(t.content,e));continue}if(c||=OD(`acp-segment-${++l}`,t.internal===!0),t.internal===!0&&!c.internal&&(d(),c=OD(`acp-segment-${++l}`,!0)),t.type===`message`&&t.role===`assistant`){let e=$E(ZE(t.content)),n=eD(t),r=$(t.id)||`assistant`,i=mD(t.content,r),a=hD(t.content,r),o=gD(t.content,r);if(n===`final_answer`&&e){c.finalMessage=e;continue}let s=e?`acp-progress-${$(t.id)||String(++l)}`:``;c.assistantMessages.push({text:e,processItemId:s,phase:n}),!c.internal&&(e||i.length>0||a.length>0||o.length>0)&&c.processItems.push({id:s,type:`progress`,title:`Progress update`,detail:e,status:`completed`,...i.length>0?{images:i}:{},...a.length>0?{audios:a}:{},...o.length>0?{files:o}:{}});continue}if(c.internal||t.internal===!0||t.type===`plan`)continue;let n=ED(t);n&&DD(t)?(c.resultImages=pD([...c.resultImages,...n.images||[]]),c.resultAudios=pD([...c.resultAudios,...n.audios||[]]),c.resultFiles.push(...n.files||[]),c.processItems.push({...n,images:void 0,audios:void 0,files:void 0})):n&&c.processItems.push(n)}d(u);let f=s[s.length-1];f&&u?f.status=`inProgress`:f&&[`cancelled`,`canceled`,`max_tokens`,`max_turn_requests`,`refusal`,`error`,`cancel_error`].includes($(n.stopReason).toLowerCase())&&(f.status=`interrupted`);let p=Number.isFinite(Number(t.maxTurns))?Math.max(1,Math.floor(Number(t.maxTurns))):80,m=s.slice(-p),h=YE(n.codexSubagents),g=Number(h.version)===1?{version:1,rootThreadId:$(h.rootThreadId),revision:Number(h.revision||0),agents:XE(h.agents).slice(0,128).map(e=>{let t=YE(e);return{threadId:$(t.threadId),parentThreadId:$(t.parentThreadId)||void 0,name:$(t.name)||void 0,status:$(t.status)}}).filter(e=>!!(e.threadId&&e.status))}:void 0;return{version:2,available:m.length>0,reason:m.length>0?void 0:`empty-acp-session`,sessionId:$(n.sessionId),title:$(n.title),updatedAt:$(n.updatedAt),source:`acp`,state:$(n.state),error:$(n.error),errorKind:$(n.errorKind),revision:Number(n.revision||0),delta:n.delta===!0,replaceFromTurnId:n.delta===!0?$(m[0]?.id):``,stopReason:$(n.stopReason),plan:o,...g?{codexSubagents:g}:{},hasMoreBefore:n.hasMoreBefore===!0||s.length>m.length,turnLimit:p,truncated:n.truncated===!0,turns:m}}function jD(e){let t=String(e.type||``).trim().toLowerCase(),n=String(e.kind||``).trim().toLowerCase();return t===`thought`||t===`progress`||t===`plan`?null:t===`patch`||[`edit`,`delete`,`move`].includes(n)?`edit`:n===`read`||t===`file-read`||t===`read`?`read`:n===`search`||t===`search`||t===`web-search`?`search`:n===`execute`||t===`command`?`execute`:n===`fetch`?`fetch`:`tool`}function MD(e,t){return e===`edit`?t===1?`Edited a file`:`Edited files`:e===`read`?t===1?`Read a file`:`Read files`:e===`search`?t===1?`Searched code`:`Searched code ${t} times`:e===`execute`?t===1?`Ran a command`:`Ran commands`:e===`fetch`?t===1?`Fetched a resource`:`Fetched resources`:t===1?`Used a tool`:`Used tools`}function ND(e){let t=e.filter(e=>[`failed`,`rejected`,`cancelled`,`canceled`].includes(String(e.status||``).toLowerCase())).length;if(t>0)return t===1?`Action failed`:`${t} actions failed`;let n=new Map;for(let t of e){let e=jD(t);e&&n.set(e,(n.get(e)||0)+1)}return n.size===0?`Reasoning`:[...n.entries()].map(([e,t],n)=>{let r=MD(e,t);return n===0?r:`${r.charAt(0).toLowerCase()}${r.slice(1)}`}).join(`, `)}function PD(e){return String(e.type||``).trim().toLowerCase()===`progress`}function FD(e){let t=String(e.type||``).trim().toLowerCase();return t===`progress`||t===`user-steer`}function ID(e){let t=[],n=[],r=()=>{n.length!==0&&(t.push({kind:`group`,id:`group:${String(n[0]?.id||``)}`,items:n}),n=[])};for(let i of e)if(String(i.type||``).trim().toLowerCase()!==`plan`){if(!FD(i)){n.push(i);continue}r(),t.push({kind:`item`,item:i})}return r(),t}function LD(e){return e.trim().replace(/\\/g,`/`)}function RD(e){return LD(e).replace(/\/+$/,``)}function zD(e){let t=RD(e);return/^\/Users\/[^/]+/.exec(t)?.[0]??``}function BD(e,t){let n=LD(e).replace(/\/+$/,``),r=RD(t);if(!n||!r)return null;let i=[r];r===`/private/tmp`||r.startsWith(`/private/tmp/`)||r===`/private/var`||r.startsWith(`/private/var/`)?i.push(r.slice(8)):(r===`/tmp`||r.startsWith(`/tmp/`)||r===`/var`||r.startsWith(`/var/`))&&i.push(`/private${r}`);for(let e of i){if(n===e)return``;let t=`${e}/`;if(n.startsWith(t))return n.slice(t.length)}return null}function VD(e,t){let n=LD(e);if(!n||n.startsWith(`../`))return null;if(n.startsWith(`./`))return n.replace(/^\.\/+/,``);if(n.startsWith(`~/`)){let e=zD(t);return e?BD(`${e}/${n.slice(2)}`,t):null}return n.startsWith(`/`)?BD(n,t):n}function HD(e){let t=LD(e);return!t.startsWith(`/`)||t.startsWith(`//`)?null:t.replace(/^\/+/,``)}var UD={kind:`unavailable`},WD={kind:`working-copy`};function GD(e){if(e.staged.available||e.unstaged.available)return WD;let t=e.commits[0];return t?{base:t.base,head:t.head,kind:`last-commit`}:WD}function KD(e,t){let n=new URLSearchParams({root:e});return t.kind===`last-commit`&&(n.set(`base`,t.base),n.set(`head`,t.head)),n}var qD=(0,G.createContext)({});function JD(e,t){let n=e.processItems[e.processItems.length-1],r=t.processItems[t.processItems.length-1];return e.status!==`inProgress`&&t.status!==`inProgress`&&e.userMessage===t.userMessage&&e.finalMessage===t.finalMessage&&e.startedAt===t.startedAt&&e.completedAt===t.completedAt&&e.durationMs===t.durationMs&&e.userImages?.length===t.userImages?.length&&e.userAudios?.length===t.userAudios?.length&&e.userFiles?.length===t.userFiles?.length&&e.resultImages?.length===t.resultImages?.length&&e.resultAudios?.length===t.resultAudios?.length&&e.resultFiles?.length===t.resultFiles?.length&&e.processItems.length===t.processItems.length&&n?.id===r?.id&&n?.status===r?.status&&n?.title===r?.title&&n?.detail===r?.detail}function YD(e,t){if(!e||!t||e.sessionId!==t.sessionId)return t;let n=new Map(e.turns.filter(e=>e.status!==`inProgress`).map(e=>[e.id,e]));return{...t,turns:t.turns.map(e=>{let t=n.get(e.id);return t&&JD(t,e)?t:e})}}function XD(e,t){if(e&&t&&e.sessionId===t.sessionId&&typeof e.revision==`number`&&typeof t.revision==`number`&&t.revision<e.revision)return e;if(!t?.delta)return YD(e,t);if(!e||e.sessionId!==t.sessionId)return t;if(!t.replaceFromTurnId||t.turns.length===0)return{...e,...t,available:e.available,hasMoreBefore:e.hasMoreBefore,turns:e.turns};let n=e.turns.findIndex(e=>e.id===t.replaceFromTurnId);if(n<0){let n=new Set(e.turns.map(e=>e.id)),r=t.turns.filter(e=>!n.has(e.id)),i=[...e.turns,...r],a=e.turnLimit&&i.length>e.turnLimit?i.slice(-e.turnLimit):i;return YD(e,{...e,...t,available:e.available||t.available,hasMoreBefore:e.hasMoreBefore||t.hasMoreBefore||a.length<i.length,turns:a})}return YD(e,{...t,available:e.available||t.available,hasMoreBefore:e.hasMoreBefore||t.hasMoreBefore,turns:[...e.turns.slice(0,n),...t.turns]})}function ZD(e,t){if(ck(t)){ee(I(e,`chat`));return}let n=t.getBoundingClientRect(),r=Array.from(t.querySelectorAll(`[data-turn-id]`)).find(e=>e.getBoundingClientRect().bottom>n.top);if(!r)return;let i=Array.from(r.querySelectorAll(`[data-process-item-id]`)).find(e=>e.getBoundingClientRect().bottom>n.top),a=(i||r).getBoundingClientRect(),o=a.height>0?Math.max(0,Math.min(1,(n.top-a.top)/a.height)):0,s=r.dataset.turnId;s&&me({version:1,surface:`chat`,resource:{kind:`agent`,id:e},locator:{kind:`message`,id:s,...i?.dataset.processItemId?{childId:i.dataset.processItemId}:{}},position:{unit:`fraction`,value:o}})}function QD(e,t){let n=I(e,`chat`),r=L(n);if(!r)return`none`;if(r.surface!==`chat`||r.resource.kind!==`agent`)return ee(n),`expired`;let i=t.querySelector(`[data-turn-id="${CSS.escape(r.locator.id)}"]`);if(!i)return ee(n),`expired`;let a=((r.locator.childId?i.querySelector(`[data-process-item-id="${CSS.escape(r.locator.childId)}"]`):null)||i).getBoundingClientRect(),o=t.getBoundingClientRect(),s=a.height*r.position.value;return t.scrollTop+=a.top+s-o.top,`restored`}var $D=80,eO=80,tO=20,nO=20,rO=1e3,iO=[250,1e3];function aO(e){return e===`acp`?tO:$D}var oO=72,sO=96;function cO(e){if(!e||!Number.isFinite(e)||e<1e3)return``;let t=Math.round(e/1e3);if(t<=0)return``;if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r?`${n}m ${r}s`:`${n}m`}function lO(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return``;let n=t<0xe8d4a51000?t*1e3:t;return cO(Math.max(0,Date.now()-n))}function uO(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return null;let n=t<0xe8d4a51000?t*1e3:t,r=new Date(n);return Number.isFinite(r.getTime())?{dateTime:r.toISOString(),label:r.toLocaleTimeString([],{hour:`numeric`,minute:`2-digit`}),title:r.toLocaleString()}:null}function dO({timestamp:e,kind:t}){let n=uO(e);return n?(0,K.jsx)(`time`,{className:`code-agent-transcript-message-time code-agent-transcript-message-time-${t}`,"data-testid":`code-agent-transcript-${t}-time`,dateTime:n.dateTime,title:n.title,children:n.label}):null}function fO(e){return{thinking:e.agentTranscriptThinking,running:e.agentTranscriptRunning,reading:e.agentTranscriptReading,searching:e.agentTranscriptSearching,editing:e.agentTranscriptEditing,plan:e.agentTranscriptPlanActive,fetching:e.agentTranscriptFetching,tool:e.agentTranscriptUsingTool,processing:e.agentTranscriptWorking}}function pO(e,t){return fO(t)[iE(e.processItems)]}function mO(e,t){return aE(e.processItems,fO(t))}function hO(e,t){let n=oE(e.processItems);return n?sE(e.processItems)||(n.total<=99?t.agentTranscriptPlanProgress(n.completed,n.total):t.agentTranscriptPlanActive):``}function gO(e,t,n=t.agentTranscriptWorking,r=``){let i=cO(e.durationMs),a=e.status===`interrupted`?e.processItems.find(e=>e.type===`error`):void 0;return a?.title?a.title:i?t.agentTranscriptWorkedFor(i):e.status===`inProgress`?r||n:t.agentTranscriptProcess}function _O(e,t){if(!(e.processItems.length<=0))return t.agentTranscriptProcessCount(e.processItems.length)}function vO(e){let t=e.split(`
184
+ `);return t.map((e,n)=>(0,K.jsxs)(`span`,{children:[e,n<t.length-1?(0,K.jsx)(`br`,{}):null]},n))}function yO(e){return e.replace(/<oai-mem-citation>[\s\S]*?<\/oai-mem-citation>/g,``).trim()}function bO(e){let t=e.trim();return xO(t)?!1:/^[a-z][a-z\d+.-]*:/i.test(t)||SO(t)}function xO(e){return!!kO(e)?.lineNumber}function SO(e){return/^(?:[a-z0-9-]+\.)+[a-z]{2,}(?::\d+)?[/?#].*$/i.test(e.trim())}function CO(e){let t=e.trim();return SO(t)?`https://${t}`:e}var wO=new Set(`c.cc.cpp.cxx.h.hh.hpp.hxx.go.java.js.jsx.ts.tsx.mjs.cjs.json.jsonl.py.rb.rs.sh.bash.zsh.sql.md.mdx.pdf.txt.xml.html.css.scss.less.yaml.yml.toml.ini.conf.gradle.kt.kts.scala.proto.swift.vue.svelte.svg.png.jpg.jpeg.gif.webp`.split(`.`)),TO=new Set([`BUILD`,`BUCK`,`Dockerfile`,`Makefile`,`WORKSPACE`]);function EO(e){return kO(e)?.path??e.replace(/:(\d+)(?::(\d+)(?:-(\d+))?)?$/,``)}function DO(e){let t=e.split(/[\\/]/).filter(Boolean).pop()||e;if(TO.has(t))return!0;let n=t.match(/\.([A-Za-z0-9+_-]+)$/);return n?wO.has((n[1]||``).toLowerCase()):!1}function OO(e){try{return decodeURI(e)}catch{return e}}function kO(e){let t=OO(e.trim());return Wb(t).find(e=>e.startIndex===0&&e.length===t.length&&e.pathTarget&&DO(e.pathTarget.path))?.pathTarget??null}function AO(e,t){let n=e.trim();if(!n||n.startsWith(`#`)||SO(n))return null;let r=kO(n);if(!r)return null;let i=VD(r.path,t||``);if(!i&&!r.path.startsWith(`/`))return null;let a=!i&&r.path.startsWith(`/`)?xt(r.path):``;return!i&&!a?null:{filePath:i||a,target:{...r.lineNumber?{lineNumber:r.lineNumber,column:r.column,endColumn:r.endColumn}:{},...!i&&a?{globalRoot:!0}:{}}}}function jO(e){let t=e.trim();if(!t)return!1;let n=kO(t);if(!n)return!1;let r=n.path;return r.startsWith(`/`)||r.startsWith(`~/`)||r.startsWith(`./`)||r.startsWith(`../`)||r.includes(`/`)||!!n.lineNumber}function MO(e,t){let n=EO(e.trim()).split(/[\\/]/).filter(Boolean).pop()||e.trim();return t&&t>1?`${n}:${t}`:n}function NO(e,t){return t===`src`&&/^data:image\/(?:png|gif|jpe?g|webp|svg\+xml);base64,/i.test(e)||t===`href`&&xO(e)?e:t===`href`&&SO(e)?CO(e):bt(e)}function PO({copy:e,message:t=e.agentTranscriptUnavailable,onRetry:n,testId:r}){return(0,K.jsxs)(`div`,{className:`code-agent-transcript-terminal-sync-error`,"data-testid":r,role:`alert`,children:[(0,K.jsx)(`span`,{children:t}),(0,K.jsx)(`button`,{type:`button`,onClick:n,children:e.retry})]})}function FO({images:e,className:t,testId:n,fallbackAlt:r}){let[i,a]=(0,G.useState)(null);return(0,G.useEffect)(()=>{if(!i)return;let e=e=>{e.key===`Escape`&&a(null)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i]),e.length<=0?null:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:t,"data-testid":n,children:e.map(e=>(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-image-trigger`,"aria-label":`Open ${e.alt||r}`,onClick:()=>a(e),children:(0,K.jsx)(`img`,{src:e.url,alt:e.alt||r,loading:`lazy`,decoding:`async`})},e.id))}),i?(0,nE.createPortal)((0,K.jsxs)(`div`,{className:`code-agent-transcript-image-overlay`,"data-testid":`code-agent-transcript-image-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":i.alt||r,onClick:()=>a(null),children:[(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-image-close`,"aria-label":`Close image preview`,onClick:e=>{e.stopPropagation(),a(null)},children:(0,K.jsx)(pt,{})}),(0,K.jsx)(`img`,{src:i.url,alt:i.alt||r,onClick:e=>e.stopPropagation()})]}),document.body):null]})}function IO({images:e}){return(0,K.jsx)(FO,{images:e,className:`code-agent-transcript-user-images`,testId:`code-agent-transcript-user-images`,fallbackAlt:`Attached image`})}function LO(e){if(e.error)return e.error;if(e.resourceKind===`link`)return e.mimeType||`Resource link`;let t=e.content||``,n=t?t.split(`
185
+ `).length:0,r=t.length;return`${n===1?`1 line`:`${n} lines`} · ${r===1?`1 char`:`${r} chars`}${e.truncated?` · truncated`:``}`}function RO(e){if(!e)return``;try{let t=new URL(e);return[`http:`,`https:`].includes(t.protocol)?t.toString():``}catch{return``}}function zO({files:e}){let{workspaceRoot:t,onOpenFile:n}=(0,G.useContext)(qD);return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-agent-transcript-user-files`,"data-testid":`code-agent-transcript-user-files`,children:e.map(e=>{let r=e.content||``,i=!!r,a=e.resourceKind===`link`?RO(e.uri):``,o=e.resourceKind===`link`&&e.uri?WO({path:e.uri},t):null;return e.resourceKind===`link`?(0,K.jsxs)(`div`,{className:`code-agent-transcript-user-file code-agent-transcript-resource-link`,children:[(0,K.jsx)(BO,{filePath:e.name}),a?(0,K.jsx)(`a`,{href:a,target:`_blank`,rel:`noreferrer`,title:e.uri,children:e.name}):o&&n?(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-markdown-file-link`,title:e.uri,onClick:()=>n(o.filePath,o.target),children:e.name}):(0,K.jsx)(`span`,{title:e.uri,children:e.name}),(0,K.jsx)(`span`,{className:`code-agent-transcript-user-file-meta`,children:LO(e)})]},e.id):(0,K.jsxs)(`details`,{className:`code-agent-transcript-user-file ${e.error?`error`:``}`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(BO,{filePath:e.name}),(0,K.jsx)(`span`,{className:`code-agent-transcript-user-file-name`,title:e.name,children:e.name}),(0,K.jsx)(`span`,{className:`code-agent-transcript-user-file-meta`,children:LO(e)})]}),e.error?(0,K.jsx)(`div`,{className:`code-agent-transcript-user-file-error`,children:e.error}):i?(0,K.jsx)(`pre`,{children:r}):null]},e.id)})})}function BO({filePath:e}){let t=he(e);return(0,K.jsx)(`span`,{className:`code-agent-transcript-file-icon`,style:{WebkitMaskImage:`url("${t}")`,maskImage:`url("${t}")`},"aria-hidden":`true`})}function VO({children:e,filePath:t,lineNumber:n}){let r=MO(t,n);return(0,K.jsxs)(`span`,{title:n&&n>1?`${t}:${n}`:t,children:[(0,K.jsx)(BO,{filePath:t}),(0,K.jsx)(`span`,{className:`code-agent-transcript-file-label`,children:r})]})}function HO({images:e}){return(0,K.jsx)(FO,{images:e,className:`code-agent-transcript-process-images`,testId:`code-agent-transcript-process-images`,fallbackAlt:`Generated image`})}function UO(e){if(!e.startsWith(`file://`))return e;try{let t=new URL(e),n=decodeURIComponent(t.pathname);return t.hostname&&(n=`//${t.hostname}${n}`),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1)),n}catch{return e}}function WO(e,t){let n=UO(e.path),r=VD(n,t||``),i=!r&&n.startsWith(`/`)?xt(n):``;return!r&&!i?null:{filePath:r||i,target:{...e.lineNumber===void 0?{}:{lineNumber:e.lineNumber},...e.column===void 0?{}:{column:e.column},...e.endLineNumber===void 0?{}:{endLineNumber:e.endLineNumber},...e.endColumn===void 0?{}:{endColumn:e.endColumn},...!r&&i?{globalRoot:!0}:{}}}}function GO(e){if(!e.lineNumber)return e.path;let t=e.column?`:${e.column}`:``,n=e.endLineNumber?`-${e.endLineNumber}${e.endColumn?`:${e.endColumn}`:``}`:e.endColumn?`-${e.endColumn}`:``;return`${e.path}:${e.lineNumber}${t}${n}`}function KO(e){return e?.length?`Locations\n${e.map(GO).join(`
186
+ `)}`:``}function qO({locations:e}){let{workspaceRoot:t,onOpenFile:n}=(0,G.useContext)(qD);return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-agent-transcript-locations`,"data-testid":`code-agent-transcript-locations`,children:e.map((e,r)=>{let i=WO(e,t),a=GO(e);return!n||!i?(0,K.jsx)(`span`,{className:`code-agent-transcript-file-link`,title:a,children:a},`${e.path}-${r}`):(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-transcript-file-link`,title:a,onClick:()=>n(i.filePath,i.target),children:[(0,K.jsx)(BO,{filePath:i.filePath}),(0,K.jsx)(`span`,{className:`code-agent-transcript-file-label`,children:a})]},`${e.path}-${r}`)})})}function JO({images:e}){return(0,K.jsx)(FO,{images:e,className:`code-agent-transcript-result-images`,testId:`code-agent-transcript-result-images`,fallbackAlt:`Generated image`})}function YO({audios:e}){return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-agent-transcript-audios`,"data-testid":`code-agent-transcript-audios`,children:e.map(e=>(0,K.jsxs)(`figure`,{children:[e.name?(0,K.jsx)(`figcaption`,{children:e.name}):null,(0,K.jsx)(`audio`,{controls:!0,preload:`metadata`,src:e.url,children:e.mimeType?(0,K.jsx)(`source`,{src:e.url,type:e.mimeType}):null})]},e.id))})}function XO(e){return[String(e.terminal?.command||``).trim(),...Array.isArray(e.terminal?.args)?e.terminal.args:[]].filter(Boolean).join(` `)||e.terminalId}function ZO(e){return!Number.isFinite(e)||Number(e)<0?``:Number(e)<1e3?`${Math.round(Number(e))}ms`:`${(Number(e)/1e3).toFixed(+(Number(e)<1e4))}s`}function QO(e){let t=e.terminal?.exitStatus;return t?.signal?t.signal:Number.isInteger(t?.exitCode)?`Exit ${t?.exitCode}`:e.terminal?.released?`Released`:``}function $O(e,t){if(!e.startsWith(`Output
187
+ `)||e.includes(`
188
+
189
+ `))return!1;let n;try{n=JSON.parse(e.slice(7))}catch{return!1}if(!n||typeof n!=`object`||Array.isArray(n))return!1;let r=n,i=Object.keys(r);return i.length<=0||i.some(e=>![`exitCode`,`signal`].includes(e))?!1:t.some(e=>{let t=e.terminal?.exitStatus;return t?(!Object.prototype.hasOwnProperty.call(r,`exitCode`)||r.exitCode===t.exitCode)&&(!Object.prototype.hasOwnProperty.call(r,`signal`)||r.signal===t.signal):!1})}function ek({terminals:e,terminalStateFinal:t=!1,onStop:n,onInput:r,onResize:i}){let[a,o]=(0,G.useState)(``),[s,c]=(0,G.useState)(``),[l,u]=(0,G.useState)(``);return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-agent-transcript-terminals`,"data-testid":`code-agent-transcript-terminals`,children:e.map(e=>{let d=XO(e),f=ZO(e.terminal?.durationMs),p=QO(e),m=e.terminal?.output||``;return(0,K.jsxs)(`section`,{className:`code-agent-transcript-terminal`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`code`,{title:d,children:d}),(0,K.jsxs)(`div`,{className:`code-agent-transcript-terminal-actions`,children:[!t&&!e.terminal?.exitStatus&&!e.terminal?.released&&n?(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-terminal-stop`,"data-testid":`code-acp-terminal-stop`,"aria-label":`Stop command`,title:`Stop command`,disabled:!!s,onClick:()=>{c(e.terminalId),u(``),n(e.terminalId).catch(e=>u(e instanceof Error?e.message:`Failed to stop command`)).finally(()=>c(``))},children:s===e.terminalId?(0,K.jsx)(`span`,{className:`code-permission-switching-spinner`}):(0,K.jsx)(pt,{})}):null,m?(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-terminal-copy`,"aria-label":a===e.terminalId?`Copied terminal output`:`Copy terminal output`,title:a===e.terminalId?`Copied`:`Copy output`,onClick:()=>{Se(m).then(t=>{t&&(o(e.terminalId),window.setTimeout(()=>o(t=>t===e.terminalId?``:t),1200))})},children:a===e.terminalId?(0,K.jsx)(Ze,{}):(0,K.jsx)(ft,{})}):null]})]}),e.terminal?.cwd||f||p||e.terminal?.truncated?(0,K.jsxs)(`div`,{className:`code-agent-transcript-terminal-meta`,children:[e.terminal?.cwd?(0,K.jsx)(`span`,{title:e.terminal.cwd,children:e.terminal.cwd}):null,f?(0,K.jsx)(`span`,{children:f}):null,p?(0,K.jsx)(`span`,{children:p}):null,e.terminal?.truncated?(0,K.jsx)(`span`,{children:`Earlier output hidden`}):null]}):null,(0,K.jsx)(vE,{terminalId:e.terminalId,output:m,interactive:!!(!t&&e.terminal?.interactive&&!e.terminal.exitStatus&&!e.terminal.released&&r),onInput:r?t=>r(e.terminalId,t):void 0,onResize:i?(t,n)=>i(e.terminalId,t,n):void 0}),l?(0,K.jsx)(`div`,{className:`code-agent-transcript-terminal-error`,role:`alert`,children:l}):null]},e.terminalId)})})}function tk({item:e}){let t=String(e.detail||``).trim(),n=e.changes||[],r=!!(t||n.length>0),i=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{children:e.title||`Action`}),ik(e.status)?(0,K.jsx)(`small`,{children:e.status}):null]});return r?(0,K.jsxs)(`details`,{className:`code-agent-transcript-subagent-action`,"data-testid":`code-agent-transcript-subagent-action`,children:[(0,K.jsxs)(`summary`,{children:[i,(0,K.jsx)(mt,{})]}),t?(0,K.jsx)(`div`,{className:`detail`,children:vO(t)}):null,n.length>0?(0,K.jsx)(`div`,{className:`changes`,children:n.map((e,t)=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{title:e.path,children:e.path}),(0,K.jsxs)(`small`,{children:[e.added>0?`+${e.added}`:``,e.removed>0?` -${e.removed}`:``]})]},`${e.path}-${t}`))}):null]}):(0,K.jsx)(`div`,{className:`code-agent-transcript-subagent-action static`,children:i})}function nk({transcript:e,onStop:t}){let n=[`working`,`waiting-for-permission`,`waiting-for-input`,`interrupting`].includes(e.state||``),r=e.error?`Failed`:n?`Working`:`Completed`,i=e.turns.reduce((e,t)=>e+t.processItems.length,0),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(!1),[l,u]=(0,G.useState)(``);(0,G.useEffect)(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&o(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]);let d=(0,K.jsxs)(`div`,{className:`code-agent-transcript-subagent-entries`,children:[e.turns.map(e=>(0,K.jsxs)(`div`,{className:`code-agent-transcript-subagent-turn`,children:[e.userMessage?(0,K.jsx)(`div`,{className:`user`,children:vO(e.userMessage)}):null,e.processItems.length>0?(0,K.jsx)(`div`,{className:`actions`,children:e.processItems.map(e=>(0,K.jsx)(tk,{item:e},e.id))}):null,(0,K.jsx)(JO,{images:e.resultImages||[]}),e.finalMessage?(0,K.jsx)(`div`,{className:`assistant`,children:vO(e.finalMessage)}):null]},e.id)),e.turns.length===0?(0,K.jsx)(`div`,{className:`empty`,children:`No subagent output received yet`}):null]}),f=(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`span`,{children:e.title||`Subagent`}),(0,K.jsxs)(`span`,{className:`code-agent-transcript-subagent-meta`,title:e.sessionId,children:[e.turns.length,` `,e.turns.length===1?`turn`:`turns`,i>0?` · ${i} ${i===1?`action`:`actions`}`:``]}),(0,K.jsx)(`span`,{className:`code-agent-transcript-subagent-status ${e.error?`error`:n?`active`:``}`,children:r}),n&&t?(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-subagent-control stop`,"data-testid":`code-acp-subagent-stop`,"aria-label":`Stop subagent`,title:`Stop subagent`,disabled:s,onClick:()=>{c(!0),u(``),t().catch(e=>u(e instanceof Error?e.message:`Failed to stop subagent`)).finally(()=>c(!1))},children:s?(0,K.jsx)(`span`,{className:`code-permission-switching-spinner`}):(0,K.jsx)(pt,{})}):null,(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-subagent-control`,"data-testid":`code-acp-subagent-fullscreen`,"aria-label":a?`Close subagent details`:`Open subagent details`,title:a?`Close details`:`Open details`,onClick:()=>o(e=>!e),children:a?(0,K.jsx)(pt,{}):(0,K.jsx)(`span`,{"aria-hidden":`true`,children:`↗`})})]});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`section`,{className:`code-agent-transcript-subagent`,"data-testid":`code-agent-transcript-subagent`,children:[f,e.error?(0,K.jsx)(`div`,{className:`code-agent-transcript-subagent-error`,role:`status`,children:e.error}):null,l?(0,K.jsx)(`div`,{className:`code-agent-transcript-subagent-error`,role:`alert`,children:l}):null,d]}),a?(0,K.jsx)(`div`,{className:`code-agent-transcript-subagent-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":`Subagent details`,children:(0,K.jsxs)(`div`,{className:`code-agent-transcript-subagent-dialog`,children:[f,e.error?(0,K.jsx)(`div`,{className:`code-agent-transcript-subagent-error`,role:`status`,children:e.error}):null,l?(0,K.jsx)(`div`,{className:`code-agent-transcript-subagent-error`,role:`alert`,children:l}):null,d]})}):null]})}function rk(e){let t=e.type.replace(/[^a-z0-9_-]/gi,``).toLowerCase()||`event`,n=ak(e)?`running`:(e.status||``).replace(/[^a-z0-9_-]/gi,``).toLowerCase();return[`code-agent-transcript-process-item`,t,n?`status-${n}`:``].filter(Boolean).join(` `)}function ik(e){let t=String(e||``).trim().toLowerCase();return!!t&&t!==`completed`&&t!==`success`}function ak(e){let t=String(e.status||``).trim().replace(/[_-]/g,``).toLowerCase();return[`running`,`inprogress`,`pending`,`started`,`active`].includes(t)}function ok(e){return[`failed`,`rejected`,`cancelled`,`canceled`].includes(String(e.status||``).trim().toLowerCase())||e.type===`error`}function sk(e){return e.scrollHeight-e.clientHeight-e.scrollTop}function ck(e){return sk(e)<=sO}function lk(e){let t=window.getSelection();return!t||t.isCollapsed||t.rangeCount===0?!1:!!(t.anchorNode&&e.contains(t.anchorNode)||t.focusNode&&e.contains(t.focusNode))}function uk(e){let t=e.split(`
190
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.match(/^\[(x|>| )\]\s+(.+)$/i);if(!t)return null;let n=(t[1]||``).toLowerCase();return{status:n===`x`?`completed`:n===`>`?`running`:`pending`,text:t[2]||``}});return t.some(e=>e===null)?null:t}function dk(e){return[`message`,`agent-message`,`progress`,`reasoning`,`thought`,`hook`,`warning`,`error`,`review`,`rollback`,`compaction`,`subagent`].includes(e.type)}function fk(e){return dk(e)||e.type===`plan`||e.type===`user-steer`}function pk(e){return!fk(e)}function mk(e,t){if(t===`acp`)return ID(e);let n=[],r=[],i=()=>{r.length>0&&n.push({kind:`group`,id:`group:${r[0]?.id||``}`,items:r}),r=[]};for(let t of e){if(pk(t)){r.push(t);continue}i(),n.push({kind:`item`,item:t})}return i(),n}function hk(e,t){let n=e.flatMap(e=>e.kind===`item`?bk(e.item)?[e.item]:[]:t===`inProgress`?e.items.filter(e=>!ok(e)&&!e.collaboration):[]),r=new Set;n.forEach((e,t)=>{bk(e)&&r.add(t)});for(let e=n.length-1;e>=0;--e)if(ak(n[e])){r.add(e);break}return{items:n.filter((e,t)=>r.has(t))}}function gk(e,t){return ok(e)?t.agentTranscriptActionFailed(e.title):e.title}function _k(e){let t=e.filter(e=>[`failed`,`rejected`,`cancelled`,`canceled`].includes(String(e.status||``).toLowerCase())).length;if(t>0)return t===1?`Action failed`:`${t} actions failed`;let n=e.reduce((e,t)=>{let n=t.type;return e[n]=(e[n]||0)+1,e},{}),r=n.command||0,i=(n[`file-read`]||0)+(n.read||0),a=(n[`web-search`]||0)+(n.search||0),o=n.patch||0;if(e.length===i+a&&(i>0||a>0)){let e=[];i>0&&e.push(i===1?`read a file`:`read ${i} files`),a>0&&e.push(`searched code`);let t=e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} and ${e[e.length-1]}`;return t?t.charAt(0).toUpperCase()+t.slice(1):`Completed actions`}return e.length===r?r===1?`Ran command`:`Ran ${r} commands`:e.length===i?i===1?`Read a file`:`Read ${i} files`:e.length===a?a===1?`Searched code`:`Searched ${a} times`:o>0&&o===e.length?o===1?`Edited files`:`Edited files ${o} times`:r>0?`Ran ${e.length} actions`:`Completed ${e.length} actions`}function vk(e,t,n){return!!(t||n||(e.images||[]).length>0||(e.audios||[]).length>0||(e.files||[]).length>0||(e.locations||[]).length>0||(e.terminals||[]).length>0||(e.terminalIds||[]).length>0||e.detailTruncated===!0||e.subagentSessionId||e.subagentTranscript)}function yk(e){return e.type===`patch`}function bk(e){return e.type===`user-steer`}function xk(e){return String(e.detail||``).split(`
191
+ `).map(e=>e.trim()).filter(Boolean).filter(e=>!e.startsWith(`Success.`)).filter(Sk).slice(0,16)}function Sk(e){let t=e.trim();return/^(add|added|delete|deleted|update|updated|move|moved|rename|renamed)\s+.+/i.test(t)||/^[AMDRC]\s+.+/.test(t)}function Ck(e){let t=e.trim(),n=t.match(/^([AMDRC])\s+(.+)$/);if(n)return{kind:n[1]||``,path:n[2]||t,added:``,removed:``};let r=t.match(/\s(\+\d+)(?:\s(-\d+))?$/),i=r?.[1]||``,a=r?.[2]||``,o=r?t.slice(0,r.index).trim():t,s=o.match(/^(add|added|delete|deleted|update|updated|move|moved|rename|renamed)\s+(.+)$/i);return{kind:s?.[1]||``,path:s?.[2]||o,added:i,removed:a}}function wk(e){return String(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`).trim()}function Tk(e,t){let n=wk(e),r=wk(t||``).replace(/\/+$/,``);if(!n||!r)return n;let i=[r];r.startsWith(`/private/`)&&i.push(r.slice(8)),(r.startsWith(`/var/`)||r.startsWith(`/tmp/`))&&i.push(`/private${r}`);for(let e of i){if(n===e)return``;if(n.startsWith(`${e}/`))return n.slice(e.length+1)}return n}function Ek(e,t){return Tk(e.path,t)||e.path}function Dk(e){return!!(e.added||e.removed)}function Ok(e,t){let n=[],r=new Map;for(let i of e){let e=Ek(i,t),a=e||i.path,o=r.get(a);if(o===void 0){r.set(a,n.length),n.push({...i,path:e||i.path});continue}let s=n[o];s&&(Dk(i)||!Dk(s))&&(n[o]={...i,path:e||i.path})}return n}function kk(e,t){return Ok(e.map(e=>({kind:e.kind,path:e.path,added:e.added>0?`+${e.added}`:``,removed:e.removed>0?`-${e.removed}`:``})),t)}function Ak(e,t){return Ok(e.flatMap(e=>e.changes?.length?kk(e.changes):xk(e).map(Ck)),t)}function jk(e,t){return t?e===1?`Failed editing 1 file`:`Failed editing ${e} files`:e===1?`Edited 1 file`:`Edited ${e} files`}function Mk(e,t){return t?jk(e,t):e===1?`1 file changed`:`${e} files changed`}function Nk(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)?`added`:e.startsWith(`-`)&&!e.startsWith(`---`)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`Index:`)||e.startsWith(`===`)?`meta`:``}function Pk(e,t){let n=e.closest(`.code-agent-transcript-scroll`),r=e.getBoundingClientRect().top;t(),window.requestAnimationFrame(()=>{if(!n?.isConnected||!e.isConnected)return;let t=e.getBoundingClientRect().top-r;Math.abs(t)<.5||(n.scrollTop+=t)})}function Fk({item:e}){let t=(e.detail||e.title||``).trim(),n=e.images||[],r=e.audios||[],i=e.files||[],a=e.terminals||[];return!t&&n.length<=0&&r.length<=0&&i.length<=0&&a.length<=0?null:(0,K.jsx)(`div`,{className:`code-agent-transcript-steer`,"data-testid":`code-agent-transcript-steer`,children:(0,K.jsxs)(`div`,{className:`code-agent-transcript-user code-agent-transcript-steer-bubble`,children:[t?(0,K.jsx)(`div`,{children:vO(t)}):null,(0,K.jsx)(IO,{images:n}),(0,K.jsx)(YO,{audios:r}),(0,K.jsx)(zO,{files:i}),(0,K.jsx)(ek,{terminals:a}),(0,K.jsx)(dO,{timestamp:e.createdAt,kind:`steer`})]})})}function Ik(e,t){return e===`started`?t.agentTranscriptCollaborationStarted:e===`updated`?t.agentTranscriptCollaborationUpdated:e===`finished`?t.agentTranscriptCollaborationActionCompleted:e===`interrupted`?t.agentTranscriptCollaborationPauseRequested:e===`failed`?t.agentTranscriptCollaborationFailed:t.agentTranscriptCollaborationRecorded}function Lk(e,t){return e===`pending`?t.agentTranscriptCollaborationPending:e===`running`?t.agentTranscriptCollaborationInProgress:e===`completed`?t.agentTranscriptCollaborationCompleted:e===`paused`?t.agentTranscriptCollaborationInterrupted:e===`failed`?t.agentTranscriptCollaborationFailed:e===`closed`?t.agentTranscriptCollaborationClosed:t.agentTranscriptCollaborationNoFinalState}function Rk({icon:e}){return(0,K.jsx)([lt,ct,rt,it,st,Ke][e]||lt,{})}function zk({agents:e,renderProcessItem:t,copy:n,disclosureScope:r,openAgentIds:i,setOpenAgentIds:a,openActivityIds:o,setOpenActivityIds:s}){let[c,l]=(0,G.useState)({}),[u,d]=(0,G.useState)({});if(e.length===0)return null;let f=new Map(e.map(e=>[e.id,e])),p=new Map,m=[],h=e=>{let t=new Set([e.id]),n=e.parentThreadId;for(;n&&f.has(n);){if(t.has(n))return!0;t.add(n),n=f.get(n)?.parentThreadId}return!1};for(let t of e)if(t.parentThreadId&&f.has(t.parentThreadId)&&!h(t)){let e=p.get(t.parentThreadId)||[];e.push(t),p.set(t.parentThreadId,e)}else m.push(t);let g=(e,f)=>{let m=`${r}:${e.id}`,h=i.has(m),_=Lk(e.status,n),v=p.get(e.id)||[],y=e.activities.length>0||v.length>0,b=Math.max(8,c[e.id]||8),x=e.activities.slice(-b),S=e.activities.length-x.length,C=()=>{s(t=>{let n=new Set(t);return e.activities.forEach(e=>n.delete(`${r}:${e.id}`)),n})};return(0,K.jsxs)(`section`,{className:`code-agent-transcript-collaboration-group ${h?`expanded`:``}`,"data-testid":`code-agent-transcript-collaboration-group`,"data-agent-thread-id":e.threadId,"data-agent-icon":e.icon,"data-agent-depth":f,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-transcript-collaboration-summary ${y?``:`static`}`,"data-testid":`code-agent-transcript-collaboration-summary`,"aria-expanded":y?h:void 0,disabled:!y,title:`${e.task||e.name}${e.task&&e.task!==e.name?` · ${e.name}`:``} · ${_} · ${n.agentTranscriptProcessCount(e.events.length)}`,onClick:e=>{y&&(e.stopPropagation(),Pk(e.currentTarget,()=>{a(e=>{let t=new Set(e);return t.has(m)?t.delete(m):t.add(m),t}),h&&C()}))},children:[(0,K.jsxs)(`span`,{className:`code-agent-transcript-collaboration-agent tone-${e.tone}`,children:[(0,K.jsx)(Rk,{icon:e.icon}),(0,K.jsxs)(`span`,{className:`code-agent-transcript-collaboration-agent-labels`,children:[(0,K.jsx)(`span`,{children:e.task||e.name}),e.task&&e.task!==e.name?(0,K.jsx)(`small`,{children:e.name}):null]})]}),(0,K.jsx)(`span`,{className:`code-agent-transcript-collaboration-action ${e.status}`,children:_}),(0,K.jsxs)(`span`,{className:`code-agent-transcript-collaboration-count`,children:[n.agentTranscriptProcessCount(e.events.length),v.length>0?` · ${n.agentTranscriptCollaborationChildCount(v.length)}`:``]}),y?(0,K.jsx)(mt,{className:`code-agent-transcript-chevron`}):null]}),h?(0,K.jsxs)(`div`,{className:`code-agent-transcript-collaboration-events`,children:[S>0?(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-collaboration-activities-earlier`,"data-testid":`code-agent-transcript-collaboration-activities-earlier`,onClick:t=>{t.stopPropagation(),l(t=>({...t,[e.id]:Math.min(e.activities.length,b+20)}))},children:n.agentTranscriptCollaborationEarlierActivities(Math.min(20,S))}):null,x.map(i=>{let a=`${r}:${i.id}`,c=o.has(a),l=Math.max(8,u[i.id]||8),f=i.processItemIds.slice(-l),p=i.processItemIds.length-f.length;return(0,K.jsxs)(`div`,{className:`code-agent-transcript-collaboration-activity ${c?`expanded`:``}`,"data-testid":`code-agent-transcript-collaboration-activity`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-transcript-collaboration-event`,"data-testid":`code-agent-transcript-collaboration-event`,"data-process-item-id":i.processItemId,"aria-expanded":c,title:i.title||i.message||e.name,onClick:e=>{e.stopPropagation(),Pk(e.currentTarget,()=>{s(e=>{let t=new Set(e);return t.has(a)?t.delete(a):t.add(a),t})})},children:[(0,K.jsx)(`span`,{className:`code-agent-transcript-collaboration-action ${i.action}`,children:Ik(i.action,n)}),(0,K.jsx)(`span`,{className:`code-agent-transcript-collaboration-event-detail`,children:i.message||(i.action===`started`||i.action===`updated`||i.action===`recorded`?e.task||e.name:i.title||e.name)}),i.count>1?(0,K.jsx)(`span`,{className:`code-agent-transcript-collaboration-event-count`,children:n.agentTranscriptProcessCount(i.count)}):null,(0,K.jsx)(mt,{className:`code-agent-transcript-chevron`})]}),c?(0,K.jsxs)(`div`,{className:`code-agent-transcript-collaboration-evidence`,"data-testid":`code-agent-transcript-collaboration-evidence`,children:[p>0?(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-collaboration-earlier`,"data-testid":`code-agent-transcript-collaboration-earlier`,onClick:e=>{e.stopPropagation(),d(e=>({...e,[i.id]:Math.min(i.processItemIds.length,l+20)}))},children:n.agentTranscriptCollaborationEarlierEvidence(Math.min(20,p))}):null,f.map(e=>t(e))]}):null]},i.id)}),v.length>0?(0,K.jsx)(`div`,{className:`code-agent-transcript-collaboration-children`,children:v.map(e=>g(e,f+1))}):null]}):null]},e.id)};return(0,K.jsxs)(`div`,{className:`code-agent-transcript-collaboration`,"data-testid":`code-agent-transcript-collaboration`,children:[(0,K.jsxs)(`div`,{className:`code-agent-transcript-collaboration-heading`,children:[(0,K.jsx)($e,{}),(0,K.jsx)(`span`,{children:n.agentTranscriptCollaborationHeading})]}),m.map(e=>g(e,0))]})}function Bk({item:e,title:t,showStatus:n=!0,copy:r,copied:i,detailOpen:a,onToggle:o,onCopy:s,onStopTerminal:c,onInputTerminal:l,onResizeTerminal:u,terminalOutcomeSyncFailed:d=!1,onRetryTerminalOutcome:f,onStopSubagent:p}){if(bk(e))return(0,K.jsx)(Fk,{item:e});let m=e.images||[],h=e.audios||[],g=e.files||[],_=e.locations||[],v=e.terminals||[],y=e.detail&&e.detail.trim()!==e.title.trim()?e.detail:``,b=y&&$O(y,v)?``:y,x=d&&e.terminalIds?.length?``:b,S=!!y||_.length>0,C=!!x,w=e.type===`plan`&&x?uk(x):null,T=vk(e,x,w),E=t||e.title,D=(0,K.jsxs)(K.Fragment,{children:[w?(0,K.jsx)(`ol`,{className:`code-agent-transcript-plan-list`,children:w.map((e,t)=>(0,K.jsx)(`li`,{className:e.status,"aria-current":e.status===`running`?`step`:void 0,children:(0,K.jsx)(`span`,{children:e.text})},`${t}-${e.text}`))}):null,(0,K.jsx)(HO,{images:m}),(0,K.jsx)(YO,{audios:h}),(0,K.jsx)(zO,{files:g}),(0,K.jsx)(qO,{locations:_}),d?(0,K.jsxs)(`div`,{className:`code-agent-transcript-terminal-sync-error`,"data-testid":`code-acp-terminal-sync-error`,role:`alert`,children:[(0,K.jsx)(`span`,{children:r.agentTranscriptTerminalStatusUnavailable}),f?(0,K.jsx)(`button`,{type:`button`,onClick:()=>f(e.id),children:r.agentTranscriptRetryTerminalStatus}):null]}):(0,K.jsx)(ek,{terminals:v,terminalStateFinal:!ak(e),onStop:c?t=>c(e.id,t):void 0,onInput:l?(t,n)=>l(e.id,t,n):void 0,onResize:u?(t,n,r)=>u(e.id,t,n,r):void 0}),e.subagentTranscript?(0,K.jsx)(nk,{transcript:e.subagentTranscript,onStop:e.subagentSessionId&&p?()=>p(e.subagentSessionId||``):void 0}):null,!w&&C&&dk(e)?(0,K.jsx)(`div`,{className:`code-agent-transcript-process-detail`,children:vO(x)}):!w&&C?(0,K.jsx)(`pre`,{children:x}):null]});return(0,K.jsxs)(`section`,{className:rk(e),"data-testid":`code-agent-transcript-process-item`,"data-process-item-id":e.id,"data-type":e.type,"data-status":e.status||``,children:[(0,K.jsxs)(`div`,{className:`code-agent-transcript-process-title`,children:[T?(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-transcript-process-title-toggle`,"data-testid":`code-agent-transcript-process-item-toggle`,"aria-expanded":a,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),Pk(t.currentTarget,()=>o(e.id))},onKeyDown:t=>{t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),Pk(t.currentTarget,()=>o(e.id)))},children:[(0,K.jsx)(`span`,{className:`code-agent-transcript-process-title-text`,children:E}),n&&ik(e.status)?(0,K.jsx)(`span`,{className:`code-agent-transcript-process-status`,children:e.status}):null,(0,K.jsx)(mt,{className:`code-agent-transcript-process-item-chevron`})]}):(0,K.jsxs)(`span`,{className:`code-agent-transcript-process-title-static`,children:[(0,K.jsx)(`span`,{className:`code-agent-transcript-process-title-text`,children:E}),n&&ik(e.status)?(0,K.jsx)(`span`,{className:`code-agent-transcript-process-status`,children:e.status}):null]}),S?(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-copy ${i?`copied`:``}`,"aria-label":i?r.agentTranscriptCopiedDetails:r.agentTranscriptCopyDetails,title:i?r.agentTranscriptCopiedDetails:r.agentTranscriptCopyDetails,"data-tooltip":i?r.agentTranscriptCopiedDetails:r.agentTranscriptCopyDetails,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:()=>s(e),children:i?(0,K.jsx)(Ze,{}):(0,K.jsx)(ft,{})}):null]}),T&&a?D:null]})}function Vk(e){return(0,K.jsx)(_t,{label:`transcript tool`,resetKey:[e.item.id,e.item.status||``,String(e.item.detail?.length||0),e.item.detailTruncated?`truncated`:`complete`,String(e.item.terminals?.length||0),String(e.item.subagentTranscript?.turns.length||0)].join(`\0`),fallback:(t,n)=>(0,K.jsx)(PO,{copy:e.copy,message:`${e.item.title}: ${e.copy.agentTranscriptUnavailable}`,onRetry:n,testId:`code-agent-transcript-tool-render-error`}),children:(0,K.jsx)(Et,{surface:`transcript-tool`,identity:e.item.id,children:(0,K.jsx)(Bk,{...e})})})}function Hk({agents:e,processItems:t,copy:n,disclosureScope:r,openAgentIds:i,setOpenAgentIds:a,openActivityIds:o,setOpenActivityIds:s,onLoadProcessItemDetail:c,onStopTerminal:l,onInputTerminal:u,onResizeTerminal:d,onStopSubagent:f}){let[p,m]=(0,G.useState)({}),[h,g]=(0,G.useState)(()=>new Set),[_,v]=(0,G.useState)(``),y=(0,G.useMemo)(()=>t.map(e=>Object.prototype.hasOwnProperty.call(p,e.id)?{...e,detail:p[e.id]?.detail||``,terminals:p[e.id]?.terminals,subagentTranscript:p[e.id]?.subagentTranscript,detailTruncated:!1}:e),[p,t]),b=(0,G.useMemo)(()=>new Map(y.map(e=>[e.id,e])),[y]),x=(0,G.useCallback)(async e=>{if(!c)return;let t=await c(e);m(n=>({...n,[e]:t}))},[c]),S=(0,G.useCallback)(e=>{let t=!h.has(e),n=b.get(e);t&&n&&(n.detailTruncated||n.terminalIds?.length||n.subagentSessionId)&&x(e).catch(()=>{}),g(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[b,x,h]),C=(0,G.useCallback)(e=>{(e.detailTruncated&&c?c(e.id):Promise.resolve({detail:e.detail||``})).then(t=>Se([e.title,t.detail,KO(e.locations)].filter(Boolean).join(`
192
+
193
+ `))).then(t=>{t&&(v(e.id),window.setTimeout(()=>v(t=>t===e.id?``:t),1200))}).catch(()=>{})},[c]),w=(0,G.useCallback)(async(e,t)=>{l&&(await l(t),await x(e))},[x,l]),T=(0,G.useCallback)(async(e,t,n)=>{u&&(await u(t,n),await x(e))},[x,u]),E=(0,G.useCallback)(async(e,t,n,r)=>{await d?.(t,n,r)},[d]);return(0,K.jsx)(zk,{agents:e,disclosureScope:r,openAgentIds:i,setOpenAgentIds:a,openActivityIds:o,setOpenActivityIds:s,renderProcessItem:e=>{let t=b.get(e);return t?(0,K.jsx)(Vk,{item:t,copy:n,copied:_===t.id,detailOpen:h.has(t.id),onToggle:S,onCopy:C,onStopTerminal:w,onInputTerminal:T,onResizeTerminal:E,onStopSubagent:f},t.id):null},copy:n})}function Uk({item:e,markdownComponents:t,copy:n}){let r=String(e.detail||``).trim();return r?(0,K.jsx)(`div`,{className:`code-acp-progress-update code-markdown-preview`,"data-testid":`code-acp-progress-update`,children:(0,K.jsx)(_t,{label:`transcript progress Markdown`,resetKey:r,fallback:(e,t)=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(PO,{copy:n,onRetry:t,testId:`code-agent-transcript-markdown-render-error`}),(0,K.jsx)(`pre`,{children:r})]}),children:(0,K.jsx)(Et,{surface:`transcript-markdown`,identity:e.id,children:(0,K.jsx)(yt,{remarkPlugins:[vt,kt],rehypePlugins:[Ct,At],components:t,skipHtml:!0,urlTransform:NO,children:r})})})}):null}function Wk({plan:e}){let[t,n]=(0,G.useState)(!0),r=uk(String(e.detail||``)),i=e.totalSteps?`${e.completedSteps||0}/${e.totalSteps}`:``;return(0,K.jsxs)(`aside`,{className:`code-agent-transcript-plan-driver ${t?`expanded`:``}`,"data-testid":`code-agent-transcript-plan-driver`,"aria-label":`Current plan`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-transcript-plan-driver-summary`,"aria-expanded":t,onClick:()=>n(e=>!e),children:[(0,K.jsx)(`span`,{children:`Plan`}),i?(0,K.jsx)(`small`,{children:i}):null,(0,K.jsx)(mt,{className:`code-agent-transcript-plan-driver-chevron`})]}),t?r?(0,K.jsx)(`ol`,{className:`code-agent-transcript-plan-list`,children:r.map((e,t)=>(0,K.jsx)(`li`,{className:e.status,"aria-current":e.status===`running`?`step`:void 0,children:(0,K.jsx)(`span`,{children:e.text})},`${t}:${e.text}`))}):(0,K.jsx)(`div`,{className:`code-agent-transcript-plan-driver-detail`,children:e.detail}):null]})}function Gk({groupId:e,items:t,summaryLabel:n,copy:r,copiedItemId:i,detailOpen:a,openProcessItemIds:o,onToggleGroup:s,onToggleItem:c,onCopy:l,onStopTerminal:u,onInputTerminal:d,onResizeTerminal:f,terminalOutcomeSyncFailedItemIds:p,onRetryTerminalOutcome:m,onStopSubagent:h}){return(0,K.jsxs)(`section`,{className:`code-agent-transcript-process-group ${t.some(ak)?`running`:``}`,"data-testid":`code-agent-transcript-process-group`,"data-count":t.length,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-transcript-process-group-summary`,"data-testid":`code-agent-transcript-process-group-toggle`,"aria-expanded":a,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),Pk(t.currentTarget,()=>s(e))},onKeyDown:t=>{t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),Pk(t.currentTarget,()=>s(e)))},children:[(0,K.jsx)(`span`,{className:`code-agent-transcript-process-title-text`,children:n||_k(t)}),(0,K.jsx)(mt,{className:`code-agent-transcript-process-item-chevron`})]}),a?(0,K.jsx)(`div`,{className:`code-agent-transcript-process-group-list`,children:t.map(e=>(0,K.jsx)(Vk,{item:e,copy:r,copied:i===e.id,detailOpen:o.has(e.id),onToggle:c,onCopy:l,onStopTerminal:u,onInputTerminal:d,onResizeTerminal:f,terminalOutcomeSyncFailed:p.has(e.id),onRetryTerminalOutcome:m,onStopSubagent:h},e.id))}):null]})}function Kk({items:e,copy:t,onLoadPatchChanges:n,source:i,workspaceRoot:a,gitDiffTarget:o}){let[s,c]=(0,G.useState)(!1),[l,u]=(0,G.useState)(null),[d,f]=(0,G.useState)(``),p=(0,G.useMemo)(()=>Object.fromEntries(e.flatMap(e=>(e.changes||[]).flatMap(e=>e.decision?[[Tk(e.path,a)||e.path,e.decision]]:[]))),[e,a]),m=Ak(e,a),h=l?kk(l,a):[],g=new Map(h.map(e=>[e.path,e])),_=l?[...m.map(e=>g.get(e.path)||e),...h.filter(e=>!m.some(t=>t.path===e.path))]:m,v=e.some(e=>e.status===`failed`),y=_.reduce((e,t)=>e+Number(t.added.replace(`+`,``)||0),0),b=_.reduce((e,t)=>e+Number(t.removed.replace(`-`,``)||0),0),x=Mk(_.length,v),S=e.flatMap(e=>e.changes||[]),C=m.length>0&&m.every(e=>S.some(t=>(Tk(t.path,a)||t.path)===e.path&&typeof t.diff==`string`)),w=new Set((l||[]).map(e=>e.path)),T=l?[...l,...S.filter(e=>!w.has(Tk(e.path,a)||e.path))]:S,E=i===`acp`?_.map(e=>Tk(e.path,a)).filter(e=>e&&!e.startsWith(`/`)&&!e.split(`/`).includes(`..`)):[],D=(0,G.useCallback)(()=>{if(i===`acp`){if(c(!0),l||C||!n)return;f(``),n(e.map(e=>e.id)).then(u).catch(e=>f(e instanceof Error?e.message:t.agentTranscriptUnavailable));return}if(!a)return;let o=new URLSearchParams({root:a});window.open(r(`/review?${o.toString()}`),`_blank`,`noopener,noreferrer`)},[t.agentTranscriptUnavailable,l,C,e,n,i,a]),O=(0,G.useCallback)(()=>{!a||o.kind===`unavailable`||window.open(r(`/review?${KD(a,o).toString()}`),`_blank`,`noopener,noreferrer`)},[o,a]);return(0,K.jsxs)(`section`,{className:`code-agent-transcript-result-card ${v?`failed`:``}`,"data-testid":`code-agent-transcript-result-card`,children:[(0,K.jsxs)(`div`,{className:`code-agent-transcript-result-header`,children:[(0,K.jsx)(`div`,{className:`code-agent-transcript-result-summary`,"data-testid":`code-agent-transcript-result-summary`,"aria-label":x,children:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{children:x}),y?(0,K.jsxs)(`span`,{className:`added`,children:[`+`,y]}):null,b?(0,K.jsxs)(`span`,{className:`removed`,children:[`-`,b]}):null]})}),a&&_.length>0?(0,K.jsxs)(`div`,{className:`code-agent-transcript-result-actions`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-result-review`,"aria-label":`${t.agentTranscriptReviewChanges}: ${E.length} workspace ${E.length===1?`file`:`files`}`,onClick:D,children:t.agentTranscriptReviewChanges}),o.kind===`unavailable`?null:(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-result-review git-diff`,onClick:O,children:o.kind===`last-commit`?t.agentTranscriptGitDiffLastCommit:t.agentTranscriptGitDiff})]}):null]}),i===`acp`&&s?(0,nE.createPortal)((0,K.jsx)(`div`,{className:`code-agent-transcript-change-review-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":t.agentTranscriptReviewChanges,onMouseDown:()=>c(!1),children:(0,K.jsxs)(`div`,{className:`code-agent-transcript-change-review-dialog`,onMouseDown:e=>e.stopPropagation(),children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`span`,{children:x}),y?(0,K.jsxs)(`span`,{className:`added`,children:[`+`,y]}):null,b?(0,K.jsxs)(`span`,{className:`removed`,children:[`-`,b]}):null,(0,K.jsx)(`button`,{type:`button`,"aria-label":t.close,title:t.close,onClick:()=>c(!1),children:(0,K.jsx)(pt,{})})]}),(0,K.jsxs)(`div`,{className:`code-agent-transcript-change-review-body`,"data-testid":`code-agent-transcript-result-details`,children:[!C&&!l&&!d?(0,K.jsx)(`div`,{className:`code-agent-transcript-result-loading`,children:t.agentTranscriptLoadingChanges}):null,d?(0,K.jsxs)(`div`,{className:`code-agent-transcript-result-error`,role:`alert`,children:[(0,K.jsx)(`span`,{children:t.agentTranscriptChangesUnavailable}),(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{children:t.agentTranscriptTechnicalDetails}),(0,K.jsx)(`code`,{children:d})]})]}):null,l||C?_.map(n=>{let r=Ek(n,a),i=T.filter(e=>(Tk(e.path,a)||e.path)===r),o=p[r];return(0,K.jsxs)(`section`,{className:`code-agent-transcript-change-review-file`,children:[(0,K.jsxs)(`header`,{title:r,children:[(0,K.jsx)(`span`,{className:`code-agent-transcript-result-file-path`,children:r}),(0,K.jsxs)(`span`,{className:`code-agent-transcript-result-file-stats`,children:[n.added?(0,K.jsx)(`span`,{className:`added`,children:n.added}):null,n.removed?(0,K.jsx)(`span`,{className:`removed`,children:n.removed}):null]})]}),i.map((e,t)=>e.diff?(0,K.jsx)(`pre`,{className:`code-agent-transcript-result-diff`,children:e.diff.split(`
194
+ `).map((e,t)=>(0,K.jsxs)(`span`,{className:Nk(e),children:[e,`
195
+ `]},`${t}:${e}`))},`${r}:${t}`):null),o?(0,K.jsx)(`div`,{className:`code-agent-transcript-result-decision`,"data-testid":`code-acp-patch-decision`,children:(0,K.jsx)(`span`,{children:o===`reverted`?t.agentTranscriptChangeReverted:t.agentTranscriptChangeKept})}):null]},`${e[0]?.id||`patch`}:${r}`)}):null]})]})}),document.body):null]})}function qk({turn:e,copy:t,onOpenFile:n,onOpenUrlInFarming:r,workspaceRoot:i,processOpen:a,groupProcessActions:o,source:s,onToggleProcess:c,onLoadProcessItemDetail:l,onLoadPatchChanges:u,gitDiffTarget:d,onStopTerminal:f,onInputTerminal:p,onResizeTerminal:m,onStopSubagent:h,subagentStates:g,openCollaborationAgentIds:_,setOpenCollaborationAgentIds:v,openCollaborationActivityIds:y,setOpenCollaborationActivityIds:b,onFork:x}){let S=(0,G.useRef)(null),[C,w]=(0,G.useState)({}),T=(0,G.useRef)(new Set),E=(0,G.useMemo)(()=>e.processItems.map(e=>Object.prototype.hasOwnProperty.call(C,e.id)?{...e,detail:C[e.id]?.detail||``,terminals:C[e.id]?.terminals,subagentTranscript:C[e.id]?.subagentTranscript,detailTruncated:!1}:e),[C,e.processItems]),D=(0,G.useMemo)(()=>E.filter(bk),[E]),O=E.length>0,k=E.filter(yk),A=e.userImages||[],j=e.userAudios||[],M=e.userFiles||[],N=e.resultImages||[],P=e.resultAudios||[],F=e.resultFiles||[],[ee,I]=(0,G.useState)(``),[L,te]=(0,G.useState)(!1),[R,ne]=(0,G.useState)(!1),re=(0,G.useRef)(!1),[z,ie]=(0,G.useState)(()=>new Set),[ae,B]=(0,G.useState)(()=>new Set),oe=(0,G.useRef)(new Set),V=(0,G.useRef)(new Set),se=(0,G.useRef)(new Set),[,ce]=(0,G.useState)(0),le=(0,G.useMemo)(()=>_E(E,g),[E,g]),ue=(0,G.useMemo)(()=>new Set(le.flatMap(e=>e.events.map(e=>e.processItemId))),[le]),fe=(0,G.useMemo)(()=>E.filter(e=>!ue.has(e.id)),[ue,E]),pe=(0,G.useMemo)(()=>({...e,processItems:fe}),[fe,e]),me=fe.length>0,he=(0,G.useMemo)(()=>o?mk(fe,s):fe.map(e=>({kind:`item`,item:e})),[o,fe,s]),ge=(0,G.useMemo)(()=>hk(he,e.status),[he,e.status]),H=e.status===`inProgress`?[...fe].reverse().find(e=>e.type===`compaction`&&ak(e)):void 0,_e=de(),ve=(0,G.useMemo)(()=>yO(e.finalMessage),[e.finalMessage]),ye=e.status===`inProgress`&&!ve&&ge.items.length===0&&le.length===0&&(!!e.userMessage||A.length>0||j.length>0||M.length>0||D.length>0||O);(0,G.useEffect)(()=>{if(e.status!==`inProgress`||!e.startedAt)return;let t=window.setInterval(()=>ce(Date.now()),3e4);return()=>window.clearInterval(t)},[e.startedAt,e.status]);let be=e.status===`inProgress`?lO(e.startedAt):``,xe=E===e.processItems?e:{...e,processItems:E},U=s===`acp`?pO(xe,t):t.agentTranscriptWorking,Ce=ge.items.length>0?t.agentTranscriptProcess:U,we=s===`acp`?mO(xe,t):``,Te=s===`acp`?hO(xe,t):``,Ee=H?t.agentTranscriptCompactingContext:e.status===`inProgress`&&be?t.agentTranscriptWorkingFor(be):gO(pe,t,Ce,Te),De=(0,G.useCallback)(async(e,t=!1)=>{if(!e.detailTruncated&&!e.terminalIds?.length&&!e.subagentSessionId||!l)return{detail:e.detail||``,terminals:e.terminals,subagentTranscript:e.subagentTranscript};if(!t&&Object.prototype.hasOwnProperty.call(C,e.id))return C[e.id]||{detail:e.detail||``};if(T.current.has(e.id))return{detail:e.detail||``};T.current.add(e.id);try{let t=await l(e.id);return w(n=>({...n,[e.id]:t})),t}finally{T.current.delete(e.id)}},[C,l]),Oe=(0,G.useCallback)(e=>{if(se.current.has(e.id))return;se.current.add(e.id),V.current.add(e.id),B(t=>{if(!t.has(e.id))return t;let n=new Set(t);return n.delete(e.id),n});let t=()=>{se.current.delete(e.id),B(t=>new Set([...t,e.id]))},n=r=>{De(e,!0).then(i=>{if(!i.terminals?.some(e=>!!e.terminal?.exitStatus||e.terminal?.released)){if(r<2){window.setTimeout(()=>n(r+1),500*(r+1));return}t();return}se.current.delete(e.id),oe.current.delete(e.id)}).catch(()=>{if(r<2){window.setTimeout(()=>n(r+1),500*(r+1));return}t()})};n(0)},[De]);(0,G.useEffect)(()=>{E.filter(e=>e.terminalIds?.length&&ak(e)).forEach(e=>oe.current.add(e.id)),E.filter(e=>e.terminalIds?.length&&!ak(e)&&oe.current.has(e.id)&&!V.current.has(e.id)).forEach(Oe)},[Oe,E]),(0,G.useEffect)(()=>{let e=E.filter(e=>e.terminalIds?.length&&ak(e)&&z.has(e.id));if(e.length===0)return;let t=()=>e.forEach(e=>{De(e,!0).catch(()=>{})});t();let n=window.setInterval(t,1e3);return()=>window.clearInterval(n)},[De,z,E]);let ke=(0,G.useCallback)(e=>{De(e).then(t=>{let n=[e.title,t.detail,KO(e.locations)].filter(Boolean).join(`
196
+
197
+ `);if(n)return Se(n)}).then(t=>{t&&(I(e.id),window.setTimeout(()=>I(t=>t===e.id?``:t),1200))}).catch(()=>{})},[De]),Ae=(0,G.useCallback)(()=>{let e=ve.trim();e&&Se(e).then(e=>{e&&(te(!0),window.setTimeout(()=>te(!1),1200))})},[ve]),je=(0,G.useCallback)(async()=>{if(!(!x||re.current)){re.current=!0,ne(!0);try{await x()}finally{re.current=!1,ne(!1)}}},[x]),Me=(0,G.useCallback)(()=>{c(e.id)},[c,e.id]),Pe=(0,G.useCallback)(e=>{if(!z.has(e)){let t=E.find(t=>t.id===e);(t?.detailTruncated||t?.terminalIds?.length||t?.subagentSessionId)&&De(t).catch(()=>{})}ie(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[De,z,E]),Fe=(0,G.useCallback)(async(e,t)=>{if(!f)return;await f(t);let n=E.find(t=>t.id===e);n&&await De(n,!0)},[De,f,E]),Ie=(0,G.useCallback)(async(e,t,n)=>{if(!p)return;await p(t,n);let r=E.find(t=>t.id===e);r&&await De(r,!0)},[De,p,E]),Le=(0,G.useCallback)(async(e,t,n,r)=>{m&&await m(t,n,r)},[m]),Re=(0,G.useCallback)(e=>{let t=E.find(t=>t.id===e);t&&Oe(t)},[Oe,E]),ze=(0,G.useRef)(r);ze.current=r;let Be=a,Ve=(0,G.useMemo)(()=>({a:({href:e,children:t,onClick:r,...a})=>{let o=e?AO(e,i):null,s=e?bO(e):!1,c=e&&CO(e),l=s&&c&&/^https?:/i.test(c)?c:``,u=e=>{if(r?.(e),!e.defaultPrevented&&o&&n){e.preventDefault(),n(o.filePath,o.target);return}};return(0,K.jsx)(`a`,{...a,className:[a.className,o?`code-agent-transcript-markdown-file-link`:``].filter(Boolean).join(` `)||void 0,href:o?`#`:c,target:s?`_blank`:void 0,rel:s?`noreferrer`:void 0,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:u,onContextMenu:e=>{l&&vS({event:e.nativeEvent,url:l,onOpenInFarming:ze.current?()=>ze.current?.(l):void 0})},children:o?(0,K.jsx)(VO,{filePath:o.filePath,lineNumber:o.target?.lineNumber,children:t}):t})},code:({className:e,children:t,...r})=>{let a=Ot(t),o=!(e||a.includes(`
198
+ `))&&jO(a)?AO(a,i):null;return!o||!n?(0,K.jsx)(`code`,{className:e,...r,children:t}):(0,K.jsx)(`a`,{className:`code-agent-transcript-markdown-file-link`,href:`#`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.preventDefault(),n(o.filePath,o.target)},children:(0,K.jsx)(VO,{filePath:o.filePath,lineNumber:o.target?.lineNumber,children:t})})},pre:({children:n,...r})=>{let i=St(n);return i===null?(0,K.jsx)(`pre`,{...r,children:n}):(0,K.jsx)(_t,{label:`transcript Mermaid`,resetKey:i,fallback:(e,n)=>(0,K.jsxs)(`figure`,{className:`code-markdown-mermaid error`,"aria-label":t.mermaidDiagram,children:[(0,K.jsx)(`figcaption`,{className:`code-markdown-mermaid-error-title`,children:t.mermaidRenderFailed}),(0,K.jsx)(PO,{copy:t,message:t.mermaidRenderFailed,onRetry:n,testId:`code-agent-transcript-mermaid-render-error`}),(0,K.jsx)(`pre`,{className:`code-markdown-mermaid-fallback`,children:(0,K.jsx)(`code`,{className:`language-mermaid`,children:i})})]}),children:(0,K.jsx)(Et,{surface:`transcript-mermaid`,identity:e.id,children:(0,K.jsx)(Tt,{source:i,copy:t})})})}}),[t,n,i]);return(0,K.jsxs)(`article`,{ref:S,className:`code-agent-transcript-turn ${e.status===`inProgress`?`running`:``}`,"data-turn-id":e.id,children:[e.userMessage||A.length>0||j.length>0||M.length>0?(0,K.jsxs)(`div`,{className:`code-agent-transcript-user`,children:[e.userMessage?(0,K.jsx)(`div`,{children:vO(e.userMessage)}):null,(0,K.jsx)(IO,{images:A}),(0,K.jsx)(YO,{audios:j}),(0,K.jsx)(zO,{files:M}),(0,K.jsx)(dO,{timestamp:e.startedAt,kind:`user`})]}):null,O?(0,K.jsx)(`div`,{className:`code-agent-transcript-process ${Be?`expanded`:``}`,children:me||le.length>0?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-transcript-process-summary`,"data-testid":`code-agent-transcript-process-summary`,"aria-expanded":Be,title:we||_O(pe,t),onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),Pk(e.currentTarget,Me)},onKeyDown:e=>{e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),e.stopPropagation(),Pk(e.currentTarget,Me))},children:[(0,K.jsx)(`span`,{className:`code-agent-transcript-process-summary-label`,children:Ee}),(0,K.jsx)(mt,{className:`code-agent-transcript-chevron`})]}),!Be&&ge.items.length>0?(0,K.jsx)(`div`,{className:`code-agent-transcript-process-list code-agent-transcript-process-compact-list`,"data-testid":`code-agent-transcript-process-compact-list`,children:ge.items.map(e=>(0,K.jsx)(Vk,{item:e,title:s===`acp`?gk(e,t):e.title,showStatus:!1,copy:t,copied:ee===e.id,detailOpen:z.has(e.id),onToggle:Pe,onCopy:ke,onStopTerminal:Fe,onInputTerminal:Ie,onResizeTerminal:Le,terminalOutcomeSyncFailed:ae.has(e.id),onRetryTerminalOutcome:Re,onStopSubagent:h},e.id))}):null,Be&&me?(0,K.jsx)(`div`,{className:`code-agent-transcript-process-list`,children:he.map(e=>{if(e.kind===`group`){let n=z.has(e.id)||e.items.some(e=>z.has(e.id))||s!==`acp`&&!_e&&e.items.some(ak);return(0,K.jsx)(Gk,{groupId:e.id,items:e.items,summaryLabel:s===`acp`?ND(e.items):void 0,copy:t,copiedItemId:ee,detailOpen:n,openProcessItemIds:z,onToggleGroup:Pe,onToggleItem:Pe,onCopy:ke,onStopTerminal:Fe,onInputTerminal:Ie,onResizeTerminal:Le,terminalOutcomeSyncFailedItemIds:ae,onRetryTerminalOutcome:Re,onStopSubagent:h},e.id)}return s===`acp`&&PD(e.item)?(0,K.jsx)(Uk,{item:e.item,markdownComponents:Ve,copy:t},e.item.id):(0,K.jsx)(Vk,{item:e.item,copy:t,copied:ee===e.item.id,detailOpen:z.has(e.item.id),onToggle:Pe,onCopy:ke,onStopTerminal:Fe,onInputTerminal:Ie,onResizeTerminal:Le,terminalOutcomeSyncFailed:ae.has(e.item.id),onRetryTerminalOutcome:Re,onStopSubagent:h},e.item.id)})}):null,s===`acp`&&le.length>0?(0,K.jsx)(Hk,{agents:le,processItems:E,copy:t,disclosureScope:e.id,openAgentIds:_,setOpenAgentIds:v,openActivityIds:y,setOpenActivityIds:b,onLoadProcessItemDetail:l,onStopTerminal:f,onInputTerminal:p,onResizeTerminal:m,onStopSubagent:h}):null]}):null}):null,ve||N.length>0||P.length>0||F.length>0?(0,K.jsxs)(`div`,{className:`code-agent-transcript-answer`,children:[ve?(0,K.jsx)(`div`,{className:`code-agent-transcript-assistant code-markdown-preview`,children:(0,K.jsx)(_t,{label:`transcript answer Markdown`,resetKey:ve,fallback:(e,n)=>(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(PO,{copy:t,onRetry:n,testId:`code-agent-transcript-markdown-render-error`}),(0,K.jsx)(`pre`,{children:ve})]}),children:(0,K.jsx)(Et,{surface:`transcript-markdown`,identity:e.id,children:(0,K.jsx)(yt,{remarkPlugins:[vt,kt],rehypePlugins:[Ct,At],components:Ve,skipHtml:!0,urlTransform:NO,children:ve})})})}):null,(0,K.jsx)(JO,{images:N}),(0,K.jsx)(YO,{audios:P}),(0,K.jsx)(zO,{files:F}),ve?(0,K.jsxs)(`div`,{className:`code-agent-transcript-answer-actions`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-answer-action ${L?`copied`:``}`,"data-testid":`code-agent-transcript-copy-answer`,"aria-label":L?t.agentTranscriptCopiedAnswer:t.agentTranscriptCopyAnswer,title:L?t.agentTranscriptCopiedAnswer:t.agentTranscriptCopyAnswer,"data-tooltip":L?t.agentTranscriptCopiedAnswer:t.agentTranscriptCopyAnswer,onClick:Ae,children:L?(0,K.jsx)(Ze,{}):(0,K.jsx)(ft,{})}),x?(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-answer-action code-agent-transcript-fork-action`,"data-testid":`code-agent-transcript-fork`,"aria-label":t.agentTranscriptFork,title:t.agentTranscriptFork,"data-tooltip":t.agentTranscriptFork,disabled:R,onClick:je,children:(0,K.jsx)(Ne,{})}):null,(0,K.jsx)(dO,{timestamp:e.completedAt,kind:`answer`})]}):null]}):ye?(0,K.jsx)(`div`,{className:`code-agent-transcript-placeholder`,children:t.agentTranscriptWaiting}):null,k.length>0?(0,K.jsx)(`div`,{className:`code-agent-transcript-results code-agent-transcript-status-row`,children:(0,K.jsx)(Kk,{items:k,copy:t,onLoadPatchChanges:u,source:s,workspaceRoot:i,gitDiffTarget:d})}):null]})}var Jk=(0,G.memo)(qk);function Yk(e){return[e.id,e.status,String(e.userMessage.length),String(e.finalMessage.length),String(e.completedAt||``),e.processItems.map(e=>`${e.id}:${e.status||``}:${e.detail?.length||0}`).join(``)].join(`\0`)}function Xk({agentId:e,workspaceRoot:t,active:n,viewportLayoutKey:i=``,source:a,refreshSignal:o=0,runtimeState:s=``,expectHistory:c=!1,forkedFromAgent:l=!1,onOpenWorkspaceFilePath:u,onOpenUrlInFarming:d,onAvailabilityChange:f,onReadLatest:p,onForkLatest:m,groupProcessActions:h=!0,copy:g}){let[_,v]=(0,G.useState)(null),y=(0,G.useRef)(null),[b,x]=(0,G.useState)(!0),[S,C]=(0,G.useState)(``),[w,T]=(0,G.useState)(()=>new Set),[E,D]=(0,G.useState)(()=>new Set),[O,k]=(0,G.useState)(()=>new Set),[A,j]=(0,G.useState)(()=>new Set),[M,N]=(0,G.useState)(()=>aO(a)),[P,F]=(0,G.useState)(!1),[te,R]=(0,G.useState)(!1),[ne,re]=(0,G.useState)({owner:``,target:UD}),z=(0,G.useRef)(null),ie=(0,G.useRef)(null),ae=(0,G.useRef)(!0),B=(0,G.useRef)(i),oe=(0,G.useRef)(!1),V=(0,G.useRef)(!1),se=(0,G.useRef)(null),ce=(0,G.useRef)(!1),le=(0,G.useRef)(!1),ue=(0,G.useRef)(u);(0,G.useLayoutEffect)(()=>{ue.current=u},[u]),(0,G.useLayoutEffect)(()=>{let t=B.current!==i;if(B.current=i,!t||!n||!ae.current)return;let r=z.current;!r||V.current||ce.current||lk(r)||(r.scrollTop=r.scrollHeight,ee(I(e,`chat`)),R(!1),p?.())},[n,e,p,i]),(0,G.useEffect)(()=>{v(null),y.current=null,C(``),x(!0),F(!1),N(aO(a)),T(new Set),D(new Set),k(new Set),j(new Set),R(!1);let t=!!L(I(e,`chat`));ae.current=!t,oe.current=t,ce.current=!1,le.current=!1,ie.current=null},[e,a]),(0,G.useEffect)(()=>()=>{se.current!==null&&(window.clearTimeout(se.current),se.current=null)},[]),(0,G.useEffect)(()=>{if(!n)return;let e=()=>{let e=z.current;if(e){if(lk(e)){ae.current=!1,le.current=!0;return}ce.current||le.current&&(le.current=!1,R(!ck(e)&&e.scrollHeight>e.clientHeight+sO))}},t=()=>{window.requestAnimationFrame(()=>{ce.current=!1,e()})};return document.addEventListener(`selectionchange`,e),document.addEventListener(`pointerup`,t),document.addEventListener(`pointercancel`,t),()=>{document.removeEventListener(`selectionchange`,e),document.removeEventListener(`pointerup`,t),document.removeEventListener(`pointercancel`,t),ce.current=!1,le.current=!1}},[n]),(0,G.useEffect)(()=>{if(!n)return;let t=!1,i=null,o=null,s=0,c=null,l=!1,u=0,d=()=>{let n=++u;o!==null&&(window.clearTimeout(o),o=null),c?.abort(),c=new AbortController;let i=new URLSearchParams({maxTurns:String(M)}),f=y.current;a===`acp`&&f?.sessionId&&f.turnLimit===M&&Number.isFinite(f.revision)&&i.set(`sinceRevision`,String(f.revision)),a===`acp`&&i.set(`media`,`external-v1`);let p=!1;fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-transcript?${i.toString()}`),{signal:c.signal}).then(e=>{if(p=!0,!e.ok)throw Error(g.agentTranscriptUnavailable);return e.json()}).then(e=>{if(t||n!==u)return;s=0,l=!1;let r=a===`acp`&&e.transcript?AD(e.transcript,{maxTurns:M}):e.transcript||null;v(e=>{let t=a===`acp`?XD(e,r):YD(e,r);return y.current=t,t}),C(``),x(!1),F(!1)}).catch(e=>{if(t||n!==u||e?.name===`AbortError`)return;let r=a===`acp`&&!p&&e instanceof TypeError?iO[s]:void 0;if(r!==void 0){s+=1,o=window.setTimeout(d,r);return}s=0,l=a===`acp`&&!p&&e instanceof TypeError,C(y.current?.available?``:g.agentTranscriptUnavailable),x(!1),F(!1)})},f=()=>{l=!0},p=()=>{l&&(l=!1,d())};return d(),window.addEventListener(`farming:backend-disconnected`,f),window.addEventListener(`farming:backend-connected`,p),a!==`acp`&&(i=window.setInterval(d,3e3)),()=>{t=!0,window.removeEventListener(`farming:backend-disconnected`,f),window.removeEventListener(`farming:backend-connected`,p),c?.abort(),o!==null&&window.clearTimeout(o),i!==null&&window.clearInterval(i)}},[n,e,g.agentTranscriptUnavailable,o,a,M]);let de=(0,G.useMemo)(()=>_?.turns||[],[_]),fe=de[de.length-1],pe=fe?.processItems[fe.processItems.length-1],me=[fe?.id||``,fe?.status||``,fe?.completedAt||``,pe?.id||``,pe?.status||``].join(`\0`),he=`${e}\0${t||``}`,ge=ne.owner===he?ne.target:UD,H=a===`acp`&&!S&&de.length===0&&(s===`connecting`||c);(0,G.useEffect)(()=>{if(!n||!_?.available||de.length===0)return;let e=z.current,t=e?ck(e):ae.current;e&&(ce.current||lk(e))||t&&p?.()},[n,p,_?.available,_?.updatedAt,de.length]),(0,G.useLayoutEffect)(()=>{if(b||!_?.available||de.length===0)return;let t=z.current;if(!t||V.current)return;let r=lk(t);if(ce.current||r){r&&(ae.current=!1,le.current=!0);return}let i=ie.current;if(i){ie.current=null,window.requestAnimationFrame(()=>{if(ce.current||lk(t))return;let n=t.scrollHeight-i.scrollHeight+i.scrollTop;t.scrollTop=Math.max(0,n),ZD(e,t)});return}if(ae.current){oe.current=!1,window.requestAnimationFrame(()=>{ce.current||lk(t)||(t.scrollTop=t.scrollHeight,ee(I(e,`chat`)),R(!1),n&&p?.())});return}oe.current&&(oe.current=!1,window.requestAnimationFrame(()=>{ce.current||lk(t)||QD(e,t)===`expired`&&(ae.current=!0,t.scrollTop=t.scrollHeight,R(!1),n&&p?.())}))},[n,e,b,p,_?.available,_?.updatedAt,de.length]),(0,G.useEffect)(()=>()=>{let t=z.current;t&&ZD(e,t)},[e]),(0,G.useEffect)(()=>{f?.({loading:b,hasContent:!!(_?.available&&de.length>0),available:!!_?.available})},[b,f,_?.available,de.length]);let _e=(0,G.useCallback)((t,n)=>ue.current?.(e,t,{...n,suppressSearchOnMiss:!0}),[e]),ve=(0,G.useMemo)(()=>({workspaceRoot:t,onOpenFile:u?_e:void 0}),[_e,u,t]);(0,G.useEffect)(()=>{if(!n||!t)return;let i=!1;return fetch(r(`/api/files/worktrees?agentId=${encodeURIComponent(e)}`)).then(e=>e.ok?e.json():null).then(async e=>{if(i)return;if(e?.worktrees?.isGitRepo!==!0){re({owner:he,target:UD});return}let n=WD;try{n=GD(await Rt({root:t}))}catch{}i||re({owner:he,target:n})}).catch(()=>{}),()=>{i=!0}},[n,e,he,me,t]);let ye=(0,G.useCallback)(async t=>{let n=await fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-tool-details/${encodeURIComponent(t)}`)),i=await n.json().catch(()=>({}));if(!n.ok)throw Error(i.error||g.agentTranscriptUnavailable);return{detail:String(i.detail||``),terminals:Array.isArray(i.terminals)?i.terminals:void 0,subagentTranscript:i.subagentSession&&typeof i.subagentSession==`object`?AD(i.subagentSession,{maxTurns:12}):void 0}},[e,g.agentTranscriptUnavailable]),be=(0,G.useCallback)(t=>zt(e,t),[e]),xe=(0,G.useCallback)(async t=>{let n=await fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t)}/kill`),{method:`POST`}),i=await n.json().catch(()=>({}));if(!n.ok)throw Error(i.error||`Failed to stop command`)},[e]),Se=(0,G.useCallback)(async(t,n)=>{let i=await fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t)}/input`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({input:n})}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a.error||`Failed to send terminal input`)},[e]),U=(0,G.useCallback)(async(t,n,i)=>{let a=await fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t)}/resize`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cols:n,rows:i})}),o=await a.json().catch(()=>({}));if(!a.ok)throw Error(o.error||`Failed to resize terminal`)},[e]),Ce=(0,G.useCallback)(async t=>{let n=await fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-subagents/${encodeURIComponent(t)}/cancel`),{method:`POST`}),i=await n.json().catch(()=>({}));if(!n.ok)throw Error(i.error||`Failed to stop subagent`)},[e]),we=(0,G.useCallback)(e=>{!_?.hasMoreBefore||P||M>=rO||(ie.current={scrollTop:e.scrollTop,scrollHeight:e.scrollHeight},F(!0),N(e=>{let t=Math.min(rO,e+(a===`acp`?nO:eO));return t===e&&F(!1),t}))},[P,a,_?.hasMoreBefore,M]),Te=(0,G.useCallback)(()=>{V.current=!0,se.current!==null&&(window.clearTimeout(se.current),se.current=null)},[]),Ee=(0,G.useCallback)(()=>{se.current!==null&&window.clearTimeout(se.current),se.current=window.setTimeout(()=>{V.current=!1,se.current=null},420)},[]),De=(0,G.useCallback)(()=>{Te()},[Te]),Oe=(0,G.useCallback)(()=>{Te()},[Te]),ke=(0,G.useCallback)(()=>{Ee()},[Ee]),Ae=(0,G.useCallback)(()=>{let t=z.current;if(!t)return;if(oe.current=!1,ce.current||lk(t)){ae.current=!1,le.current=!0,ZD(e,t);return}let r=ck(t);ae.current=r,ZD(e,t),R(!r&&t.scrollHeight>t.clientHeight+sO),n&&r&&p?.(),t.scrollTop<=oO&&we(t)},[n,e,p,we]),je=(0,G.useCallback)(e=>{if(Te(),Ee(),e.deltaY>=0)return;let t=z.current;!t||t.scrollTop>oO||we(t)},[Ee,Te,we]),Me=(0,G.useCallback)(e=>{if(e.button!==0||e.pointerType===`touch`)return;let t=e.target;t instanceof Element&&t.closest(`button, a, input, textarea, select, summary, [role="button"]`)||(ce.current=!0)},[]),Pe=(0,G.useCallback)(e=>{let t=de.find(t=>t.id===e);if(a===`acp`&&t?.status===`inProgress`){D(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return}T(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[a,de]),Fe=(0,G.useCallback)(()=>{let t=z.current;t&&(ae.current=!0,le.current=!1,t.scrollTop=t.scrollHeight,ee(I(e,`chat`)),R(!1),p?.())},[e,p]);return(0,K.jsx)(qD.Provider,{value:ve,children:(0,K.jsxs)(`div`,{className:`code-agent-transcript ${a===`acp`&&_?.plan?`has-plan-driver`:``}`,"data-testid":`code-agent-transcript`,children:[l?(0,K.jsxs)(`div`,{className:`code-agent-transcript-fork-origin`,"data-testid":`code-agent-transcript-fork-origin`,role:`note`,children:[(0,K.jsx)(`span`,{"aria-hidden":`true`}),(0,K.jsxs)(`span`,{className:`code-agent-transcript-fork-origin-label`,children:[(0,K.jsx)(Ne,{}),g.agentTranscriptForkedFromAgent]}),(0,K.jsx)(`span`,{"aria-hidden":`true`})]}):null,a===`acp`&&_?.plan?(0,K.jsx)(Wk,{plan:_.plan}):null,b||H?(0,K.jsx)(`div`,{className:`code-agent-transcript-state subtle`,children:g.agentTranscriptSyncing}):S?(0,K.jsx)(`div`,{className:`code-agent-transcript-state`,role:`status`,children:S}):_?.available?de.length===0?(0,K.jsx)(`div`,{className:`code-agent-transcript-blank`,role:`status`,children:g.agentTranscriptEmpty}):(0,K.jsx)(`div`,{className:`code-agent-transcript-scroll`,"data-testid":`code-agent-transcript-scroll`,ref:z,onPointerDown:Me,onScroll:Ae,onWheel:je,onTouchStart:De,onTouchMove:Oe,onTouchEnd:ke,onTouchCancel:ke,children:de.map((e,n)=>{let r=a===`acp`&&e.status===`inProgress`?E.has(e.id):w.has(e.id);return(0,K.jsx)(_t,{label:`transcript turn`,resetKey:Yk(e),fallback:(t,n)=>(0,K.jsx)(`article`,{className:`code-agent-transcript-turn`,"data-turn-id":e.id,children:(0,K.jsx)(PO,{copy:g,onRetry:n,testId:`code-agent-transcript-turn-render-error`})}),children:(0,K.jsx)(Et,{surface:`transcript-turn`,identity:e.id,children:(0,K.jsx)(Jk,{turn:e,copy:g,onOpenFile:u?_e:void 0,onOpenUrlInFarming:d,workspaceRoot:t,processOpen:r,groupProcessActions:h,source:a,onToggleProcess:Pe,onLoadProcessItemDetail:a===`acp`?ye:void 0,onLoadPatchChanges:a===`acp`?be:void 0,gitDiffTarget:ge,onStopTerminal:a===`acp`?xe:void 0,onInputTerminal:a===`acp`?Se:void 0,onResizeTerminal:a===`acp`?U:void 0,onStopSubagent:a===`acp`?Ce:void 0,subagentStates:_?.codexSubagents?.agents||[],openCollaborationAgentIds:O,setOpenCollaborationAgentIds:k,openCollaborationActivityIds:A,setOpenCollaborationActivityIds:j,onFork:n===de.length-1&&e.status!==`inProgress`?m:void 0})})},e.id)})}):(0,K.jsx)(`div`,{className:`code-agent-transcript-blank`,role:`status`,children:g.agentTranscriptEmpty}),te?(0,K.jsx)(`button`,{type:`button`,className:`code-agent-transcript-jump-bottom`,"data-testid":`code-agent-transcript-jump-bottom`,"aria-label":`Jump to latest chat`,onClick:Fe,children:(0,K.jsx)(Je,{})}):null]})})}function Zk(e){return(0,K.jsx)(Xk,{...e,source:`acp`,groupProcessActions:!0})}function Qk(e){let t=e.runtimeObservation.kind;return t===`codex`||t===`claude`||t===`shell`?t:t===`process`?`agent`:null}function $k(e){if(!e)return{kind:null,kindSource:`none`,turnActive:!1,terminalBusy:!1};let t=e.runtimeObservation.phase,n=t===`starting`||t===`working`||t===`waiting`;return{kind:Qk(e),kindSource:`terminal-status`,turnActive:n,terminalBusy:e.runtimeBinding.kind===`terminal`?e.terminalStatus?e.terminalStatus.busy===!0:e.terminalBusy===!0:!1}}function eA(e){let t=$k(e);return t.kind===`codex`&&t.turnActive}function tA(e){return $k(e).turnActive}function nA(e){let t=(e||``).trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e)),n=t?.split(`/`).pop()||``;return n===`codex`?`codex`:n===`claude`?`claude`:[`bash`,`zsh`,`sh`,`fish`].includes(n)?`shell`:t?`agent`:null}var rA={plusMenu:!1,goalMode:!1,permissionMode:!1,modelPicker:!1,reasoningEffort:!1,serviceTier:!1,speechInput:!0},iA={plusMenu:!0,goalMode:!0,permissionMode:!0,modelPicker:!0,reasoningEffort:!0,serviceTier:!1,speechInput:!0},aA=[{command:`/goal`,label:`Goal`,description:`Set or update what this Codex session should keep working toward`,source:`codex`},{command:`/plan`,label:`Plan mode`,description:`Ask Codex to plan first before editing`,source:`codex`},{command:`/skills`,label:`Skills`,description:`Browse and use available Codex skills`,source:`codex`},{command:`/permissions`,label:`Permissions`,description:`Change what Codex can do without asking first`,source:`codex`},{command:`/model`,label:`Model`,description:`Change or inspect the active Codex model`,source:`codex`},{command:`/reasoning`,label:`Reasoning`,description:`Change the reasoning effort for this session`,source:`codex`},{command:`/mcp`,label:`MCP`,description:`Show MCP server status`,source:`codex`},{command:`/fast`,label:`Fast`,description:`Toggle Codex fast mode when available`,source:`codex`},{command:`/status`,label:`Status`,description:`Inspect the session, model, permissions, and token usage`,source:`codex`},{command:`/usage`,label:`Usage`,description:`View account token usage from Codex`,source:`codex`},{command:`/compact`,label:`Compact`,description:`Summarize long context to free tokens`,source:`codex`},{command:`/review`,label:`Review`,description:`Ask Codex to review the current working tree`,source:`codex`},{command:`/personality`,label:`Personality`,description:`Choose how Codex communicates in this session`,source:`codex`},{command:`/help`,label:`Help`,description:`Show available Codex slash commands`,source:`codex`}],oA=[{command:`/help`,label:`Help`,description:`Show available Claude Code slash commands`,source:`claude`},{command:`/model`,label:`Model`,description:`Change or inspect the active Claude model`,source:`claude`},{command:`/permissions`,label:`Permissions`,description:`Review or change Claude Code permission behavior`,source:`claude`},{command:`/cost`,label:`Cost`,description:`Show Claude Code usage for the current conversation`,source:`claude`},{command:`/compact`,label:`Compact`,description:`Compact the current Claude Code conversation`,source:`claude`},{command:`/clear`,label:`Clear`,description:`Clear the current Claude Code conversation`,source:`claude`},{command:`/config`,label:`Config`,description:`Open Claude Code configuration`,source:`claude`},{command:`/doctor`,label:`Doctor`,description:`Check Claude Code installation and account health`,source:`claude`},{command:`/memory`,label:`Memory`,description:`Edit or inspect Claude Code memory`,source:`claude`}];function sA(e){return e===`codex`?aA:e===`claude`?oA:[]}function cA(e){let t=new Set;return e.filter(e=>{let n=e.command.trim().toLowerCase();return!n||t.has(n)?!1:(t.add(n),!0)})}function lA(e){let t=$k(e).kind,n=e?.runtimeBinding.kind||`terminal`;return{kind:t,composer:t===`codex`?{...iA,modelPicker:n===`terminal`,reasoningEffort:n===`terminal`,serviceTier:n===`terminal`}:t===`claude`?{...iA,modelPicker:!1,reasoningEffort:!1}:{...rA,goalMode:!!e?.providerCapabilities.goalSubmission},actions:{pin:!!e,rename:!!e,archive:!!(e&&!e.isMain),markUnread:!!e,copyWorkingDirectory:!!e,forkSameWorktree:!!e,forkNewWorktree:e?.canForkNewWorktree===!0,kill:!!(e&&(e.isMain||e.requiresProcessExitAcknowledgement===!0))}}}function uA(e){if(!e?.providerCapabilities)return!1;let t=e.providerCapabilities,n=t.runtimeSwitch&&e.runtimeBinding.kind===`terminal`&&e.providerSessionTemporary===!0&&e.terminalInputReceived!==!0;return!!(t.runtimeSwitch&&t.supportsChat&&(e.providerSessionTemporary!==!0||n)&&e.providerSessionId)}function dA(e){return!!(e&&e.runtimeBinding.kind===`acp`&&e.runtimeBinding.supportsFork===!0&&e.providerCapabilities.sessionFork&&e.providerSessionId&&e.providerSessionTemporary!==!0)}function fA(e){return!!(e&&(e.agents.some(e=>!e.isMain)||e.agentSessions.length>0))}function pA(e){if(!e||e.hasMain||!e.workspace)return!1;let t=e.workspace.replace(/[\\/]+$/,``).split(/[\\/]/).pop()??``;return/-farming-fork-\d{8}-\d{6}(?:-\d+)?$/.test(t)}function mA(e){let t=lA(e),n=uA(e),r=[n,t.actions.pin,t.actions.rename,t.actions.archive,t.actions.markUnread,t.actions.copyWorkingDirectory,t.actions.forkSameWorktree,t.actions.forkNewWorktree,t.actions.kill].filter(Boolean).length;return{itemCount:r,separatorCount:r>0?2+Number(n):0}}function hA({agent:e,active:t,viewportLayoutKey:n,switching:r,switchingKind:i,focusSignal:a,onActivate:o,onSessionOutput:s,onOpenPath:c,onResolvePath:l,onSearchTerminalWord:u,onOpenWorkspaceFilePath:d,onOpenUrlInFarming:f,onFollowOutputChange:p,onReadLatest:m,onRuntimeModeChange:h,onForkAgent:g,copy:_}){let v=mr(e)?e.runtimeBinding:null,y=!!v,b=uA(e),x=r||tA(e),S=dA(e)&&!tA(e),C=(0,G.useCallback)(n=>{n.button===0&&(t||o(e.id,{focusTerminal:!1}))},[t,e.id,o]);return(0,K.jsxs)(`section`,{className:`code-agent-work-pane ${t?`active`:``} ${b?`runtime-switchable`:``}`,"data-testid":`code-agent-work-pane`,"data-agent-id":e.id,hidden:!t,"aria-busy":r,children:[b?(0,K.jsxs)(`div`,{className:`code-terminal-mode-toggle`,"data-testid":`code-terminal-mode-toggle`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`button`,{type:`button`,className:y?`active`:``,"aria-pressed":y,"aria-label":_.transcriptView,title:_.transcriptView,disabled:x,onClick:()=>!y&&h?.(e.id,`chat`),children:(0,K.jsx)(Qe,{})}),(0,K.jsx)(`button`,{type:`button`,className:y?``:`active`,"aria-pressed":!y,"aria-label":_.terminalView,title:_.terminalView,disabled:x,onClick:()=>y&&h?.(e.id,`terminal`),children:(0,K.jsx)(ot,{})})]}):null,!y&&t?(0,K.jsx)(`div`,{className:`code-agent-work-view terminal active`,"data-testid":`code-agent-terminal-view`,"aria-hidden":!1,children:(0,K.jsx)(tE,{agent:e,active:t,onActivate:o,onOpenPath:c,onResolvePath:l,onSearchWord:u,onOpenUrlInFarming:f,onFollowOutputChange:p,onReadLatest:m,onSessionOutput:s,focusSignal:a,copy:_})},`terminal`):null,y?(0,K.jsx)(`div`,{className:`code-agent-work-view transcript active`,"data-testid":`code-agent-chat-view`,"aria-hidden":!1,onPointerDown:C,children:(0,K.jsx)(Zk,{agentId:e.id,workspaceRoot:e.projectWorkspace||e.cwd,active:t,viewportLayoutKey:n,runtimeState:v?.state||``,expectHistory:(e.source||``).startsWith(`codex-history:`),forkedFromAgent:!!(e.parentAgentId&&e.forkedFromProviderSessionId),refreshSignal:v?.sessionRevision||(v?.sessionUpdatedAt?Date.parse(v.sessionUpdatedAt):0),onOpenWorkspaceFilePath:d,onOpenUrlInFarming:t=>f?.(e.id,t),onReadLatest:()=>m?.(e.id),onForkLatest:S?()=>g?.(e.id,`same-worktree`,{targetRuntime:`chat`,expectedRevision:v?.sessionRevision||0}):void 0,copy:_})},`chat`):null,r?(0,K.jsxs)(`div`,{className:`code-permission-switching`,"data-testid":`code-permission-switching`,role:`status`,"aria-live":`polite`,children:[(0,K.jsx)(`span`,{className:`code-permission-switching-spinner`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:i===`runtime`?_.runtimeModeRestarting:_.permissionProfileRestarting})]}):null]})}var gA=`__farming_main_agent__`,_A=`__agent_chats__`;function vA(e){return e.kind===`agent-session`?`${e.kind}:${e.provider}:${e.id}`:`${e.kind}:${e.id}`}function yA(e){let t=e.replace(/\/+$/,``);return t.split(`/`).filter(Boolean).pop()||t||`Farming`}function bA(e){return e.gitWorktree?.workspace?e.gitWorktree.workspace:e.projectWorkspace?e.projectWorkspace:e.cwd||`Farming`}function xA(e){return e===`/`?`/`:e?yA(e):`Farming`}function SA(e){return e||`No workspace`}function CA(e){return e===`xhigh`?`Extra High`:e?`${e.slice(0,1).toUpperCase()}${e.slice(1)}`:`Config`}function wA(e){if(!e||e===`config`)return{model:`gpt-5.5`,effort:`xhigh`};let[t=`gpt-5.5`,n=`xhigh`]=e.split(`:`);return{model:t,effort:n}}function TA(e,t){return/^gpt-/i.test(t)?(e?.displayName||e?.label||t).replace(/^gpt-/i,``).replace(/^GPT-/i,``):e?.displayName?e.displayName:e?.label||t||`Model`}function EA(e){let t=new Map;return e.forEach(e=>{let n=e.model||e.value.split(`:`)[0];if(!n)return;let r=t.get(n)??{value:n,label:n.replace(/^gpt-/i,``),defaultEffort:e.effort||`medium`,reasoningLevels:[],serviceTiers:[{value:`default`,label:`Standard`,description:`Default speed`}],source:e.source};e.effort&&!r.reasoningLevels?.some(t=>t.value===e.effort)&&(r.reasoningLevels=[...r.reasoningLevels??[],{value:e.effort,effort:e.effort,label:CA(e.effort),description:e.description}]),t.set(n,r)}),Array.from(t.values())}function DA(e){let t=Array.isArray(e.catalog)?e.catalog.filter(e=>e&&typeof e.value==`string`&&typeof e.label==`string`):[];return t.length>0?t:EA(Array.isArray(e.models)?e.models.filter(e=>e&&typeof e.value==`string`&&typeof e.label==`string`):[])}function OA(e){let t=e.providerHomeId&&e.providerHomeId!==`default`?`home:${e.providerHomeId}:${e.id}`:e.id;return vA({kind:`agent-session`,provider:e.provider,id:t})}function kA(e){let t=e.workspace||e.cwd;return t?er(t):e.projectless?`Chats`:e.providerName||`Agent`}function AA(e){return e.projectless?``:e.workspace||e.cwd||``}function jA(e){return e.cwd||e.workspace||``}function MA(e){return e.projectless?_A:AA(e)||`__agent_sessions__`}function NA(e){if(e.projectless)return`Chats`;let t=AA(e);return t?xA(t):`Agent Sessions`}function PA(e){let t=Date.parse(e.updatedAt||e.createdAt||``);return Number.isFinite(t)?t:0}function FA(e,t){return PA(t)-PA(e)}function IA(e,t){let n=new Map;return e.forEach(e=>{let t=bA(e),r=e.isMain?gA:t,i=n.get(r)??{id:r,name:e.isMain?`Main Agent`:xA(t),workspace:t,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1,gitWorktree:e.gitWorktree??null};i.agents.push(e),i.hasMain||=e.isMain,i.hasProjectAgent||=!e.isMain,e.gitWorktree?.workspace&&(i.gitWorktree=e.gitWorktree),i.name=i.hasMain?`Main Agent`:xA(i.workspace),n.set(r,i)}),t.forEach(e=>{let t=MA(e),r=AA(e),i=n.get(t)??{id:t,name:NA(e),workspace:r,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1,gitWorktree:null};i.agentSessions.push(e),i.hasAgentSession=!0,n.set(t,i)}),Array.from(n.values()).map(e=>({...e,agents:e.agents.sort((e,t)=>{if(e.isMain!==t.isMain)return e.isMain?-1:1;let n=(t.projectOrder??0)-(e.projectOrder??0);return n===0?(t.startedAt??0)-(e.startedAt??0):n}),agentSessions:e.agentSessions.sort(FA)})).sort((e,t)=>{let n=e.agents.some(e=>e.isMain);if(n!==t.agents.some(e=>e.isMain))return n?-1:1;let r=e.id===_A;return r===(t.id===`__agent_chats__`)?e.name.localeCompare(t.name):r?1:-1})}function LA(e,t){return t||e.isComposing===!0||e.nativeEvent?.isComposing===!0||e.nativeEvent?.keyCode===229}function RA(e,t,n=Date.now()){return e.key===`Enter`&&t>0&&n-t<=120}function zA(e,t,n,r=Date.now()){return e.key!==`Enter`||e.shiftKey||LA(e,t)||RA(e,n,r)?!1:e.ctrlKey||e.metaKey||e.altKey?(e.ctrlKey===!0||e.metaKey===!0)&&e.altKey!==!0:!0}function BA(e,t){return e||t}function VA({attachments:e,onRemove:t}){return e.length===0?null:(0,K.jsx)(`div`,{className:`code-composer-attachments`,"data-testid":`code-composer-attachments`,children:e.map(e=>{let n=e.kind===`image`&&!!e.previewUrl;return(0,K.jsxs)(`div`,{className:[`code-composer-attachment`,n?`image`:`chip`,e.status].join(` `),"data-testid":`code-composer-attachment`,children:[n?(0,K.jsx)(`div`,{className:`code-composer-attachment-preview`,"data-testid":`code-composer-attachment-preview`,children:(0,K.jsx)(`img`,{src:e.previewUrl,alt:e.name})}):(0,K.jsx)(`span`,{className:`code-composer-attachment-fallback`,"aria-hidden":`true`,children:(0,K.jsx)(je,{})}),(0,K.jsx)(`span`,{className:`code-composer-attachment-name`,title:e.name,children:e.name}),e.status!==`ready`&&(0,K.jsx)(`span`,{className:`code-composer-attachment-status`,children:e.status===`uploading`?`Uploading`:`Failed`}),(0,K.jsx)(`button`,{type:`button`,className:`code-composer-attachment-remove`,"aria-label":`Remove ${e.name}`,onClick:()=>t(e.id),children:(0,K.jsx)(pt,{})})]},e.id)})})}function HA(e,t){let n=Math.max(0,Math.min(t,e.length)),r=e.lastIndexOf(`
199
+ `,Math.max(0,n-1))+1,i=e.slice(r,n),a=i.match(/^(\s*)\/([A-Za-z0-9._:-]*)$/);if(a)return{start:r+(a[1]?.length??0),end:n,query:a[2]??``,trigger:`/`};let o=i.match(/(^|\s)\$([A-Za-z0-9._:-]*)$/);return o?{start:r+(o.index??0)+(o[1]?.length??0),end:n,query:o[2]??``,trigger:`$`}:null}function UA(e,t,n){let r=t.trim().toLowerCase();return e.command.startsWith(n)?r?e.command.slice(1).toLowerCase().startsWith(r)||e.label.toLowerCase().includes(r):!0:!1}function WA(e,t){let n=t.trim().toLowerCase();return n?+!e.command.slice(1).toLowerCase().startsWith(n):0}function GA(e){return`code-slash-command-${e.replace(/^[/$]/,``).replace(/[^A-Za-z0-9_-]+/g,`-`)||`root`}`}function KA(e){(0,G.useLayoutEffect)(()=>{let t=e.current;if(!t)return;let n=t.closest(`.code-main`),r=()=>{t.style.removeProperty(`--mobile-composer-current-height`),n?.style.removeProperty(`--mobile-composer-current-height`)},i=()=>{if(!de()){r();return}let e=t.getBoundingClientRect().height;if(e<=0)return;let i=`${Math.ceil(e)}px`;t.style.setProperty(`--mobile-composer-current-height`,i),n?.style.setProperty(`--mobile-composer-current-height`,i)};i();let a=typeof ResizeObserver>`u`?null:new ResizeObserver(i);return a?.observe(t),window.addEventListener(`resize`,i),()=>{a?.disconnect(),window.removeEventListener(`resize`,i),r()}},[e])}function qA(e){e.style.height=`auto`;let t=window.getComputedStyle(e),n=Number.parseFloat(t.minHeight)||0,r=Number.parseFloat(t.maxHeight)||1/0,i=Math.min(r,Math.max(n,e.scrollHeight));e.style.height=`${Math.ceil(i)}px`,e.style.overflowY=e.scrollHeight>r?`auto`:`hidden`}function JA(e,t){(0,G.useLayoutEffect)(()=>{let t=e.current;if(!t)return;let n=()=>qA(t);n();let r=t.getBoundingClientRect().width,i=typeof ResizeObserver>`u`?null:new ResizeObserver(e=>{let i=e[0]?.contentRect.width??t.getBoundingClientRect().width;Math.abs(i-r)<.5||(r=i,n())});return i?.observe(t),window.addEventListener(`resize`,n),()=>{i?.disconnect(),window.removeEventListener(`resize`,n),t.style.removeProperty(`height`),t.style.removeProperty(`overflow-y`)}},[e,t])}var YA=[`sol`,`terra`,`luna`],XA=4,ZA=240;function QA(e,t){let n=t.match(/^(.*?)[-\s](sol|terra|luna)$/i)?.[1]?.toLowerCase();if(!n)return null;let r=e.flatMap(e=>{let t=e.value.match(/^(.*?)[-\s](sol|terra|luna)$/i),r=t?.[1]?.toLowerCase(),i=t?.[2]?.toLowerCase();return!r||r!==n||!i?[]:[{...e,variant:i}]}).sort((e,t)=>YA.indexOf(e.variant)-YA.indexOf(t.variant));return r.length>=2?r:null}function $A({label:e,active:t,disabled:n,unavailable:r,unavailableReason:i,onChange:a}){let[o,s]=(0,G.useState)(!1),c=(0,G.useRef)(null);(0,G.useEffect)(()=>()=>{c.current!==null&&window.clearTimeout(c.current)},[]);function l(){c.current!==null&&window.clearTimeout(c.current),s(!0),c.current=window.setTimeout(()=>{c.current=null,s(!1)},650)}function u(){c.current!==null&&window.clearTimeout(c.current),c.current=null,s(!1)}return(0,K.jsxs)(`div`,{className:`code-model-matrix-rocker is-ultra ${t?`is-active`:``} ${r?`is-disabled`:``}`,title:r?i:void 0,children:[(0,K.jsx)(`span`,{children:e}),(0,K.jsx)(`button`,{type:`button`,className:`code-model-matrix-rocker-button`,disabled:n||r,"aria-label":r&&i?`Ultra reasoning unavailable: ${i}`:`Ultra reasoning`,"aria-pressed":t,onClick:()=>{t||l(),a(!t)},children:(0,K.jsxs)(`span`,{className:`code-model-matrix-rocker-control ${o?`is-kicked`:``}`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-slot`,children:(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-energy`})}),(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-knob-position`,children:(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-knob ${o?`is-kicked`:``}`,onAnimationEnd:u})})]})})]})}function ej({active:e,available:t,disabled:n,unavailableReason:r,onChange:i}){let[a,o]=(0,G.useState)(!1),s=!t,c=n||s;return(0,K.jsxs)(`button`,{type:`button`,className:`code-model-matrix-fast ${e?`is-active`:``} ${s?`is-disabled`:``}`,"aria-label":s&&r?`Fast mode unavailable: ${r}`:`Fast mode`,title:s?r:void 0,"aria-pressed":e,"aria-disabled":c,disabled:c,onClick:()=>{o(!0),i(!e)},children:[(0,K.jsx)(`span`,{className:`code-model-matrix-fast-bolt ${a?`is-kicked`:``}`,"aria-hidden":`true`,onAnimationEnd:()=>o(!1),children:(0,K.jsx)(De,{})}),(0,K.jsx)(`span`,{children:`Fast`}),(0,K.jsx)(`small`,{children:t?e?`ON`:`OFF`:`—`})]})}function tj({models:e,currentModel:t,currentReasoning:n,fastAvailable:r,fast:i,disabled:a,onSelect:o,onFastChange:s,advanced:c}){let l=QA(e,t),u=!!l?.find(e=>e.value===t)?.reasoning.some(e=>e.value===n),[d,f]=(0,G.useState)(!u),[p,m]=(0,G.useState)(null),[h,g]=(0,G.useState)(null),[_,v]=(0,G.useState)(null),y=(0,G.useRef)(!!l),b=(0,G.useRef)(new Map),x=(0,G.useRef)(null),S=(0,G.useRef)(null),C=(0,G.useRef)(null),w=(0,G.useRef)(null),T=(0,G.useRef)(null),E=(0,G.useRef)(null),D=(0,G.useRef)(null),O=(0,G.useRef)(null),k=(0,G.useRef)(null);if((0,G.useEffect)(()=>{let e=!y.current&&!!l;y.current=!!l,e&&u&&(D.current=w.current?.getBoundingClientRect().height??null,f(!1))},[l,u]),(0,G.useEffect)(()=>{if(!h)return;if(t===h.model&&n===h.reasoning){g(null);return}let e=window.setTimeout(()=>g(null),5e3);return()=>window.clearTimeout(e)},[t,n,h]),(0,G.useEffect)(()=>{if(_===null)return;if(!r||i===_){v(null);return}let e=window.setTimeout(()=>v(null),5e3);return()=>window.clearTimeout(e)},[i,r,_]),(0,G.useEffect)(()=>()=>{C.current!==null&&window.cancelAnimationFrame(C.current),O.current!==null&&window.cancelAnimationFrame(O.current),k.current!==null&&window.clearTimeout(k.current)},[]),(0,G.useLayoutEffect)(()=>{let e=w.current,t=d?E.current:T.current,n=D.current;if(D.current=null,!e||!t)return;O.current!==null&&window.cancelAnimationFrame(O.current),k.current!==null&&window.clearTimeout(k.current),O.current=null,k.current=null;let r=t.getBoundingClientRect().height,i=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;if(n===null||i||Math.abs(n-r)<1){e.style.height=`${r}px`,e.style.overflow=d?`visible`:`hidden`;return}e.style.height=`${n}px`,e.style.overflow=`hidden`,e.offsetHeight,O.current=window.requestAnimationFrame(()=>{e.style.height=`${r}px`,O.current=null}),k.current=window.setTimeout(()=>{e.style.height=`${r}px`,e.style.overflow=d?`visible`:`hidden`,k.current=null},ZA+40)},[d]),!l)return c;let A=l.find(e=>e.value===t)??l[0],j=A.reasoning.filter(e=>e.value!==`ultra`);n!==`ultra`&&j.some(e=>e.value===n)&&b.current.set(A.value,n);let M=b.current.get(A.value)||j[j.length-1]?.value||n,N=n===`ultra`?M:n,P=Math.max(0,j.findIndex(e=>e.value===N)),F=A.reasoning.find(e=>e.value===n)?.label||n;function ee(e,t){a||(g({model:e.value,reasoning:t}),b.current.set(e.value,t),o(e.value,t))}let I=l.map(e=>({model:e,reasoning:e.reasoning.filter(e=>e.value!==`ultra`)})),L=Math.max(0,I.findIndex(e=>e.model.value===t)),te=Math.max(0,I[L]?.reasoning.findIndex(e=>e.value===N)??0),R=h?I.findIndex(e=>e.model.value===h.model):-1,ne=R>=0?I[R]?.reasoning.findIndex(e=>e.value===h?.reasoning)??-1:-1,re=p??(R>=0&&ne>=0?{row:R,column:ne}:null)??{row:L,column:te},z=I[re.row]??I[0],ie=Math.min(re.column,Math.max(0,z.reasoning.length-1)),ae=z.reasoning[ie],B=h?l.find(e=>e.value===h.model)??A:A,oe=h?.reasoning??n,V=B.reasoning.filter(e=>e.value!==`ultra`),se=B.reasoning.find(e=>e.value===`ultra`),ce=b.current.get(B.value)||V[V.length-1]?.value||oe,le=B.reasoning.find(e=>e.value===oe)?.label||oe,ue=!!se&&oe===`ultra`,de=_??i,fe=`${(typeof re.x==`number`?re.x:(ie+.5)/Math.max(1,z.reasoning.length))*100}%`,pe=typeof re.y==`number`?re.y:(re.row+.5)/Math.max(1,I.length),me=`${pe*100}%`,he=`${Math.max(0,Math.min(1-1/Math.max(1,I.length),pe-.5/Math.max(1,I.length)))*100}%`,ge=`${100/Math.max(1,I.length)}%`;function H(e){let t=e.currentTarget.getBoundingClientRect(),n=Math.max(0,Math.min(1,(e.clientX-t.left)/Math.max(1,t.width))),r=Math.max(0,Math.min(1,(e.clientY-t.top)/Math.max(1,t.height))),i=Math.max(0,Math.min(I.length-1,Math.floor(r*I.length))),a=I[i]?.reasoning.length||1;return{row:i,column:Math.max(0,Math.min(a-1,Math.floor(n*a))),x:Math.max(.5/a,Math.min(1-.5/a,n)),y:Math.max(.5/I.length,Math.min(1-.5/I.length,r))}}function _e(e){let t=I[e.row],n=t?.reasoning[e.column];t&&n&&ee(t.model,n.value)}function ve(e){a||!r||de===e||(v(e),s(e))}function ye(e){if(a||!se||ue===e)return;let t=e?se.value:ce;g({model:B.value,reasoning:t}),e||b.current.set(B.value,t),o(B.value,t)}function be(e){S.current=e,C.current===null&&(C.current=window.requestAnimationFrame(()=>{C.current=null;let e=S.current;S.current=null,e&&m(e)}))}function xe(){S.current=null,C.current!==null&&(window.cancelAnimationFrame(C.current),C.current=null)}function Se(e,t=!0){let n=x.current;if(!n||n.pointerId!==e.pointerId)return;let r=H(e);x.current=null,xe(),t&&_e(r),m(null),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)}function U(){D.current=w.current?.getBoundingClientRect().height??null,f(e=>!e)}return(0,K.jsxs)(`div`,{className:`code-model-matrix-shell is-${z.model.variant}`,"data-testid":`code-model-matrix-picker`,"data-advanced":d?`open`:`closed`,"data-fast":de?`on`:`off`,"data-ultra":ue?`on`:`off`,children:[(0,K.jsxs)(`div`,{className:`code-model-matrix-stage`,ref:w,children:[(0,K.jsxs)(`div`,{ref:T,className:`code-model-matrix`,"aria-hidden":d,inert:d?!0:void 0,children:[(0,K.jsx)(`div`,{className:`code-model-matrix-head`,style:{"--matrix-columns":z.reasoning.length},"aria-hidden":`true`,children:z.reasoning.map(e=>(0,K.jsx)(`span`,{children:e.label},e.value))}),(0,K.jsx)(`div`,{className:`code-model-matrix-labels`,"aria-hidden":`true`,children:I.map(({model:e})=>(0,K.jsx)(`span`,{className:e.value===z.model.value?`selected`:``,"data-variant":e.variant,children:e.variant.charAt(0).toUpperCase()+e.variant.slice(1)},e.value))}),(0,K.jsxs)(`div`,{className:`code-model-matrix-surface ${p?`is-dragging`:``}`,role:`radiogroup`,"aria-label":`Model and reasoning`,style:{"--matrix-columns":j.length,"--matrix-rows":I.length,"--matrix-selection-x":fe,"--matrix-selection-y":me,"--matrix-selection-row-top":he,"--matrix-selection-row-height":ge},onPointerDown:e=>{a||(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),x.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,dragged:!1})},onPointerMove:e=>{let t=x.current;if(!t||t.pointerId!==e.pointerId)return;if(e.pointerType===`mouse`&&e.buttons===0){Se(e);return}let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);!t.dragged&&n>=XA&&(t.dragged=!0),t.dragged&&be(H(e))},onPointerUp:e=>Se(e),onPointerCancel:e=>Se(e,!1),onLostPointerCapture:e=>{x.current?.pointerId===e.pointerId&&(x.current=null,xe(),m(null))},children:[(0,K.jsx)(`span`,{className:`code-model-matrix-fill`,"data-variant":z.model.variant,"aria-hidden":`true`}),(0,K.jsx)(`div`,{className:`code-model-matrix-cells`,children:I.flatMap(({model:e,reasoning:t},n)=>t.map((r,i)=>{let o=n===re.row&&i===ie,s=o&&!ue;return(0,K.jsx)(`button`,{type:`button`,className:o?`selected`:``,role:`radio`,"data-matrix-cell":!0,"data-testid":`code-model-matrix-cell-${e.variant}-${r.value}`,"aria-label":`${e.label}, ${r.label}`,"aria-checked":s,disabled:a,style:{"--matrix-cell-left":`${i/Math.max(1,t.length)*100}%`,"--matrix-cell-top":`${n/Math.max(1,I.length)*100}%`,"--matrix-cell-width":`${100/Math.max(1,t.length)}%`,"--matrix-cell-height":`${100/Math.max(1,I.length)}%`},onClick:t=>{t.detail===0&&ee(e,r.value)}},`${e.value}:${r.value}`)}))}),(0,K.jsx)(`span`,{className:`code-model-matrix-thumb`,"data-variant":z.model.variant,"aria-hidden":`true`})]}),(0,K.jsx)(`div`,{className:`code-model-matrix-rockers`,children:(0,K.jsx)($A,{label:se?.label||`Ultra`,active:ue,disabled:a,unavailable:!se,unavailableReason:`Ultra is not offered for this model by the active Codex CLI.`,onChange:ye})}),(0,K.jsx)(ej,{active:r&&de,available:r,disabled:a,unavailableReason:`Fast is not offered for this model by the active Codex CLI.`,onChange:ve}),(0,K.jsx)(`span`,{className:`code-model-matrix-current`,"aria-live":`polite`,children:p?`${z.model.label} · ${ae?.label||``}`:h?`${B.label} · ${le}`:`${A.label} · ${F||j[P]?.label}`})]}),(0,K.jsx)(`div`,{ref:E,className:`code-model-matrix-advanced`,"data-testid":`code-model-matrix-advanced`,"aria-hidden":!d,inert:d?void 0:!0,children:c})]}),(0,K.jsxs)(`button`,{type:`button`,className:`code-model-matrix-advanced-toggle`,"data-testid":`code-model-matrix-advanced-toggle`,"aria-expanded":d,onClick:U,children:[(0,K.jsx)(`span`,{children:`Advanced`}),(0,K.jsx)(Ge,{className:d?`expanded`:``})]})]})}var nj=`M8 10.9995C9.654 10.9995 11 9.65351 11 7.99951V3.99951C11 2.34551 9.654 0.999512 8 0.999512C6.346 0.999512 5 2.34551 5 3.99951V7.99951C5 9.65351 6.346 10.9995 8 10.9995ZM6 3.99951C6 2.89651 6.897 1.99951 8 1.99951C9.103 1.99951 10 2.89651 10 3.99951V7.99951C10 9.10251 9.103 9.99951 8 9.99951C6.897 9.99951 6 9.10251 6 7.99951V3.99951ZM13 7.49951V7.99951C13 10.5855 11.02 12.6935 8.5 12.9485V14.4995C8.5 14.7755 8.276 14.9995 8 14.9995C7.724 14.9995 7.5 14.7755 7.5 14.4995V12.9485C4.98 12.6935 3 10.5845 3 7.99951V7.49951C3 7.22351 3.224 6.99951 3.5 6.99951C3.776 6.99951 4 7.22351 4 7.49951V7.99951C4 10.2055 5.794 11.9995 8 11.9995C10.206 11.9995 12 10.2055 12 7.99951V7.49951C12 7.22351 12.224 6.99951 12.5 6.99951C12.776 6.99951 13 7.22351 13 7.49951Z`,rj=`M8 10.9995C9.654 10.9995 11 9.65351 11 7.99951V3.99951C11 2.34551 9.654 0.999512 8 0.999512C6.346 0.999512 5 2.34551 5 3.99951V7.99951C5 9.65351 6.346 10.9995 8 10.9995ZM13 7.49951V7.99951C13 10.5855 11.02 12.6935 8.5 12.9485V14.4995C8.5 14.7755 8.276 14.9995 8 14.9995C7.724 14.9995 7.5 14.7755 7.5 14.4995V12.9485C4.98 12.6935 3 10.5845 3 7.99951V7.49951C3 7.22351 3.224 6.99951 3.5 6.99951C3.776 6.99951 4 7.22351 4 7.49951V7.99951C4 10.2055 5.794 11.9995 8 11.9995C10.206 11.9995 12 10.2055 12 7.99951V7.49951C12 7.22351 12.224 6.99951 12.5 6.99951C12.776 6.99951 13 7.22351 13 7.49951Z`;function ij({listening:e}){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:e?rj:nj})})}function aj(e){return!Number.isFinite(e)||e<0?`0`:e>=1e6?`${Math.round(e/1e5)/10}m`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function oj(e,t){return t===`goal`?e.goalMode:t===`plan`?e.planMode:e.messageMode}function sj(e,t,n){return t===`goal`?e.describeAgentGoal:t===`plan`?e.describePlanFirst:n===`shell`?e.shellCommandPlaceholder:e.askFollowUpChanges}function cj(){return typeof window<`u`&&ae()}function lj(e){return e.trim().replace(/^gpt[-\s]*/i,``)||e}function uj(e,t){return e===`xhigh`&&t.trim().toLowerCase()===`extra high`?`XHigh`:t}function dj(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/60),r=t%60;return`${n}:${String(r).padStart(2,`0`)}`}var fj=[.28,.5,.72,.46,.9,.36,.62,.82,.42,.68,.95,.52,.33,.75,.57,.88,.4,.64,.93,.48,.7,.31,.58,.83];function pj(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M8.85 1.35a.55.55 0 0 1 .55.68L8.28 6.1h3.07a.55.55 0 0 1 .42.9l-5.5 6.6a.55.55 0 0 1-.96-.48l1.12-4.2H3.65a.55.55 0 0 1-.44-.88l5.2-6.48a.55.55 0 0 1 .44-.21ZM4.8 7.9h2.34a.55.55 0 0 1 .53.69l-.63 2.38L10.17 7.1H7.56a.55.55 0 0 1-.53-.7l.62-2.26L4.8 7.9Z`})})}function mj({active:e,agentKind:t,capabilities:n,slashCommands:r,draft:i,attachments:a,composerMode:o,plusMenuOpen:s,approvalMenuOpen:c,modelMenuOpen:l,modelPickerPane:u,agentModelPreset:d,agentModel:f,agentReasoningEffort:p,agentServiceTier:m,agentModelOptions:h,currentPermissionMode:g,permissionModeDisabled:_,modelProfileDisabled:v,currentPermissionLabel:y,currentPermissionColor:b,permissionModeHint:x,currentModelLabel:S,currentReasoningLabel:C,currentSpeedLabel:w,currentReasoningOptions:T,currentServiceTierOptions:E,permissionModeOptions:D,contextWindow:O,pendingFollowUp:k,submitAction:A,speechSupported:j,speechListening:M,textareaRef:N,attachmentInputRef:P,plusMenuRef:F,approvalMenuRef:ee,modelMenuRef:I,onDraftChange:L,onNavigateHistory:te,onRemoveAttachment:R,onSubmit:ne,onInterrupt:re,onSendPendingFollowUp:z,onDiscardPendingFollowUp:ie,onEditPendingFollowUp:B,onPasteAttachment:oe,onAttachmentFiles:V,onChooseAttachmentFile:se,onActivateComposerMode:ce,onClearComposerMode:le,onTogglePlusMenu:ue,onToggleApprovalMenu:de,onToggleModelMenu:fe,onCloseMenus:pe,onSetModelPickerPane:me,onComposerMenuKeyDown:he,onComposerMenuBlur:ge,onUpdatePermissionMode:H,onUpdateModel:_e,onUpdateReasoningEffort:ve,onUpdateServiceTier:ye,onUpdateModelProfile:be,onUpdateServiceTierInline:xe,onToggleSpeechInput:Se,copy:U}){let Ce=e&&(n.plusMenu||n.goalMode),we=e&&n.permissionMode,Te=e&&n.modelPicker,Ee=n.serviceTier&&E.length>0,De=h.map(e=>({value:e.value,label:TA(e,e.value),reasoning:(e.reasoningLevels||[]).map(e=>({value:e.value,label:U.reasoningOptionLabel(e.value,e.label)}))})),Oe=t===`codex`&&!!QA(De,f),[Ae,je]=(0,G.useState)(cj),[Me,Ne]=(0,G.useState)(0),[Pe,Fe]=(0,G.useState)(!1),[Ie,Re]=(0,G.useState)(i.length),[ze,Be]=(0,G.useState)(!1),[He,Ue]=(0,G.useState)(null),[We,Ge]=(0,G.useState)(0),Ke=e&&n.speechInput&&(!Ae||j),qe=(0,G.useRef)(new Map),Je=(0,G.useRef)(null),Xe=(0,G.useRef)(!1),Qe=(0,G.useRef)(0),$e=(0,G.useRef)(i),et=(0,G.useRef)(!1);KA(Je),JA(N,i);let tt=s||c||l,nt=(0,G.useMemo)(()=>HA(i,Ie),[i,Ie]),W=nt?`${nt.trigger}:${nt.start}:${nt.end}:${nt.query}`:``,rt=(0,G.useMemo)(()=>nt?r.filter(e=>UA(e,nt.query,nt.trigger)).sort((e,t)=>WA(e,nt.query)-WA(t,nt.query)):[],[r,nt]),it=e&&Pe&&!tt&&!!nt&&W!==He&&rt.length>0,at=tt||it,ot=rt[We]??rt[0]??null,st=U.permissionModeLabel(g,y),ct=U.reasoningOptionLabel(p,C),lt=U.serviceTierLabel(m,w),ut=lj(S),dt=uj(p,ct),ft=O?`Context window: ${O.percentUsed}% used (${O.percentLeft}% left), ${aj(O.usedTokens)} / ${aj(O.limitTokens)} tokens used`:``,ht=!e||A===`disabled`,gt=e&&A===`interrupt`,_t=nt?.trigger===`$`?`Skills`:`Commands`,vt=Ae&&M&&Ke,yt=j||Ae,bt=()=>{(Ae||ae())&&Be(!0),Se()},xt=()=>{if(et.current){et.current=!1;return}bt()},St=e=>{e.pointerType!==`mouse`&&(e.preventDefault(),et.current=!0,bt())};function Ct(t){if(!e||t instanceof Element&&t.closest(`.code-composer-menu, button, input, select, textarea, [role="menuitem"]`))return;let n=N.current;!n||n.disabled||(n.focus({preventScroll:!0}),Tt(n))}let wt=e=>{Ct(e.target)};(0,G.useEffect)(()=>{Ge(0)},[nt?.query,rt.length]),(0,G.useEffect)(()=>{$e.current=i},[i]),(0,G.useEffect)(()=>{nt||Ue(null)},[nt]),(0,G.useEffect)(()=>{e||(Fe(!1),Ue(null))},[e]),(0,G.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 980px)`),t=()=>je(cj());return t(),window.addEventListener(`resize`,t),e.addEventListener(`change`,t),()=>{window.removeEventListener(`resize`,t),e.removeEventListener(`change`,t)}},[]),(0,G.useEffect)(()=>{if(M||!ze)return;let e=window.setTimeout(()=>Be(!1),3600);return()=>window.clearTimeout(e)},[ze,M]),(0,G.useEffect)(()=>{M&&Be(!1)},[M]),(0,G.useEffect)(()=>{if(!M){Ne(0);return}let e=Date.now();Ne(0);let t=window.setInterval(()=>{Ne(Math.floor((Date.now()-e)/1e3))},250);return()=>window.clearInterval(t)},[M]),(0,G.useEffect)(()=>{!it||!ot||qe.current.get(ot.command)?.scrollIntoView({block:`nearest`})},[it,ot]);function Tt(e=N.current){e&&Re(e.selectionStart??i.length)}function Et(e){if(!nt)return;let t=`${e.command} `,n=`${i.slice(0,nt.start)}${t}${i.slice(nt.end)}`,r=nt.start+t.length;L(n),Re(r),Ue(null),window.requestAnimationFrame(()=>{let e=N.current;e&&(e.focus({preventScroll:!0}),e.setSelectionRange(r,r),Tt(e))})}return(0,K.jsxs)(`footer`,{ref:Je,className:[`code-composer`,at?`menu-open`:``,vt?`recording`:``,a.length>0?`has-attachments`:``,k&&e?`has-pending-followup`:``].filter(Boolean).join(` `),"data-testid":`code-composer`,onClick:wt,children:[k&&e&&(0,K.jsx)(`div`,{className:`code-pending-followup`,"data-testid":`code-pending-followup`,children:k.messages.map(e=>(0,K.jsxs)(`div`,{className:`code-pending-followup-row`,"data-testid":`code-pending-followup-row`,children:[(0,K.jsx)(`span`,{className:`code-pending-followup-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Ve,{})}),(0,K.jsx)(`p`,{children:e.text||e.attachments?.map(e=>e.name).join(`, `)}),(0,K.jsxs)(`div`,{className:`code-pending-followup-actions`,children:[(0,K.jsxs)(`button`,{type:`button`,"data-testid":`code-pending-followup-send-next`,onClick:()=>z(e.id),children:[(0,K.jsx)(Ve,{}),(0,K.jsx)(`span`,{children:U.sendQueuedMessage})]}),(0,K.jsx)(`button`,{type:`button`,className:`icon`,"data-testid":`code-pending-followup-discard`,"aria-label":U.discardQueuedMessage,onClick:()=>ie(e.id),children:(0,K.jsx)(pt,{})}),(0,K.jsx)(`button`,{type:`button`,className:`icon`,"data-testid":`code-pending-followup-edit`,"aria-label":U.editQueuedMessage,onClick:()=>B(e.id),children:(0,K.jsx)(ke,{})})]})]},e.id))}),it&&(0,K.jsxs)(`div`,{className:`code-slash-menu code-composer-menu`,"data-testid":`code-slash-menu`,role:`listbox`,"aria-label":_t,children:[(0,K.jsx)(`div`,{className:`code-slash-menu-header`,children:_t}),rt.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`code-slash-command ${t===We?`active`:``}`,"data-testid":GA(e.command),role:`option`,"aria-selected":t===We,ref:t=>{t?qe.current.set(e.command,t):qe.current.delete(e.command)},onMouseMove:()=>Ge(t),onMouseDown:e=>e.preventDefault(),onClick:()=>Et(e),children:[(0,K.jsx)(`span`,{className:`code-slash-command-icon`,"aria-hidden":`true`,children:nt?.trigger??`/`}),(0,K.jsxs)(`span`,{className:`code-slash-command-copy`,children:[(0,K.jsxs)(`span`,{className:`code-slash-command-title`,children:[(0,K.jsx)(`code`,{children:e.command}),(0,K.jsx)(`strong`,{children:e.label})]}),(0,K.jsx)(`small`,{children:e.description})]}),e.scope&&(0,K.jsx)(`span`,{className:`code-slash-command-source`,children:e.scope})]},e.command))]}),(0,K.jsx)(`textarea`,{"data-testid":`code-composer-input`,ref:N,rows:1,enterKeyHint:`send`,name:`farming-chat-message`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:i,onFocus:e=>{pe(),Fe(!0),Tt(e.currentTarget)},onBlur:()=>Fe(!1),onClick:e=>Tt(e.currentTarget),onKeyUp:e=>Tt(e.currentTarget),onSelect:e=>Tt(e.currentTarget),onCompositionStart:()=>{Xe.current=!0},onCompositionEnd:e=>{Xe.current=!1,Qe.current=Date.now(),$e.current=e.currentTarget.value,Tt(e.currentTarget)},onChange:e=>{$e.current=e.target.value,L(e.target.value),Ue(null),Tt(e.currentTarget)},onPaste:oe,onKeyDown:e=>{let t=Xe.current;if(!LA(e,t)){if(RA(e,Qe.current)){e.preventDefault(),e.stopPropagation();return}if(it){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let t=e.key===`ArrowDown`?1:-1;Ge(e=>(e+t+rt.length)%rt.length);return}if(e.key===`Home`){e.preventDefault(),e.stopPropagation(),Ge(0);return}if(e.key===`End`){e.preventDefault(),e.stopPropagation(),Ge(rt.length-1);return}if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),Ue(W);return}if((e.key===`Enter`||e.key===`Tab`)&&ot){e.preventDefault(),e.stopPropagation(),Et(ot);return}}if(e.key===`ArrowUp`&&e.currentTarget.selectionStart===e.currentTarget.selectionEnd&&e.currentTarget.value.lastIndexOf(`
200
+ `,Math.max(0,e.currentTarget.selectionStart-1))===-1){let t=k?.messages[k.messages.length-1];if(t&&B(t.id)){e.preventDefault(),e.stopPropagation(),window.requestAnimationFrame(()=>{let e=N.current;e&&(e.setSelectionRange(e.value.length,e.value.length),Tt(e))});return}}if(e.key===`ArrowUp`||e.key===`ArrowDown`){let t=e.key===`ArrowUp`?`previous`:`next`,n=te(t,{direction:t,value:e.currentTarget.value,selectionStart:e.currentTarget.selectionStart,selectionEnd:e.currentTarget.selectionEnd});if(n!==null){e.preventDefault(),e.stopPropagation(),window.requestAnimationFrame(()=>{let e=N.current;if(!e)return;let t=n.length;e.setSelectionRange(t,t),Tt(e)});return}}zA(e,t,Qe.current)&&(e.preventDefault(),e.stopPropagation(),ne(BA(e.currentTarget.value,$e.current)))}},placeholder:e?sj(U,o,t):U.openAgentTerminalFirst,disabled:!e}),ze&&!M&&(0,K.jsx)(`div`,{className:`code-composer-dictation-hint`,"data-testid":`code-composer-dictation-hint`,children:U.mobileDictationHint}),(0,K.jsx)(VA,{attachments:a,onRemove:R}),(0,K.jsx)(`input`,{ref:P,className:`code-composer-file-input`,"data-testid":`code-composer-file-input`,type:`file`,multiple:!0,onChange:V}),(0,K.jsx)(`div`,{className:`code-composer-toolbar ${vt?`recording`:``}`,"data-testid":`code-composer-toolbar`,children:vt?(0,K.jsxs)(`div`,{className:`code-composer-recording-bar`,"data-testid":`code-composer-recording`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-composer-recording-stop`,"data-testid":`code-composer-recording-stop`,"aria-label":U.stopDictation,onPointerDown:St,onClick:xt,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})}),(0,K.jsx)(`div`,{className:`code-composer-recording-wave`,"aria-hidden":`true`,children:fj.map((e,t)=>(0,K.jsx)(`span`,{style:{"--voice-bar-scale":e,"--voice-bar-delay":`${t*38}ms`}},t))}),(0,K.jsx)(`span`,{className:`code-composer-recording-time`,children:dj(Me)}),(0,K.jsx)(`button`,{type:`button`,className:`code-composer-send ${gt?`interrupt`:``}`,"data-testid":`code-composer-send`,"data-action":A,"aria-label":gt?U.interruptAgent:U.sendMessage,onClick:gt?re:()=>ne($e.current),disabled:ht,children:gt?(0,K.jsx)(`span`,{className:`code-composer-stop-icon`,"aria-hidden":`true`}):(0,K.jsx)(Ye,{})})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`code-composer-left-tools`,"data-testid":`code-composer-left-tools`,children:[Ce&&(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-composer-add`,"data-testid":`code-composer-add`,"aria-label":U.addContext,"aria-haspopup":`menu`,"aria-expanded":s,disabled:!e,onClick:ue,children:(0,K.jsx)(Le,{})}),s&&(0,K.jsxs)(`div`,{className:`code-plus-menu code-composer-menu`,role:`menu`,"data-testid":`code-composer-plus-menu`,ref:F,onKeyDown:he,onBlur:ge,onMouseDown:e=>e.preventDefault(),children:[n.plusMenu?(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-composer-attach-file`,onClick:se,children:[(0,K.jsx)(`span`,{children:U.attachFile}),(0,K.jsx)(`small`,{children:U.fileContext})]}):null,n.goalMode?(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-composer-goal-mode`,onClick:()=>ce(`goal`),children:[(0,K.jsx)(`span`,{children:U.goalMode}),(0,K.jsx)(`small`,{children:U.setObjective})]}):null,n.plusMenu?(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-composer-plan-mode`,onClick:()=>ce(`plan`),children:[(0,K.jsx)(`span`,{children:U.planMode}),(0,K.jsx)(`small`,{children:U.planFirst})]}):null]})]}),o!==`default`&&(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-mode-chip`,"data-testid":`code-composer-mode-chip`,"aria-label":U.clearComposerMode,onClick:le,children:[(0,K.jsx)(`span`,{children:oj(U,o)}),(0,K.jsx)(`span`,{"aria-hidden":`true`,children:(0,K.jsx)(pt,{})})]}),we&&(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-approval ${b}`,"data-testid":`code-composer-approval`,"aria-label":U.agentPermissionMode,"aria-haspopup":`menu`,"aria-expanded":c,disabled:_,onClick:de,children:[(0,K.jsx)(`span`,{className:`code-tool-icon`,"aria-hidden":`true`,children:(0,K.jsx)(hj,{mode:g})}),(0,K.jsx)(`span`,{className:`code-composer-approval-label`,children:st}),(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(gj,{})})]}),c&&(0,K.jsxs)(`div`,{className:`code-approval-menu code-composer-menu`,role:`menu`,"data-testid":`code-approval-menu`,ref:ee,onKeyDown:he,onBlur:ge,onMouseDown:e=>e.preventDefault(),children:[(0,K.jsxs)(`div`,{className:`code-approval-menu-header`,children:[(0,K.jsx)(`span`,{children:U.permissionsPrompt}),(0,K.jsx)(`small`,{children:x})]}),D.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-approval-option ${e.value===g?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===g,onClick:()=>H(e.value),children:[(0,K.jsx)(`span`,{className:`code-approval-option-icon ${e.color??`muted`}`,"aria-hidden":`true`,children:(0,K.jsx)(hj,{mode:e.value})}),(0,K.jsxs)(`span`,{className:`code-approval-option-copy`,children:[(0,K.jsx)(`span`,{children:U.permissionModeLabel(e.value,e.label)}),(0,K.jsx)(`small`,{children:U.permissionModeDescription(e.value,e.description)})]}),e.value===g&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(Ze,{})})]},e.value))]})]})]}),(0,K.jsxs)(`div`,{className:`code-composer-right-tools`,"data-testid":`code-composer-right-tools`,children:[O&&(0,K.jsxs)(`div`,{className:`code-composer-context-window`,"data-testid":`code-composer-context-window`,tabIndex:0,role:`img`,"aria-label":ft,children:[(0,K.jsx)(`span`,{className:`code-context-window-ring`,"aria-hidden":`true`,style:{"--context-percent":O.percentUsed}}),(0,K.jsxs)(`div`,{className:`code-context-window-popover`,role:`tooltip`,children:[(0,K.jsx)(`span`,{children:`Context window:`}),(0,K.jsxs)(`strong`,{children:[O.percentUsed,`% used (`,O.percentLeft,`% left)`]}),(0,K.jsxs)(`strong`,{children:[aj(O.usedTokens),` / `,aj(O.limitTokens),` tokens used`]})]})]}),Te&&(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor model-picker`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-model-picker`,"data-testid":`code-composer-model-picker`,"data-agent-model-preset":d,"aria-label":U.modelAndReasoning,"aria-haspopup":`menu`,"aria-expanded":l,title:[S,ct,lt].filter(Boolean).join(` · `),onClick:fe,children:[m===`priority`&&(0,K.jsx)(`span`,{className:`code-composer-speed-active`,"aria-hidden":`true`,children:(0,K.jsx)(pj,{})}),(0,K.jsx)(`span`,{className:`code-composer-model-label desktop`,children:S}),(0,K.jsx)(`span`,{className:`code-composer-model-label mobile`,children:ut}),(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted desktop`,children:ct}),(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted mobile`,children:dt}),(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(gj,{})})]}),l&&(0,K.jsx)(`div`,{className:`code-model-picker-menu code-composer-menu ${Oe?`has-matrix`:``}`,role:`menu`,"data-testid":`code-model-menu`,ref:I,onKeyDown:he,onBlur:ge,onMouseDown:e=>e.preventDefault(),children:(0,K.jsx)(tj,{models:De,currentModel:f,currentReasoning:p,fastAvailable:Ee&&E.some(e=>e.value===`priority`),fast:m===`priority`,disabled:v,onSelect:be,onFastChange:e=>xe(e?`priority`:`default`),advanced:(0,K.jsxs)(K.Fragment,{children:[T.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`code-model-menu-header`,children:U.reasoning}),T.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===p?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===p,disabled:v,onClick:()=>ve(e.value),children:[(0,K.jsx)(`span`,{className:`code-model-option-copy`,children:(0,K.jsx)(`span`,{children:U.reasoningOptionLabel(e.value,e.label)})}),e.value===p&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(Ze,{})})]},e.value)),(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`})]}),(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${u===`model`?`selected`:``}`,role:`menuitem`,"data-testid":`code-model-submenu-trigger`,disabled:v,onClick:()=>me(u===`model`?null:`model`),children:[(0,K.jsx)(`span`,{children:S}),(0,K.jsx)(mt,{className:`code-menu-chevron-right`})]}),u===`model`&&(0,K.jsx)(`div`,{className:`code-model-submenu code-composer-menu`,role:`menu`,"data-testid":`code-model-submenu`,onKeyDown:he,children:h.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===f?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===f,disabled:v,onClick:()=>_e(e.value),children:[(0,K.jsx)(`span`,{className:`code-model-option-copy`,children:(0,K.jsx)(`span`,{children:TA(e,e.value)})}),e.value===f&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(Ze,{})})]},e.value))})]}),Ee&&(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${u===`speed`?`selected`:``}`,role:`menuitem`,"data-testid":`code-speed-submenu-trigger`,disabled:v,onClick:()=>me(u===`speed`?null:`speed`),children:[(0,K.jsx)(`span`,{children:U.speed}),(0,K.jsx)(mt,{className:`code-menu-chevron-right`})]}),u===`speed`&&(0,K.jsx)(`div`,{className:`code-speed-submenu code-composer-menu`,role:`menu`,"data-testid":`code-speed-submenu`,onKeyDown:he,children:E.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===m?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===m,disabled:v,onClick:()=>ye(e.value),children:[(0,K.jsxs)(`span`,{className:`code-model-option-copy`,children:[(0,K.jsxs)(`span`,{className:`code-speed-option-label`,children:[e.value===`priority`&&(0,K.jsx)(`span`,{className:`code-speed-option-icon`,"aria-hidden":`true`,children:(0,K.jsx)(pj,{})}),(0,K.jsx)(`span`,{children:U.serviceTierLabel(e.value,e.label)})]}),e.description&&(0,K.jsx)(`small`,{children:U.serviceTierDescription(e.value,e.description)})]}),e.value===m&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(Ze,{})})]},e.value))})]})]})})})]}),Ke&&(0,K.jsx)(`button`,{type:`button`,className:`code-composer-mic ${M?`listening`:``}`,"data-testid":`code-composer-mic`,"aria-label":M?U.stopDictation:j?U.startDictation:U.mobileDictationHint,"aria-pressed":M,onPointerDown:St,onClick:xt,disabled:!e||!yt,title:yt?M?U.stopDictation:j?U.startDictation:U.mobileDictationHint:U.speechUnsupported,children:(0,K.jsx)(ij,{listening:M})}),(0,K.jsx)(`button`,{type:`button`,className:`code-composer-send ${gt?`interrupt`:``}`,"data-testid":`code-composer-send`,"data-action":A,"aria-label":gt?U.interruptAgent:U.sendMessage,onClick:gt?re:()=>ne($e.current),disabled:ht,children:gt?(0,K.jsx)(`span`,{className:`code-composer-stop-icon`,"aria-hidden":`true`}):(0,K.jsx)(Ye,{})})]})]})})]})}function hj({mode:e}){return e===`ask`?(0,K.jsx)(Pe,{className:`code-approval-hand-glyph`}):e===`custom`?(0,K.jsx)(`svg`,{className:`filled`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M7.99997 6C6.89497 6 5.99997 6.895 5.99997 8C5.99997 9.105 6.89497 10 7.99997 10C9.10497 10 9.99997 9.105 9.99997 8C9.99997 6.895 9.10497 6 7.99997 6ZM7.99997 9C7.44797 9 6.99997 8.552 6.99997 8C6.99997 7.448 7.44797 7 7.99997 7C8.55197 7 8.99997 7.448 8.99997 8C8.99997 8.552 8.55197 9 7.99997 9ZM14.565 9.715L13.279 8.628C13.245 8.599 13.213 8.567 13.184 8.533C12.888 8.186 12.931 7.667 13.279 7.372L14.565 6.285C14.693 6.177 14.742 6.003 14.691 5.844C14.386 4.903 13.882 4.04 13.219 3.308C13.139 3.22 13.027 3.172 12.912 3.172C12.865 3.172 12.818 3.18 12.773 3.196L11.186 3.761C11.144 3.776 11.1 3.788 11.056 3.796C11.006 3.805 10.956 3.81 10.907 3.81C10.515 3.81 10.167 3.532 10.094 3.134L9.79097 1.482C9.76097 1.318 9.63397 1.188 9.46997 1.153C8.98997 1.051 8.49897 1 8.00097 1C7.50297 1 7.01097 1.052 6.53097 1.153C6.36697 1.188 6.23997 1.318 6.20997 1.482L5.90797 3.134C5.89997 3.178 5.88797 3.221 5.87297 3.263C5.75197 3.6 5.43397 3.81 5.09397 3.81C5.00197 3.81 4.90797 3.794 4.81597 3.762L3.22897 3.197C3.18397 3.181 3.13597 3.173 3.08997 3.173C2.97497 3.173 2.86297 3.221 2.78297 3.309C2.11897 4.041 1.61597 4.904 1.30997 5.845C1.25797 6.004 1.30797 6.178 1.43597 6.286L2.72197 7.373C2.75597 7.402 2.78797 7.434 2.81697 7.468C3.11297 7.815 3.06997 8.334 2.72197 8.629L1.43597 9.716C1.30797 9.824 1.25897 9.998 1.30997 10.157C1.61497 11.098 2.11897 11.961 2.78297 12.693C2.86297 12.781 2.97497 12.829 3.08997 12.829C3.13697 12.829 3.18397 12.821 3.22897 12.805L4.81597 12.24C4.85797 12.225 4.90197 12.213 4.94597 12.205C4.99597 12.196 5.04597 12.192 5.09497 12.192C5.48697 12.192 5.83497 12.47 5.90797 12.868L6.20997 14.52C6.23997 14.684 6.36697 14.814 6.53097 14.849C7.01097 14.951 7.50297 15.002 8.00097 15.002C8.49897 15.002 8.99097 14.95 9.46997 14.849C9.63397 14.814 9.76097 14.684 9.79097 14.52L10.094 12.868C10.102 12.824 10.114 12.781 10.129 12.739C10.25 12.402 10.568 12.192 10.908 12.192C11 12.192 11.094 12.208 11.186 12.24L12.772 12.805C12.818 12.821 12.865 12.829 12.911 12.829C13.026 12.829 13.138 12.781 13.218 12.693C13.882 11.961 14.385 11.098 14.69 10.157C14.742 9.998 14.692 9.824 14.564 9.716L14.565 9.715ZM12.728 11.726L11.521 11.296C11.323 11.226 11.117 11.19 10.908 11.19C10.139 11.19 9.44697 11.676 9.18797 12.399C9.15397 12.492 9.12897 12.588 9.11097 12.686L8.88097 13.937C8.59097 13.979 8.29597 14 8.00097 14C7.70597 14 7.41097 13.979 7.11997 13.936L6.89097 12.685C6.73197 11.818 5.97697 11.189 5.09497 11.189C4.98697 11.189 4.87697 11.199 4.76597 11.219C4.66897 11.237 4.57397 11.262 4.47997 11.295L3.27297 11.725C2.90497 11.264 2.61097 10.759 2.39397 10.214L3.36797 9.391C3.74097 9.076 3.96797 8.634 4.00797 8.148C4.04797 7.662 3.89497 7.19 3.57797 6.818C3.51397 6.743 3.44297 6.672 3.36797 6.608L2.39397 5.785C2.61097 5.24 2.90497 4.734 3.27297 4.274L4.47997 4.704C4.67797 4.774 4.88397 4.81 5.09397 4.81C5.86297 4.81 6.55497 4.324 6.81397 3.601C6.84797 3.507 6.87297 3.411 6.89097 3.314L7.11997 2.063C7.41097 2.021 7.70597 1.999 8.00097 1.999C8.29597 1.999 8.59097 2.02 8.88097 2.062L9.10997 3.313C9.26897 4.18 10.024 4.809 10.906 4.809C11.014 4.809 11.124 4.799 11.234 4.779C11.331 4.761 11.427 4.736 11.521 4.703L12.728 4.273C13.096 4.733 13.39 5.239 13.607 5.784L12.634 6.607C12.261 6.922 12.033 7.364 11.994 7.85C11.954 8.336 12.107 8.809 12.424 9.18C12.489 9.256 12.559 9.326 12.635 9.39L13.609 10.213C13.392 10.758 13.098 11.264 12.73 11.724L12.728 11.726Z`})}):(0,K.jsxs)(`svg`,{viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[(0,K.jsx)(`path`,{d:`M12 3.6 19 6v5.5c0 4.2-2.7 7.6-7 8.9-4.3-1.3-7-4.7-7-8.9V6l7-2.4Z`}),e===`full`||e===`bypassPermissions`?(0,K.jsx)(`path`,{d:`M12 8v5`}):(0,K.jsx)(`path`,{d:`M9.5 12.4 11.3 14l3.5-4`}),e===`full`||e===`bypassPermissions`?(0,K.jsx)(`path`,{d:`M12 16.4h.01`}):null]})}function gj(){return(0,K.jsx)(Ge,{})}function _j(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function vj({request:e,onRespond:t,copy:n}){let r=e.toolCall?.title||n.acpPermissionTool,i=e.options.filter(e=>e.kind.startsWith(`allow`)),a=e.options.filter(e=>e.kind.startsWith(`reject`)),[o,s]=(0,G.useState)(i.find(e=>e.kind===`allow_once`)?.optionId||i[0]?.optionId||``),[c,l]=(0,G.useState)(!1),u={...e._meta||{},...e.toolCall?._meta||{}},d=_j(u.sandbox_authorization),f=_j(u.sandbox_fallback_authorization),p=u.sandbox_not_applied,m=Array.isArray(d?.network_hosts)?d.network_hosts.map(String):[],h=Array.isArray(d?.write_paths)?d.write_paths.map(String):[],g=e.securityWarnings||[],_=g.length>0&&!c,v=[];return e.toolCall?.rawInput!==void 0&&v.push([`Input`,e.toolCall.rawInput]),e.toolCall?.content!==void 0&&v.push([`Content`,e.toolCall.content]),e.toolCall?.locations!==void 0&&v.push([`Locations`,e.toolCall.locations]),(0,K.jsxs)(`section`,{className:`code-acp-request`,"data-testid":`code-acp-permission-request`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:n.acpPermissionTitle}),(0,K.jsx)(`span`,{children:e.origin===`subagent`?`Subagent · ${e.toolCall?.kind||`tool`}`:e.toolCall?.kind||`tool`})]}),(0,K.jsx)(`p`,{children:r}),v.length>0?(0,K.jsxs)(`details`,{className:`code-acp-permission-details`,children:[(0,K.jsx)(`summary`,{children:`Details`}),v.map(([e,t])=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:e}),(0,K.jsx)(`pre`,{children:typeof t==`string`?t:JSON.stringify(t,null,2)})]},e))]}):null,d?(0,K.jsxs)(`section`,{className:`code-acp-sandbox-details`,"data-testid":`code-acp-sandbox-details`,children:[d.reason?(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Reason from Agent`}),(0,K.jsx)(`span`,{children:d.reason})]}):null,d.unsandboxed?(0,K.jsxs)(`p`,{className:`warning`,children:[(0,K.jsx)(`strong`,{children:`Sandbox`}),(0,K.jsx)(`span`,{children:`Runs without the OS sandbox`})]}):null,d.network_all_hosts||d.network?(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Network`}),(0,K.jsx)(`span`,{children:`Any host`})]}):m.length>0?(0,K.jsxs)(`details`,{children:[(0,K.jsxs)(`summary`,{children:[`Network · `,m.length,` `,m.length===1?`host`:`hosts`]}),(0,K.jsx)(`ul`,{children:m.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsx)(`code`,{children:e})},e))})]}):null,d.allow_fs_write_all?(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Write access`}),(0,K.jsx)(`span`,{children:`Unrestricted workspace writes`})]}):h.length>0?(0,K.jsxs)(`details`,{children:[(0,K.jsxs)(`summary`,{children:[`Write access · `,h.length,` `,h.length===1?`path`:`paths`]}),(0,K.jsx)(`ul`,{children:h.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsx)(`code`,{children:e})},e))})]}):null,d.command?(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{children:`Command`}),(0,K.jsx)(`pre`,{children:d.command})]}):null]}):null,f?(0,K.jsxs)(`section`,{className:`code-acp-sandbox-details warning`,"data-testid":`code-acp-sandbox-fallback`,children:[(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Sandbox unavailable`}),(0,K.jsx)(`span`,{children:f.reason||`The command may run without OS sandboxing.`})]}),f.command?(0,K.jsx)(`pre`,{children:f.command}):null]}):null,p?(0,K.jsx)(`section`,{className:`code-acp-sandbox-details warning`,"data-testid":`code-acp-sandbox-not-applied`,children:(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Sandbox not applied`}),(0,K.jsx)(`span`,{children:typeof p==`string`?p:JSON.stringify(p)})]})}):null,g.length>0?(0,K.jsxs)(`label`,{className:`code-acp-permission-risk`,"data-testid":`code-acp-permission-risk`,children:[(0,K.jsx)(`strong`,{children:`Potentially misleading Unicode`}),g.map(e=>(0,K.jsxs)(`span`,{className:`code-acp-permission-risk-finding`,children:[(0,K.jsx)(`code`,{children:e.displayValue}),e.characters.map(e=>(0,K.jsxs)(`small`,{children:[e.character?`‘${e.character}’ `:``,e.codePoint,` · `,e.description]},`${e.codePoint}:${e.kind}`))]},`${e.targetType}:${e.value}`)),(0,K.jsx)(`input`,{type:`checkbox`,checked:c,onChange:e=>l(e.target.checked)}),(0,K.jsx)(`span`,{children:`I reviewed these targets and wish to proceed.`})]}):null,(0,K.jsxs)(`div`,{className:`code-acp-request-actions`,children:[i.length>1?(0,K.jsx)(gt,{ariaLabel:`Permission scope`,className:`code-acp-permission-select`,value:o,options:i.map(e=>({value:e.optionId,label:e.name})),onChange:s}):null,i.length>0?(0,K.jsx)(`button`,{type:`button`,className:`approve`,disabled:_,onClick:()=>t(e.requestId,o||i[0].optionId,!1),children:i.length===1?i[0].name:n.acpPermissionAllow}):null,a.map(n=>(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,n.optionId,!1),children:n.name},n.optionId)),(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,void 0,!0),children:n.cancel})]})]})}function yj(e){return Array.isArray(e.oneOf)?e.oneOf.map(e=>({value:e.const,label:e.title})):Array.isArray(e.enum)?e.enum.map(e=>({value:e,label:e})):Array.isArray(e.items?.anyOf)?e.items.anyOf.map(e=>({value:e.const,label:e.title})):Array.isArray(e.items?.enum)?e.items.enum.map(e=>({value:e,label:e})):[]}function bj(e){return e.type===`boolean`?e.default===!0:e.type===`array`?Array.isArray(e.default)?e.default:[]:e.type===`number`||e.type===`integer`?typeof e.default==`number`?e.default:``:typeof e.default==`string`?e.default:yj(e)[0]?.value||``}function xj({request:e,onRespond:t}){let n=e.requestedSchema?.properties||{},r=new Set(e.requestedSchema?.required||[]),[i,a]=(0,G.useState)(()=>Object.fromEntries(Object.entries(n).map(([e,t])=>[e,bj(t)]))),[o,s]=(0,G.useState)(``),c=e.requestedSchema?.title||`Input requested`,l=e.mode===`url`&&e.status===`accepted`,u=(0,G.useMemo)(()=>{if(e.mode!==`url`||!e.url)return``;try{let t=new URL(e.url);return[`http:`,`https:`].includes(t.protocol)?t.toString():``}catch{return``}},[e.mode,e.url]);return(0,K.jsxs)(`form`,{className:`code-acp-request code-acp-elicitation`,"data-testid":`code-acp-elicitation`,"data-status":e.status||`pending`,onSubmit:a=>{a.preventDefault();for(let[e,t]of Object.entries(n)){let n=i[e];if(t.type!==`array`)continue;let a=Array.isArray(n)?n:[],o=Math.max(+!!r.has(e),Number(t.minItems||0));if(a.length<o){s(`${t.title||e} needs at least ${o} selection${o===1?``:`s`}.`);return}if(Number.isFinite(t.maxItems)&&a.length>Number(t.maxItems)){s(`${t.title||e} allows at most ${t.maxItems} selections.`);return}}s(``);let o=Object.fromEntries(Object.entries(i).filter(([e,t])=>r.has(e)||(Array.isArray(t)?t.length>0:t!==``)));t(e.requestId,`accept`,o)},children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:c}),(0,K.jsx)(`span`,{children:e.origin===`subagent`?`Subagent · ${e.mode}`:e.mode})]}),(0,K.jsx)(`p`,{children:e.message}),e.requestedSchema?.description?(0,K.jsx)(`small`,{children:e.requestedSchema.description}):null,o?(0,K.jsx)(`small`,{className:`code-acp-elicitation-error`,role:`alert`,children:o}):null,e.mode===`url`?u?(0,K.jsx)(`a`,{className:`code-acp-elicitation-link`,href:u,target:`_blank`,rel:`noreferrer`,children:`Open secure link`}):(0,K.jsx)(`small`,{role:`alert`,children:`The Agent provided an unsupported link.`}):(0,K.jsx)(`div`,{className:`code-acp-request-questions`,children:Object.entries(n).map(([e,t])=>{let n=yj(t),o=t.title||e;return t.type===`boolean`?(0,K.jsxs)(`label`,{className:`code-acp-elicitation-checkbox`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:i[e]===!0,onChange:t=>a(n=>({...n,[e]:t.target.checked}))}),(0,K.jsx)(`span`,{children:o}),t.description?(0,K.jsx)(`small`,{children:t.description}):null]},e):t.type===`array`?(0,K.jsxs)(`fieldset`,{children:[(0,K.jsx)(`legend`,{children:o}),n.map(t=>{let n=Array.isArray(i[e])?i[e]:[];return(0,K.jsxs)(`label`,{className:`code-acp-elicitation-checkbox`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:n.includes(t.value),onChange:r=>a(i=>({...i,[e]:r.target.checked?[...n,t.value]:n.filter(e=>e!==t.value)}))}),(0,K.jsx)(`span`,{children:t.label})]},t.value)})]},e):n.length>0?(0,K.jsxs)(`div`,{className:`code-acp-select-question`,children:[(0,K.jsx)(gt,{label:o,value:String(i[e]??``),required:r.has(e),options:n,onChange:t=>a(n=>({...n,[e]:t}))}),t.description?(0,K.jsx)(`small`,{children:t.description}):null]},e):(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:o}),(0,K.jsx)(`input`,{type:t.type===`number`||t.type===`integer`?`number`:t.format===`email`?`email`:t.format===`date`?`date`:t.format===`date-time`?`datetime-local`:t.format===`uri`?`url`:`text`,value:String(i[e]??``),required:r.has(e),min:t.minimum??void 0,max:t.maximum??void 0,minLength:t.minLength??void 0,maxLength:t.maxLength??void 0,pattern:t.pattern??void 0,step:t.type===`integer`?1:t.type===`number`?`any`:void 0,onChange:n=>a(r=>({...r,[e]:t.type===`number`||t.type===`integer`?n.target.value===``?``:n.target.valueAsNumber:n.target.value}))}),t.description?(0,K.jsx)(`small`,{children:t.description}):null]},e)})}),l?(0,K.jsx)(`small`,{className:`code-acp-elicitation-waiting`,children:`Waiting for the Agent to confirm completion…`}):(0,K.jsxs)(`div`,{className:`code-acp-request-actions`,children:[(0,K.jsx)(`button`,{type:`submit`,className:`approve`,disabled:e.mode===`url`&&!u,children:e.mode===`url`?`Continue`:`Submit`}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,`decline`),children:`Decline`}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,`cancel`),children:`Cancel`})]})]})}function Sj(e){return e.ctrlKey&&e.key.toLowerCase()===`c`?``:e.key===`Tab`?` `:e.key===`Escape`?`\x1B`:e.key===`ArrowUp`?`\x1B[A`:e.key===`ArrowDown`?`\x1B[B`:``}function Cj({agentId:e,authTerminal:t}){let[n,i]=(0,G.useState)(``),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(``),l=(0,G.useRef)(null),u=t.terminal,d=t.state===`running`&&!u?.exitStatus&&u?.interactive===!0;(0,G.useEffect)(()=>{let e=l.current;e&&(e.scrollTop=e.scrollHeight)},[u?.output]);let f=async n=>{if(!(!d||!n||a)){o(!0);try{let i=await fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t.terminalId)}/input`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({input:n})}),a=await i.json().catch(()=>null);if(!i.ok)throw Error(a?.error||`Failed to send terminal input (${i.status})`);c(``)}catch(e){c(e instanceof Error?e.message:`Failed to send terminal input`)}finally{o(!1)}}};return(0,K.jsxs)(`div`,{className:`code-acp-auth-terminal`,"data-testid":`code-acp-auth-terminal`,children:[(0,K.jsxs)(`div`,{className:`code-acp-auth-terminal-heading`,children:[(0,K.jsx)(`strong`,{children:t.name||`Sign in`}),(0,K.jsx)(`span`,{children:t.state===`running`?`Waiting for sign-in`:t.state})]}),(0,K.jsx)(`pre`,{ref:l,"data-testid":`code-acp-auth-terminal-output`,children:u?.output||`Starting sign-in…`}),d?(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=n;t&&(i(``),f(`${t}\r`))},children:[(0,K.jsx)(`input`,{"aria-label":`Terminal sign-in input`,autoComplete:`off`,"data-testid":`code-acp-auth-terminal-input`,disabled:a,value:n,onChange:e=>i(e.currentTarget.value),onKeyDown:e=>{let t=Sj(e);t&&(e.preventDefault(),f(t))}}),(0,K.jsx)(`button`,{type:`submit`,disabled:a||!n,children:`Send`})]}):null,t.error||s?(0,K.jsx)(`small`,{className:`code-acp-auth-terminal-error`,children:t.error||s}):null]})}function wj({agentId:e,methods:t,authTerminal:n,agentName:r,authenticatingId:i,onAuthenticate:a}){if(t.length===0&&!n)return null;let o=t.filter(e=>!e.type||e.type===`agent`||e.type===`terminal`),s=t.filter(e=>e.type===`env_var`);return(0,K.jsxs)(`section`,{className:`code-acp-request code-acp-authentication`,"data-testid":`code-acp-authentication`,role:`alert`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsxs)(`strong`,{children:[`Sign in to `,r||`Agent`]}),(0,K.jsx)(`span`,{children:`Authentication required`})]}),(0,K.jsxs)(`div`,{className:`code-acp-authentication-methods`,children:[n?(0,K.jsx)(Cj,{agentId:e,authTerminal:n}):null,o.map(e=>(0,K.jsxs)(`div`,{className:`code-acp-authentication-method`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:e.name||e.id}),e.description?(0,K.jsx)(`small`,{children:e.description}):null,e.link?(0,K.jsx)(`a`,{href:e.link,target:`_blank`,rel:`noreferrer`,children:`Get credentials`}):null]}),(0,K.jsx)(`button`,{type:`button`,disabled:!!i,onClick:()=>a(e.id),children:i===e.id||n?.methodId===e.id&&n.state===`running`?`Signing in…`:`Authenticate`})]},e.id)),s.map(e=>(0,K.jsx)(`div`,{className:`code-acp-authentication-method unsupported`,children:(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:e.name||e.id}),e.description?(0,K.jsx)(`small`,{children:e.description}):null,e.type===`env_var`?(0,K.jsxs)(`small`,{children:[`Set `,e.vars?.map(e=>e.label||e.name).join(`, `)||`the requested environment variables`,` and restart the Agent.`]}):null,e.link?(0,K.jsx)(`a`,{href:e.link,target:`_blank`,rel:`noreferrer`,children:`Get credentials`}):null]})},e.id))]})]})}function Tj(e){return e.options.flatMap(e=>`options`in e?e.options:[e])}function Ej(e,t){return t.test(`${e.id} ${e.name} ${e.category||``}`)}function Dj(e,t){return e.configOptions.find(e=>e.type===`select`&&Ej(e,t))}function Oj(e,t){return e.configOptions.find(e=>e.type===`boolean`&&Ej(e,t))}function kj(e){return e?Tj(e).find(t=>t.value===e.currentValue):void 0}function Aj(e){return e.trim().replace(/^gpt[-\s]*/i,``)||e}function jj({modeId:e}){return e===`read-only`||e===`plan`?(0,K.jsxs)(`svg`,{viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[(0,K.jsx)(`path`,{d:`M3.5 12s3.1-5 8.5-5 8.5 5 8.5 5-3.1 5-8.5 5-8.5-5-8.5-5Z`}),(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`2.4`})]}):e===`default`?(0,K.jsx)(Pe,{className:`code-approval-hand-glyph`}):(0,K.jsxs)(`svg`,{viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[(0,K.jsx)(`path`,{d:`M12 3.6 19 6v5.5c0 4.2-2.7 7.6-7 8.9-4.3-1.3-7-4.7-7-8.9V6l7-2.4Z`}),e===`agent-full-access`||e===`bypassPermissions`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M12 8v5`}),(0,K.jsx)(`path`,{d:`M12 16.4h.01`})]}):e===`dontAsk`?(0,K.jsx)(`path`,{d:`M9.5 12h5`}):[`agent`,`auto`,`acceptEdits`,`build`].includes(e)?(0,K.jsx)(`path`,{d:`m9.5 12.4 1.8 1.6 3.5-4`}):(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`2.4`})]})}function Mj(e){return[`agent`,`auto`,`acceptEdits`,`build`].includes(e)?`blue`:[`agent-full-access`,`bypassPermissions`].includes(e)?`orange`:`muted`}function Nj(e){return e.configOptions.find(e=>e.type===`select`&&(e.id===`mode`||e.category===`mode`))}function Pj(e,t){return e.provider===`qoder`&&e.agentInfo?.version===`1.0.43`?t.filter(e=>e.id!==`plan`):t}function Fj({option:e,currentValue:t,label:n,onSelect:r}){return Tj(e).map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===t?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===t,onClick:()=>r(e.value),children:[(0,K.jsx)(`span`,{className:`code-model-option-copy`,children:(0,K.jsx)(`span`,{children:n(e)})}),e.value===t?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(Ze,{})}):null]},e.value))}function Ij({session:e,updatingId:t,copy:n,open:r,onToggle:i,onSetMode:a,onSetConfigOption:o}){let s=e.modes?.availableModes||[],c=Nj(e),l=s.length===0&&!!c,u=Pj(e,s.length>0?s:c?Tj(c).map(e=>({id:e.value,name:e.name,description:e.description})):[]);if(u.length===0)return null;let d=e.currentModeId||e.modes?.currentModeId||c?.currentValue||``,f=u.find(e=>e.id===d)||u[0],p=n.acpModeLabel(f?.id||d,f?.name||d),m=f?.description?n.acpModeDescription(f.id,f.description):``;return(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-approval ${Mj(d)}`,"data-testid":`code-acp-mode`,"data-acp-value":d,"aria-label":n.agentPermissionMode,"aria-haspopup":`menu`,"aria-expanded":r,disabled:!!t,onClick:i,children:[(0,K.jsx)(`span`,{className:`code-tool-icon`,"aria-hidden":`true`,children:(0,K.jsx)(jj,{modeId:d})}),(0,K.jsx)(`span`,{className:`code-composer-approval-label`,children:p}),(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(Ge,{})})]}),r?(0,K.jsxs)(`div`,{className:`code-approval-menu code-composer-menu`,role:`menu`,"data-testid":`code-acp-mode-menu`,children:[(0,K.jsxs)(`div`,{className:`code-approval-menu-header`,children:[(0,K.jsx)(`span`,{children:n.agentPermissionMode}),m?(0,K.jsx)(`small`,{children:m}):null]}),u.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-approval-option ${e.id===d?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.id===d,onClick:()=>l&&c?o(c.id,e.id):a(e.id),children:[(0,K.jsx)(`span`,{className:`code-approval-option-icon ${Mj(e.id)}`,"aria-hidden":`true`,children:(0,K.jsx)(jj,{modeId:e.id})}),(0,K.jsxs)(`span`,{className:`code-approval-option-copy`,children:[(0,K.jsx)(`span`,{children:n.acpModeLabel(e.id,e.name)}),e.description?(0,K.jsx)(`small`,{children:n.acpModeDescription(e.id,e.description)}):null]}),e.id===d?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(Ze,{})}):null]},e.id))]}):null]})}function Lj({session:e,updatingId:t,copy:n,open:r,pane:i,onToggle:a,onSetPane:o,onSetConfigOption:s,onSetProfile:c,onSetFast:l}){let u=Dj(e,/(^|[\s_-])model([\s_-]|$)/i),d=Dj(e,/(reasoning|thought)/i),f=Oj(e,/(fast|speed)/i),p=e.configOptions.filter(e=>e!==u&&e!==d&&e!==f&&e.category!==`mode`&&e.id!==`mode`),m=kj(u),h=kj(d),g=u&&d?Tj(u).map(e=>({value:e.value,label:e.name,reasoning:Tj(d).map(e=>({value:e.value,label:n.reasoningOptionLabel(e.value,e.name)}))})):[],_=!!QA(g,u?.currentValue||``);if(!u&&!d&&!f&&p.length===0)return null;let v=!!t;return(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor model-picker`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-model-picker`,"data-testid":`code-acp-model-picker`,"data-agent-model-preset":`${u?.currentValue||``}:${d?.currentValue||``}`,"aria-label":n.modelAndReasoning,"aria-haspopup":`menu`,"aria-expanded":r,disabled:v,title:[m?.name,h?.name,f?.currentValue?f.name:``].filter(Boolean).join(` · `),onClick:a,children:[f?.currentValue?(0,K.jsx)(`span`,{className:`code-composer-speed-active`,"aria-hidden":`true`,children:(0,K.jsx)(De,{})}):null,(0,K.jsx)(`span`,{className:`code-composer-model-label desktop`,children:Aj(m?.name||u?.currentValue||`Model`)}),(0,K.jsx)(`span`,{className:`code-composer-model-label mobile`,children:Aj(m?.name||u?.currentValue||`Model`)}),h?(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted desktop`,children:h.name}):null,h?(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted mobile`,children:h.name}):null,(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(Ge,{})})]}),r?(0,K.jsx)(`div`,{className:`code-model-picker-menu code-composer-menu ${_?`has-matrix`:``}`,role:`menu`,"data-testid":`code-acp-model-menu`,children:(0,K.jsx)(tj,{models:g,currentModel:u?.currentValue||``,currentReasoning:d?.currentValue||``,fastAvailable:!!f,fast:f?.currentValue===!0,disabled:v,onSelect:(e,t)=>{u&&d&&c(u.id,e,d.id,t)},onFastChange:e=>{f&&l(f.id,e)},advanced:(0,K.jsxs)(K.Fragment,{children:[d?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`code-model-menu-header`,children:n.reasoning}),(0,K.jsx)(Fj,{option:d,currentValue:d.currentValue,label:e=>n.reasoningOptionLabel(e.value,e.name),onSelect:e=>s(d.id,e)}),(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`})]}):null,u?(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${i===`model`?`selected`:``}`,role:`menuitem`,"data-testid":`code-acp-model-submenu-trigger`,onClick:()=>o(i===`model`?null:`model`),children:[(0,K.jsx)(`span`,{children:m?.name||u.currentValue}),(0,K.jsx)(mt,{className:`code-menu-chevron-right`})]}),i===`model`?(0,K.jsx)(`div`,{className:`code-model-submenu code-composer-menu`,role:`menu`,"data-testid":`code-acp-model-submenu`,children:(0,K.jsx)(Fj,{option:u,currentValue:u.currentValue,label:e=>e.name,onSelect:e=>s(u.id,e)})}):null]}):null,f?(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${i===`speed`?`selected`:``}`,role:`menuitem`,"data-testid":`code-acp-speed-submenu-trigger`,onClick:()=>o(i===`speed`?null:`speed`),children:[(0,K.jsx)(`span`,{children:n.speed}),(0,K.jsx)(mt,{className:`code-menu-chevron-right`})]}),i===`speed`?(0,K.jsx)(`div`,{className:`code-speed-submenu code-composer-menu`,role:`menu`,"data-testid":`code-acp-speed-submenu`,children:[!1,!0].map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${f.currentValue===e?`selected`:``}`,role:`menuitemradio`,"aria-checked":f.currentValue===e,onClick:()=>s(f.id,e),children:[(0,K.jsxs)(`span`,{className:`code-model-option-copy`,children:[(0,K.jsxs)(`span`,{className:`code-speed-option-label`,children:[e?(0,K.jsx)(`span`,{className:`code-speed-option-icon`,"aria-hidden":`true`,children:(0,K.jsx)(De,{})}):null,(0,K.jsx)(`span`,{children:e?f.name:n.serviceTierLabel(`default`,`Standard`)})]}),(0,K.jsx)(`small`,{children:e?f.description||n.serviceTierDescription(`priority`,``):n.serviceTierDescription(`default`,``)})]}),f.currentValue===e?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(Ze,{})}):null]},String(e)))}):null]}):null,p.map(e=>e.type===`select`?(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`}),(0,K.jsx)(`div`,{className:`code-model-menu-header`,children:e.name}),(0,K.jsx)(Fj,{option:e,currentValue:e.currentValue,label:e=>e.name,onSelect:t=>s(e.id,t)})]},e.id):(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.currentValue?`selected`:``}`,role:`menuitemcheckbox`,"aria-checked":e.currentValue,onClick:()=>s(e.id,!e.currentValue),children:[(0,K.jsxs)(`span`,{className:`code-model-option-copy`,children:[(0,K.jsx)(`span`,{children:e.name}),e.description?(0,K.jsx)(`small`,{children:e.description}):null]}),e.currentValue?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(Ze,{})}):null]},e.id))]})})}):null]})}function Rj(e){let t=Number(e?.used),n=Number(e?.size);if(!Number.isFinite(t)||t<0||!Number.isFinite(n)||n<=0)return null;let r=t/n,i=Math.max(0,Math.min(100,Math.round(r*100))),a=Number(e?.cost?.amount),o=String(e?.cost?.currency||``).trim().toUpperCase(),s=Number.isFinite(a)&&a>=0&&/^[A-Z]{3}$/.test(o)?`${a.toLocaleString(`en-US`,{maximumFractionDigits:4})} ${o}`:``;return{usedTokens:t,limitTokens:n,percentUsed:i,percentLeft:100-i,costLabel:s,level:r>=1?`critical`:r>=.85?`warning`:`normal`}}function zj(e){return(Array.isArray(e.configOptions)?e.configOptions:typeof e.configId==`string`&&(typeof e.value==`string`||typeof e.value==`boolean`)?[{configId:e.configId,value:e.value}]:[]).flatMap(e=>e&&typeof e==`object`&&`configId`in e&&typeof e.configId==`string`&&`value`in e&&(typeof e.value==`string`||typeof e.value==`boolean`)?[{configId:e.configId,value:e.value}]:[])}function Bj(e,t){return t.length===0?!0:e?t.every(t=>e.some(e=>e.id===t.configId&&typeof e.currentValue==typeof t.value&&e.currentValue===t.value)):!1}function Vj(e,t){if(!e)return e;let n=zj(t);if(n.length===0)return e;let r=new Map(n.map(e=>[e.configId,e.value]));return r.size===0?e:{...e,configOptions:e.configOptions.map(e=>{let t=r.get(e.id);return t===void 0||typeof t!=typeof e.currentValue?e:{...e,currentValue:t}})}}function Hj(e){let t=Vj(e,{configOptions:e.deferredConfigOptions||[]})||e;return e.deferredModeId?{...t,currentModeId:e.deferredModeId,modes:t.modes?{...t.modes,currentModeId:e.deferredModeId}:t.modes}:t}function Uj(e,t,n){let[i,a]=(0,G.useState)(null),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(``),[u,d]=(0,G.useState)(``),[f,p]=(0,G.useState)(!1),[m,h]=(0,G.useState)(!1),g=(0,G.useRef)(null),_=(0,G.useRef)({agentId:e,active:t}),v=(0,G.useRef)(0),y=(0,G.useRef)(null),b=(0,G.useRef)(0),x=(0,G.useRef)(null),S=(0,G.useRef)(0);_.current={agentId:e,active:t},(0,G.useEffect)(()=>{g.current=i},[i]);let C=(0,G.useCallback)(async n=>{if(!e||!t)return;let i=e,o=b.current,c=v.current+1;v.current=c;try{let t=await fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-session?includeEntries=0`),{signal:n}),l=await t.json().catch(()=>null);if(!t.ok||!l?.session)throw Error(l?.error||`Failed to read ACP session (${t.status})`);if(_.current.agentId!==i||!_.current.active||v.current!==c||y.current||b.current!==o)return;let u=Hj(l.session);g.current=u,a(u),h((l.session.deferredConfigOptions?.length||0)>0||!!l.session.deferredModeId),s(``)}catch(e){if(e instanceof DOMException&&e.name===`AbortError`||_.current.agentId!==i||!_.current.active||v.current!==c||y.current||b.current!==o)return;s(e instanceof Error?e.message:`Failed to read ACP session`)}},[t,e]);(0,G.useEffect)(()=>{v.current+=1,b.current+=1,y.current=null,S.current+=1,x.current=null,g.current=null,a(null),s(``),l(``),d(``),p(!1),h(!1)},[t,e]),(0,G.useEffect)(()=>{let e=new AbortController;return C(e.signal),()=>e.abort()},[C,n]),(0,G.useEffect)(()=>{if(!i?.authTerminal||![`running`,`completed`].includes(i.authTerminal.state))return;let e=window.setInterval(()=>{C()},500);return()=>window.clearInterval(e)},[C,i?.authTerminal?.state,i?.authTerminal?.terminalId]);let w=(0,G.useCallback)(async(t,n)=>{if(!e||y.current)return!1;let i=e,o=++b.current;y.current={agentId:i,id:t,sequence:o};let c=g.current,u=Vj(c,n),d=zj(n);u!==c&&(g.current=u,a(u)),l(t);try{let t=await fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-session`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}),c=await t.json().catch(()=>null);if(!t.ok)throw Error(c?.error||`Failed to update ACP session (${t.status})`);if(c?.deferred!==!0&&!Bj(c?.configOptions,d))throw Error(`ACP Agent did not confirm the requested configuration`);return _.current.agentId!==i||y.current?.sequence!==o?!1:(a(e=>{let t=e&&{...e,...c?.modeId?{currentModeId:c.modeId,modes:e.modes?{...e.modes,currentModeId:c.modeId}:e.modes}:{},...c?.configOptions&&c.deferred!==!0?{configOptions:c.configOptions}:{},...c?.deferredConfigOptions?{deferredConfigOptions:c.deferredConfigOptions}:{},...typeof c?.deferredModeId==`string`?{deferredModeId:c.deferredModeId}:{}};return g.current=t,t}),s(``),h((c?.deferredConfigOptions?.length||0)>0||!!c?.deferredModeId),!0)}catch(e){return c&&_.current.agentId===i&&y.current?.sequence===o&&(g.current=c,a(c)),_.current.agentId===i&&_.current.active&&y.current?.sequence===o&&s(e instanceof Error?e.message:`Failed to update ACP session`),!1}finally{y.current?.sequence===o&&(y.current=null,l(``))}},[e]),T=(0,G.useCallback)(e=>w(`mode`,{modeId:e}),[w]),E=(0,G.useCallback)((e,t)=>w(e,{configId:e,value:t}),[w]),D=(0,G.useCallback)(e=>w(e.map(e=>e.configId).join(`:`),{configOptions:e}),[w]),O=(0,G.useCallback)(async n=>{if(!e||!t||x.current)return!1;let i=e,a=++S.current;x.current={agentId:i,sequence:a},d(n);try{let e=await fetch(r(`/api/agents/${encodeURIComponent(i)}/acp-session/authenticate`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({methodId:n})}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||`Failed to authenticate ACP Agent (${e.status})`);return _.current.agentId!==i||!_.current.active||x.current?.sequence!==a?!1:(s(``),await C(),_.current.agentId===i&&_.current.active&&x.current?.sequence===a)}catch(e){return _.current.agentId===i&&_.current.active&&x.current?.sequence===a&&s(e instanceof Error?e.message:`Failed to authenticate ACP Agent`),!1}finally{x.current?.sequence===a&&(x.current=null,d(``))}},[t,e,C]),k=(0,G.useCallback)(async()=>{if(!e||!t||x.current)return!1;let n=e,i=++S.current;x.current={agentId:n,sequence:i},p(!0);try{let e=await fetch(r(`/api/agents/${encodeURIComponent(n)}/acp-session/logout`),{method:`POST`}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||`Failed to log out ACP Agent (${e.status})`);return _.current.agentId!==n||!_.current.active||x.current?.sequence!==i?!1:(s(``),await C(),_.current.agentId===n&&_.current.active&&x.current?.sequence===i)}catch(e){return _.current.agentId===n&&_.current.active&&x.current?.sequence===i&&s(e instanceof Error?e.message:`Failed to log out ACP Agent`),!1}finally{x.current?.sequence===i&&(x.current=null,p(!1))}},[t,e,C]);return{session:i,error:o,updatingId:c,authenticatingId:u,loggingOut:f,configDeferred:m,configOptionsDeferred:!!i?.deferredConfigOptions?.length,modeDeferred:!!i?.deferredModeId,setMode:T,setConfigOption:E,setConfigOptions:D,authenticate:O,logout:k}}function Wj(e,t){let n=HA(e,t);if(n)return n;let r=Math.max(0,Math.min(t,e.length)),i=e.lastIndexOf(`
201
+ `,Math.max(0,r-1))+1,a=e.slice(i,r).match(/^(\s*)\/(\$[A-Za-z0-9._:-]*)$/);return a?{start:i+(a[1]?.length??0),end:r,query:a[2]??``,trigger:`/`}:null}function Gj(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M2.5 2h1v7.5c0 .55.45 1 1 1H6v1H4.5a2 2 0 0 1-2-2V2Zm3 1h6v1h-6V3Zm0 3h4v1h-4V6Zm3 4h3.3l-1.4-1.4.7-.7 2.6 2.6-2.6 2.6-.7-.7 1.4-1.4H8.5v-1Z`})})}function Kj(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fillRule:`evenodd`,clipRule:`evenodd`,d:`M6 2h4l.5.5V4H13v1h-1l-.6 8.5-.5.5H5.1l-.5-.5L4 5H3V4h2.5V2.5L6 2Zm.5 2h3V3h-3v1ZM5 5l.57 8h4.86L11 5H5Zm1.5 1h1v5h-1V6Zm2 0h1v5h-1V6Z`})})}function qj({active:e,agentId:t,runtimeState:n,sessionUpdatedAt:r,runtimeError:i,draft:a,attachments:o,composerMode:s,contextWindow:c,pendingFollowUp:l,submissions:u,canSteerPendingFollowUp:d,submitAction:f,textareaRef:p,attachmentInputRef:m,permissions:h,elicitations:g,activeElicitations:_,speechSupported:v,speechListening:y,onDraftChange:b,onNavigateHistory:x,onRemoveAttachment:S,onSubmit:C,onInterrupt:w,onDiscardPendingFollowUp:T,onEditPendingFollowUp:E,onSteerPendingFollowUp:D,onRetrySubmission:O,onDiscardSubmission:k,onToggleSpeechInput:A,onPasteAttachment:j,onAttachmentFiles:M,onChooseAttachmentFile:N,onActivateComposerMode:P,onClearComposerMode:F,onRespondToPermission:ee,onRespondToElicitation:I,copy:L}){let te=(0,G.useRef)(!1),R=(0,G.useRef)(0),ne=(0,G.useRef)(a),re=(0,G.useRef)(null),[z,ie]=(0,G.useState)(!1),[ae,B]=(0,G.useState)(a.length),[oe,V]=(0,G.useState)(0),[se,ce]=(0,G.useState)(null),[le,ue]=(0,G.useState)(null),{session:de,error:fe,updatingId:pe,authenticatingId:me,loggingOut:he,configDeferred:ge,configOptionsDeferred:H,modeDeferred:_e,setMode:ve,setConfigOption:ye,setConfigOptions:be,authenticate:xe,logout:Se}=Uj(t,e,`${n}:${r||``}`);KA(re),JA(p,a),ne.current=a;let U=f===`interrupt`,Ce=f===`disabled`,we=(0,G.useMemo)(()=>Wj(a,ae),[a,ae]),Te=(0,G.useMemo)(()=>{if(!we)return[];let e=we.query.toLowerCase();return(de?.availableCommands||[]).filter(t=>{let n=t.name.toLowerCase();return we.trigger===`$`&&!n.startsWith(`$`)?!1:(we.trigger===`$`?n.slice(1):n).startsWith(e)||t.description.toLowerCase().includes(e)}).slice(0,12)},[we,de?.availableCommands]),Ee=e&&z&&Te.length>0,De=Te[oe]||Te[0]||null;(0,G.useEffect)(()=>V(0),[we?.query,we?.trigger,Te.length]),(0,G.useEffect)(()=>{if(!se)return;let e=e=>{e.target instanceof Node&&re.current?.contains(e.target)||(ce(null),ue(null))};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[se]);let Oe=e=>{if(!we)return;let t=`/${e} `,n=`${a.slice(0,we.start)}${t}${a.slice(we.end)}`,r=we.start+t.length;ce(null),ne.current=n,b(n),window.requestAnimationFrame(()=>{p.current?.focus({preventScroll:!0}),p.current?.setSelectionRange(r,r),B(r)})},Ae=e=>{if(!LA(e,te.current)){if(RA(e,R.current)){e.preventDefault(),e.stopPropagation();return}if(Ee&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault();let t=e.key===`ArrowDown`?1:-1;V(e=>(e+t+Te.length)%Te.length);return}if(Ee&&e.key===`Home`){e.preventDefault(),V(0);return}if(Ee&&e.key===`End`){e.preventDefault(),V(Te.length-1);return}if(Ee&&(e.key===`Enter`||e.key===`Tab`)&&De){e.preventDefault(),e.stopPropagation(),Oe(De.name);return}if(e.key===`ArrowUp`&&e.currentTarget.selectionStart===e.currentTarget.selectionEnd&&e.currentTarget.value.lastIndexOf(`
202
+ `,Math.max(0,e.currentTarget.selectionStart-1))===-1){let t=l?.messages[l.messages.length-1];if(t&&E(t.id)){e.preventDefault(),e.stopPropagation(),window.requestAnimationFrame(()=>{let e=p.current;e&&e.setSelectionRange(e.value.length,e.value.length)});return}}if(e.key===`ArrowUp`||e.key===`ArrowDown`){let t=e.key===`ArrowUp`?`previous`:`next`,n=x(t,{direction:t,value:e.currentTarget.value,selectionStart:e.currentTarget.selectionStart,selectionEnd:e.currentTarget.selectionEnd});if(n!==null){e.preventDefault(),e.stopPropagation(),window.requestAnimationFrame(()=>{let e=p.current;if(!e)return;let t=n.length;e.setSelectionRange(t,t)});return}}zA(e,te.current,R.current)&&(e.preventDefault(),e.stopPropagation(),C(BA(e.currentTarget.value,ne.current),{oppositeFollowUpBehavior:e.metaKey||e.ctrlKey}))}},je=e=>{ce(t=>t===e?null:e),ue(null)},Me=t=>{e&&(t.target instanceof Element&&t.target.closest(`.code-composer-menu, button, input, select, textarea, [role="menuitem"]`)||p.current?.focus({preventScroll:!0}))},Ne=Rj(de?.usage),Pe=Ne||c,Fe=Ne?.level||(Pe&&Pe.percentUsed>=100?`critical`:Pe&&Pe.percentUsed>=85?`warning`:`normal`),Ie=Pe?[`Context window: ${Pe.percentUsed}% used (${Pe.percentLeft}% left), ${aj(Pe.usedTokens)} / ${aj(Pe.limitTokens)} tokens used`,Fe===`critical`?`Context window is full`:Fe===`warning`?`Context window is nearly full`:``,Ne?.costLabel?`Session cost: ${Ne.costLabel}`:``].filter(Boolean).join(`. `):``,Re=de?.errorKind===`authentication`||/\b(?:auth(?:entication)?|login|sign[ -]?in|unauthorized|401)\b/i.test(i),ze=i.startsWith(`Deferred session change was not applied:`),Be=e&&!!(h.length||g.length||_.length||Re||ze||fe),He=[`code-composer`,`code-acp-composer`,se?`menu-open`:``,o.length>0?`has-attachments`:``,(l||u.length>0)&&e?`has-pending-followup`:``,Be?`has-acp-request`:``].filter(Boolean).join(` `);return(0,K.jsxs)(`div`,{ref:re,className:`code-acp-composer-stack`,"data-testid":`code-acp-composer-stack`,children:[(u.length>0||l)&&e?(0,K.jsxs)(`div`,{className:`code-pending-followup code-acp-pending-items`,"data-testid":`code-acp-pending-followup`,children:[u.map(e=>(0,K.jsxs)(`div`,{className:`code-pending-followup-row code-acp-submission ${e.status}`,"data-testid":`code-acp-submission`,"data-status":e.status,children:[(0,K.jsx)(`span`,{className:`code-pending-followup-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Ve,{})}),(0,K.jsx)(`p`,{children:e.text||e.attachments?.map(e=>e.name).join(`, `)}),(0,K.jsxs)(`div`,{className:`code-pending-followup-actions`,children:[(0,K.jsx)(`span`,{className:`code-acp-submission-status`,children:e.status===`submitting`?L.messageAwaitingAcceptance:L.messageNotAccepted}),e.status===`failed`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-acp-submission-retry`,onClick:()=>O(e.id),children:L.retry}),(0,K.jsx)(`button`,{type:`button`,className:`icon`,"data-testid":`code-acp-submission-discard`,"aria-label":L.discardQueuedMessage,onClick:()=>k(e.id),children:(0,K.jsx)(pt,{})})]}):null]})]},e.id)),l?.messages.map(e=>(0,K.jsxs)(`div`,{className:`code-pending-followup-row queued`,"data-testid":`code-acp-pending-followup-row`,children:[(0,K.jsx)(`span`,{className:`code-pending-followup-icon`,"data-testid":`code-acp-pending-followup-queue-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Gj,{})}),(0,K.jsx)(`p`,{children:e.text||e.attachments?.map(e=>e.name).join(`, `)}),(0,K.jsxs)(`div`,{className:`code-pending-followup-actions`,children:[d?(0,K.jsxs)(`button`,{type:`button`,"data-testid":`code-acp-pending-followup-steer`,onClick:()=>D(e.id),children:[(0,K.jsx)(Ve,{className:`code-pending-followup-steer-icon`}),(0,K.jsx)(`span`,{children:L.steerQueuedMessage})]}):null,(0,K.jsx)(`button`,{type:`button`,className:`icon`,"data-testid":`code-acp-pending-followup-discard`,"aria-label":L.discardQueuedMessage,onClick:()=>T(e.id),children:(0,K.jsx)(Kj,{})}),(0,K.jsx)(`button`,{type:`button`,className:`icon`,"data-testid":`code-acp-pending-followup-edit`,"aria-label":L.editQueuedMessage,onClick:()=>E(e.id),children:(0,K.jsx)(ke,{})})]})]},e.id))]}):null,ge?(0,K.jsx)(`section`,{className:`code-acp-request code-acp-notice warning`,"data-testid":`code-acp-config-deferred`,role:`status`,children:(0,K.jsx)(`p`,{children:_e&&H?L.sessionSettingsDeferred:_e?L.permissionDeferred:L.configurationDeferred})}):null,ze?(0,K.jsx)(`section`,{className:`code-acp-request`,"data-testid":`code-acp-config-deferred-error`,role:`alert`,children:(0,K.jsx)(`p`,{children:i})}):null,(0,K.jsxs)(`footer`,{className:He,"data-testid":`code-acp-composer`,onClick:Me,children:[e?h.map(e=>(0,K.jsx)(vj,{request:e,onRespond:ee,copy:L},e.requestId)):null,e?g.map(e=>(0,K.jsx)(xj,{request:e,onRespond:I},e.requestId)):null,e?_.map(e=>(0,K.jsx)(xj,{request:e,onRespond:I},`active-${e.elicitationId||e.requestId}`)):null,e&&Re?(0,K.jsx)(wj,{agentId:t,methods:de?.authMethods||[],authTerminal:de?.authTerminal||null,agentName:de?.agentInfo?.title||de?.agentInfo?.name||``,authenticatingId:me,onAuthenticate:e=>{xe(e)}}):null,e&&fe?(0,K.jsxs)(`section`,{className:`code-acp-request code-acp-notice`,"data-testid":`code-acp-error`,role:`alert`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:`ACP`}),(0,K.jsx)(`span`,{children:n||`error`})]}),(0,K.jsx)(`p`,{children:fe})]}):null,Ee?(0,K.jsxs)(`div`,{className:`code-slash-menu code-composer-menu`,"data-testid":`code-acp-command-menu`,role:`listbox`,"aria-label":`ACP commands`,children:[(0,K.jsx)(`div`,{className:`code-slash-menu-header`,children:we?.trigger===`$`?`Skills`:`Agent commands`}),Te.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`code-slash-command ${t===oe?`active`:``}`,"data-testid":`code-acp-command-${e.name}`,role:`option`,"aria-selected":t===oe,onMouseDown:e=>e.preventDefault(),onMouseMove:()=>V(t),onClick:()=>Oe(e.name),children:[(0,K.jsx)(`span`,{className:`code-slash-command-icon`,"aria-hidden":`true`,children:`/`}),(0,K.jsxs)(`span`,{className:`code-slash-command-copy`,children:[(0,K.jsx)(`span`,{className:`code-slash-command-title`,children:(0,K.jsxs)(`code`,{children:[`/`,e.name]})}),(0,K.jsxs)(`small`,{children:[e.description,e.input?.hint?` · ${e.input.hint}`:``]})]})]},e.name))]}):null,(0,K.jsx)(`textarea`,{"data-testid":`code-acp-composer-input`,ref:p,rows:1,name:`farming-acp-chat-message`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,value:a,placeholder:e?s===`goal`?L.describeAgentGoal:s===`plan`?L.describePlanFirst:L.askFollowUpChanges:L.openAgentTerminalFirst,disabled:!e,onFocus:e=>{ie(!0),B(e.currentTarget.selectionStart),ce(null),ue(null)},onBlur:()=>ie(!1),onClick:e=>B(e.currentTarget.selectionStart),onKeyUp:e=>B(e.currentTarget.selectionStart),onSelect:e=>B(e.currentTarget.selectionStart),onChange:e=>{ne.current=e.currentTarget.value,B(e.currentTarget.selectionStart),b(e.currentTarget.value)},onPaste:j,onCompositionStart:()=>{te.current=!0},onCompositionEnd:e=>{te.current=!1,R.current=Date.now(),ne.current=e.currentTarget.value,b(e.currentTarget.value)},onKeyDown:Ae,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`}),(0,K.jsx)(VA,{attachments:o,onRemove:S}),(0,K.jsx)(`input`,{ref:m,className:`code-composer-file-input`,"data-testid":`code-acp-composer-file-input`,type:`file`,multiple:!0,onChange:M}),(0,K.jsxs)(`div`,{className:`code-composer-toolbar`,"data-testid":`code-acp-composer-toolbar`,children:[(0,K.jsxs)(`div`,{className:`code-composer-left-tools`,"data-testid":`code-acp-composer-left-tools`,children:[(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-composer-add`,"data-testid":`code-acp-composer-add`,"aria-label":L.addContext,"aria-haspopup":`menu`,"aria-expanded":se===`commands`,disabled:!e,onClick:()=>je(`commands`),children:(0,K.jsx)(Le,{})}),se===`commands`?(0,K.jsxs)(`div`,{className:`code-plus-menu code-composer-menu`,role:`menu`,"data-testid":`code-acp-plus-menu`,children:[(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-acp-composer-attach-file`,onClick:()=>{ce(null),N()},children:[(0,K.jsx)(`span`,{children:L.attachFile}),(0,K.jsx)(`small`,{children:L.fileContext})]}),de?.capabilities?.auth?.logout==null?null:(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-acp-logout`,disabled:he,onClick:()=>{ce(null),Se()},children:[(0,K.jsx)(`span`,{children:he?L.acpSigningOut:L.acpSignOut}),(0,K.jsx)(`small`,{children:L.acpSignOutDescription})]}),(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-acp-composer-goal-mode`,onClick:()=>{ce(null),P(`goal`)},children:[(0,K.jsx)(`span`,{children:L.goalMode}),(0,K.jsx)(`small`,{children:L.setObjective})]}),(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-acp-composer-plan-mode`,onClick:()=>{ce(null),P(`plan`)},children:[(0,K.jsx)(`span`,{children:L.planMode}),(0,K.jsx)(`small`,{children:L.planFirst})]})]}):null]}),s===`default`?null:(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-mode-chip`,"data-testid":`code-acp-composer-mode-chip`,"aria-label":L.clearComposerMode,onClick:F,children:[(0,K.jsx)(`span`,{children:s===`goal`?L.goalMode:L.planMode}),(0,K.jsx)(`span`,{"aria-hidden":`true`,children:(0,K.jsx)(pt,{})})]}),de?(0,K.jsx)(Ij,{session:de,updatingId:pe,copy:L,open:se===`mode`,onToggle:()=>je(`mode`),onSetMode:e=>{ce(null),ve(e)},onSetConfigOption:(e,t)=>{ce(null),ye(e,t)}}):null]}),(0,K.jsxs)(`div`,{className:`code-composer-right-tools`,"data-testid":`code-acp-composer-right-tools`,children:[Pe?(0,K.jsxs)(`div`,{className:`code-composer-context-window`,"data-testid":`code-acp-context-window`,"data-level":Fe,tabIndex:0,role:`img`,"aria-label":Ie,children:[(0,K.jsx)(`span`,{className:`code-context-window-ring`,"aria-hidden":`true`,style:{"--context-percent":Pe.percentUsed}}),(0,K.jsxs)(`div`,{className:`code-context-window-popover`,role:`tooltip`,children:[(0,K.jsx)(`span`,{children:`Context window:`}),(0,K.jsxs)(`strong`,{children:[Pe.percentUsed,`% used (`,Pe.percentLeft,`% left)`]}),(0,K.jsxs)(`strong`,{children:[aj(Pe.usedTokens),` / `,aj(Pe.limitTokens),` tokens used`]}),Fe===`critical`?(0,K.jsx)(`strong`,{className:`warning`,children:`Context window is full`}):null,Fe===`warning`?(0,K.jsx)(`strong`,{className:`warning`,children:`Context window is nearly full`}):null,Ne?.costLabel?(0,K.jsx)(`strong`,{children:Ne.costLabel}):null]})]}):null,de?(0,K.jsx)(Lj,{session:de,updatingId:pe,copy:L,open:se===`model`,pane:le,onToggle:()=>je(`model`),onSetPane:ue,onSetConfigOption:(e,t)=>{ce(null),ue(null),ye(e,t)},onSetProfile:(e,t,n,r)=>{be([{configId:e,value:t},{configId:n,value:r}])},onSetFast:(e,t)=>{ye(e,t)}}):null,v?(0,K.jsx)(`button`,{type:`button`,className:`code-composer-mic ${y?`listening`:``}`,"data-testid":`code-acp-composer-mic`,"aria-label":y?L.stopDictation:L.startDictation,"aria-pressed":y,onClick:A,disabled:!e,title:y?L.stopDictation:L.startDictation,children:(0,K.jsx)(ij,{listening:y})}):null,(0,K.jsx)(`button`,{type:`button`,className:`code-composer-send ${U?`interrupt`:``}`,"data-testid":`code-acp-composer-send`,"data-action":f,"aria-label":U?L.interruptAgent:L.sendMessage,onClick:U?w:()=>C(ne.current),disabled:Ce,children:U?(0,K.jsx)(`span`,{className:`code-composer-stop-icon`,"aria-hidden":`true`}):(0,K.jsx)(Ye,{})})]})]})]})]})}var Jj=`farming.codex.sessionDisplayState.v1`,Yj=50,Xj=`tmp_uuid`;function Zj(){return{promotedKeys:[],pinnedOverrides:{},archivedOverrides:{}}}function Qj(){if(typeof window>`u`)return Zj();try{let e=JSON.parse(window.localStorage.getItem(`farming.codex.sessionDisplayState.v1`)||`{}`),t=Array.isArray(e.promotedKeys)?e.promotedKeys.filter(e=>typeof e==`string`&&e.length>0):[],n={};e.pinnedOverrides&&typeof e.pinnedOverrides==`object`&&Object.entries(e.pinnedOverrides).forEach(([e,t])=>{typeof t==`boolean`&&(n[e]=t)});let r={};return e.archivedOverrides&&typeof e.archivedOverrides==`object`&&Object.entries(e.archivedOverrides).forEach(([e,t])=>{typeof t==`boolean`&&(r[e]=t)}),{promotedKeys:t,pinnedOverrides:n,archivedOverrides:r}}catch{return Zj()}}function $j(e){typeof window>`u`||window.localStorage.setItem(Jj,JSON.stringify(e))}function eM(e=[]){let t=[],n=new Set;return e.forEach(e=>{let r=typeof e==`string`?e.trim():``;if(!/^agent-session:[a-z][a-z0-9_-]*:.+$/i.test(r))return;let i=r.replace(/^agent-session:[^:]+:/i,``);i.startsWith(`-`)||i.startsWith(Xj)||n.has(r)||(n.add(r),t.push(r))}),t.slice(0,Yj)}function tM(e,t,n){return e.map(e=>{let r=OA(e),i=r in t,a=r in n;if(!i&&!a)return e;let o=a?n[r]:e.archived;return{...e,pinned:o?!1:i?t[r]:e.pinned,archived:o}})}function nM(e,t,n=``){return n&&n!==`default`?`${e}-history:home:${n}:${t}`:`${e}-history:${t}`}function rM(e){let t=/^([a-z]+)-history(?:-fork)?:(?:(?:home:([A-Za-z0-9._-]+):)?(.+))$/.exec(e||``);if(!t)return null;let n=t[1],r=t[2]||`default`,i=t[3];return n&&i?{provider:n,providerHomeId:r,sessionId:i}:null}function iM(e){let t=rM(e);return t?OA({provider:t.provider,id:t.sessionId,providerHomeId:t.providerHomeId}):``}function aM(e,t,n){return e.map(e=>{if(n||t.has(e.id)||e.agentSessions.length<=5)return{...e,hiddenAgentSessionCount:0,agentSessionsExpanded:t.has(e.id)};let r=e.agentSessions.filter(e=>e.pinned||e.unread),i=new Set(r.map(OA)),a=e.agentSessions.filter(e=>!i.has(OA(e))),o=Math.max(0,5-r.length),s=a.slice(0,o),c=a.length-s.length;return{...e,agentSessions:[...r,...s],hiddenAgentSessionCount:c,agentSessionsExpanded:!1}})}var oM=150,sM=12;function cM(e){let t=String(e||``).trim().toLowerCase();if(t===`claude-code`)return`claude`;if([`codex`,`claude`,`opencode`,`qoder`,`qwen`,`bash`,`zsh`].includes(t))return t}function lM(e){return cM(String(e||``).trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e))?.split(`/`).pop())}function uM(e){return cM(rM(e.source)?.provider)||lM(e.command)}function dM(e){return cM(e.providerSessionProvider)||cM(e.engineName)||lM(e.command)}function fM({iconName:e,resumeId:t,children:n}){return(0,K.jsxs)(`span`,{className:`code-history-meta`,children:[(0,K.jsx)(`span`,{className:`code-history-agent-icon`,"aria-hidden":`true`,children:e?(0,K.jsx)(x,{name:e,variant:`color`}):(0,K.jsx)(ot,{})}),(0,K.jsxs)(`span`,{children:[t&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`span`,{className:`code-history-resume-id`,"data-testid":`code-history-resume-id`,title:`Resume ID: ${t}`,children:[`Resume `,xM(t)]}),` · `]}),n]})]})}function pM(e){let t=String(e||``).trim().toLowerCase();return t===`codex`||t===`claude`||t===`opencode`||t===`qoder`||t===`qwen`?t:``}function mM(e){let t=rM(e);if(!t)return null;let n=pM(t.provider),r=String(t.sessionId||``).trim();return n&&r?{...t,provider:n,sessionId:r}:null}function hM(e){return e.title||e.task||e.command||`History agent`}function gM(e){return e.projectWorkspace||e.cwd||``}function _M(...e){return e.map(e=>String(e||``).trim()).filter(Boolean).join(` · `)}function vM(e){return _M(er(gM(e)))}function yM(e){return _M(e.providerSessionProvider||e.engineName,er(bA(e)))}function bM(e){return _M(e.providerName||e.provider,e.model,e.effort?CA(e.effort):``,kA(e))}function xM(e){let t=String(e||``).trim();return t.length<=20?t:`${t.slice(0,8)}…${t.slice(-6)}`}function SM(e){return Math.max(e.archivedAt||0,e.lastActivity||0,e.startedAt||0)}function CM(e){return Math.max(e.archivedAt||0,e.lastActivity||0,e.startedAt||0)}function wM(e){if(e.kind===`session`){let t=pM(e.session.provider),n=String(e.session.id||``).trim();return t&&n?{provider:t,sessionId:n,providerHomeId:e.session.providerHomeId||`default`}:null}if(e.kind===`agent`){let t=pM(e.agent.providerSessionProvider),n=String(e.agent.providerSessionId||``).trim();return t&&n&&e.agent.providerSessionTemporary!==!0?{provider:t,sessionId:n,providerHomeId:e.agent.providerHomeId||`default`}:mM(e.agent.source)}return mM(e.entry.source)}function TM(e){let t=wM(e);return t?`resume:${t.provider}:${t.providerHomeId||`default`}:${t.sessionId}`:``}function EM(e){return e.kind===`session`?30:e.kind===`agent`?20:10}function DM(e,t){return t.updatedAt===e.updatedAt?EM(t)>EM(e):t.updatedAt>e.updatedAt}function OM(e){let t=[],n=new Map;return e.forEach(e=>{let r=TM(e);if(!r){t.push(e);return}let i=n.get(r);(!i||DM(i,e))&&n.set(r,e)}),[...t,...n.values()].sort((e,t)=>t.updatedAt-e.updatedAt)}function kM(e,t,n){return OM([...e.map(e=>({kind:`run`,historyKey:`run:${e.id}`,updatedAt:SM(e),entry:e})),...t.map(e=>({kind:`agent`,historyKey:`agent:${e.id}`,updatedAt:CM(e),agent:e})),...n.map(e=>({kind:`session`,historyKey:OA(e),updatedAt:PA(e),session:e}))])}function AM(e,t){let n=new Map(e.map(e=>[OA(e),e]));return t.forEach(e=>n.set(OA(e),e)),Array.from(n.values())}function jM(e){return String(e||``).normalize(`NFKC`).toLocaleLowerCase()}function MM(e,t){let n=jM(t).trim();return n?e.filter(e=>{let t=wM(e)?.sessionId;return e.kind===`run`?jM([hM(e.entry),vM(e.entry),e.entry.command,e.entry.task,t].join(`
203
+ `)).includes(n):e.kind===`agent`?jM([A(e.agent),yM(e.agent),e.agent.command,t].join(`
204
+ `)).includes(n):jM([e.session.title,bM(e.session),e.session.provider,t].join(`
205
+ `)).includes(n)}):e}function NM(e,t,n=sM){let r=Math.max(1,Math.floor(n)),i=Math.max(1,Math.ceil(e.length/r)),a=Math.max(0,Math.min(i-1,Math.floor(t))),o=a*r;return{items:e.slice(o,o+r),page:a,pageSize:r,totalItems:e.length,totalPages:i}}function PM({archivedRuns:e,archivedAgents:t,agentSessions:n,loading:r,error:i,providerSessionTotal:a,now:o,onResumeSession:s,onContinueRun:c,onOpenArchivedAgent:l,onRestoreArchivedAgent:u,searchAgentSessions:d,canLoadMoreAgentSessions:f,onLoadMoreAgentSessions:p,onBack:m,copy:h}){let[g,_]=(0,G.useState)(``),[v,y]=(0,G.useState)(0),[b,x]=(0,G.useState)(!1),S=g.trim(),C=!!S,[w,T]=(0,G.useState)({query:``,sessions:[],loading:!1}),E=w.query===S?w.sessions:[],D=kM(e,t,C?AM(n,E):n),O=MM(D,S),k=NM(O,v),j=D.length,M=C&&(w.query!==S||w.loading);(0,G.useEffect)(()=>{if(!S){T({query:``,sessions:[],loading:!1});return}let e=new AbortController;T({query:S,sessions:[],loading:!0});let t=window.setTimeout(()=>{d(S,e.signal).then(t=>{e.signal.aborted||T({query:S,sessions:t,loading:!1})}).catch(t=>{t instanceof DOMException&&t.name===`AbortError`||e.signal.aborted||T({query:S,sessions:[],loading:!1})})},oM);return()=>{window.clearTimeout(t),e.abort()}},[S,d]),(0,G.useEffect)(()=>{y(0)},[S]),(0,G.useEffect)(()=>{v!==k.page&&y(k.page)},[k.page,v]);let P=async()=>{let e=k.page+1;if(e<k.totalPages){y(e);return}if(!(!f||b)){x(!0);try{await p()&&y(e)}finally{x(!1)}}};return(0,K.jsxs)(`div`,{className:`code-history-panel`,"data-testid":`code-history-panel`,children:[(0,K.jsxs)(`div`,{className:`code-history-panel-header`,children:[(0,K.jsxs)(`div`,{className:`code-side-view-heading`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-side-view-back`,"data-testid":`code-history-back`,"aria-label":h.back,title:h.back,onClick:m,children:(0,K.jsx)(nt,{})}),(0,K.jsx)(`h2`,{children:h.history})]}),(0,K.jsxs)(`div`,{className:`code-search-panel-input code-history-search`,"data-testid":`code-history-search-box`,children:[(0,K.jsx)(`span`,{className:`code-search-panel-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Oe,{})}),(0,K.jsx)(`input`,{type:`text`,role:`searchbox`,inputMode:`search`,value:g,onChange:e=>_(e.currentTarget.value),placeholder:h.searchHistory,"aria-label":h.searchHistory,autoComplete:`off`,spellCheck:!1}),g&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>_(``),"aria-label":h.clearSearch,children:(0,K.jsx)(pt,{})})]})]}),r?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-history-loading`,children:(0,K.jsx)(`h2`,{children:h.loading})}):i?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-history-error`,role:`alert`,children:(0,K.jsx)(`h2`,{children:i})}):j===0?(0,K.jsxs)(`div`,{className:`code-empty-workspace`,children:[(0,K.jsx)(`h2`,{children:h.noHistoryYet}),(0,K.jsx)(`p`,{children:h.noHistoryDescription})]}):C&&M&&O.length===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-history-search-loading`,children:(0,K.jsx)(`h2`,{children:h.searching})}):C&&O.length===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-empty-history-search`,children:(0,K.jsx)(`h2`,{children:h.noMatchingAgents})}):(0,K.jsxs)(`div`,{className:`code-history-list`,children:[(0,K.jsx)(`section`,{className:`code-history-section`,"data-testid":`code-history-agents`,children:k.items.map(e=>{if(e.kind===`run`){let{entry:t}=e;return(0,K.jsxs)(`article`,{className:`code-history-card archived`,"data-testid":`code-archived-run-card`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-history-card-primary`,"data-testid":`code-archived-run-primary`,"aria-label":`${h.continueRun}: ${hM(t)}`,onClick:()=>c(t),children:(0,K.jsxs)(`span`,{className:`code-history-card-copy`,children:[(0,K.jsx)(`span`,{className:`code-history-card-title`,children:hM(t)}),(0,K.jsx)(fM,{iconName:uM(t),resumeId:wM(e)?.sessionId,children:vM(t)})]})}),(0,K.jsxs)(`div`,{className:`code-history-actions`,children:[(0,K.jsx)(`span`,{children:N(e.updatedAt,o)}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-archived-run-continue`,onClick:()=>c(t),"aria-label":h.continueRun,title:h.continueRun,children:(0,K.jsx)(ut,{})})]})]},e.historyKey)}if(e.kind===`agent`){let{agent:t}=e;return(0,K.jsxs)(`article`,{className:`code-history-card archived`,"data-testid":`code-archived-agent-card`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-history-card-primary`,"data-testid":`code-archived-agent-primary`,"aria-label":`${h.open}: ${A(t)}`,onClick:()=>l(t.id),children:(0,K.jsxs)(`span`,{className:`code-history-card-copy`,children:[(0,K.jsx)(`span`,{className:`code-history-card-title`,children:A(t)}),(0,K.jsx)(fM,{iconName:dM(t),resumeId:wM(e)?.sessionId,children:yM(t)})]})}),(0,K.jsxs)(`div`,{className:`code-history-actions`,children:[(0,K.jsx)(`span`,{children:N(e.updatedAt,o)}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-archived-agent-open`,onClick:()=>l(t.id),"aria-label":h.open,title:h.open,children:(0,K.jsx)(tt,{})}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-archived-agent-restore`,onClick:()=>u(t.id),"aria-label":h.restore,title:h.restore,children:(0,K.jsx)(ut,{})})]})]},e.historyKey)}let{session:t}=e,n=t.title||h.sessionFallbackTitle(t.providerName);return(0,K.jsxs)(`article`,{className:`code-history-card code-session`,"data-testid":`code-session-history-card`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-history-card-primary`,"data-testid":`code-session-history-primary`,"aria-label":h.resumeSessionAria(n),onClick:()=>s(t.provider,t.id,t.providerHomeId),children:(0,K.jsxs)(`span`,{className:`code-history-card-copy`,children:[(0,K.jsx)(`span`,{className:`code-history-card-title`,children:n}),(0,K.jsx)(fM,{iconName:cM(t.provider),resumeId:t.id,children:bM(t)})]})}),(0,K.jsxs)(`div`,{className:`code-history-actions`,children:[(0,K.jsx)(`span`,{children:N(e.updatedAt,o)}),(0,K.jsx)(`button`,{type:`button`,"aria-label":h.resumeSessionAria(n),title:h.restore,onClick:()=>s(t.provider,t.id,t.providerHomeId),children:(0,K.jsx)(ut,{})})]})]},e.historyKey)})}),(0,K.jsxs)(`nav`,{className:`code-history-pagination`,"data-testid":`code-history-pagination`,"aria-label":h.historyPagination,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>y(e=>Math.max(0,e-1)),disabled:k.page===0,"aria-label":h.previousPage,title:h.previousPage,children:(0,K.jsx)(dt,{})}),(0,K.jsxs)(`span`,{"data-testid":`code-history-page-status`,children:[h.historyPageStatus(k.page+1,k.totalPages,k.totalItems,f),a!==null&&` · ${h.historyProviderSessionTotal(a)}`]}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>void P(),disabled:b||k.page>=k.totalPages-1&&!f,"aria-label":h.nextPage,title:h.nextPage,children:(0,K.jsx)(mt,{})})]})]})]})}function FM(e){return e.kind===`agent`?e.claimedSessionKey||`agent:${e.agent.id}`:OA(e.session)}function IM(e){return!!e.parentAgentId&&e.source===`ui-fork-new-worktree`}function LM(e,t){return t||e===`pending`||e===`stopped`||e===`dead`}function RM(e){let t=e.replace(/\s+/g,` `).trim();return t.length>160?`${t.slice(0,157)}...`:t}function zM(e){return e?new Date(e).toLocaleString():void 0}function BM(e){return e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean).join(` · `)}function VM(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function HM(e){if(e===null||e<0)return``;let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m`;let r=Math.floor(n/60),i=n%60;return i>0?`${r}h ${i}m`:`${r}h`}function UM(e,t,n){let r=RM(e.terminalStatus?.runningCommand||e.shellCommand||``);if(r&&t){let t=VM(e.terminalStatus?.runningCommandStartedAt)??VM(e.shellCommandStartedAt),i=t===null?``:HM(n-t);return i?`Running ${i}: ${r}`:`Running: ${r}`}let i=RM(e.terminalStatus?.lastCommand||e.shellLastCommand||``);if(!i)return``;let a=e.terminalStatus?.lastExitCode,o=[HM(VM(e.terminalStatus?.lastCommandDurationMs)??VM(e.shellLastCommandDurationMs)),typeof a==`number`?`exit ${a}`:``].filter(Boolean).join(`, `);return o?`Last command: ${i} (${o})`:`Last command: ${i}`}function WM(e,t){let n=e.lastActivity??e.startedAt,r=$k(e).turnActive,i=m(e),a=UM(e,r,t),o=BM([b(e.providerSessionProvider||e.command),e.codexTerminalProfile?.model,e.codexTerminalProfile?.reasoningEffort]),s=a||(o.toLowerCase()===i.toLowerCase()?``:o),c=N(n,t);return{kind:`agent`,title:i,rowTitle:[i,a,e.cwd].filter(Boolean).join(` · `),commandTitle:a,detailLabel:s,lifecycleStatus:e.status,turnActive:r,statusIndicatorVisible:LM(e.status,r),pinned:e.pinned===!0,unread:e.unread===!0,forkedToNewWorktree:IM(e),requiresResume:!1,scheduled:!1,scheduleTitle:``,ageLabel:c,ageVisible:!r&&!!c,ageTitle:zM(n)}}function GM(e,t,n){let r=PA(e),i=e.schedule?.label||e.schedule?.name||e.schedule?.rrule||``,a=BM([e.providerName||b(e.provider),e.model,e.effort]),o=N(r,n);return{kind:`history`,title:e.title||t,rowTitle:[e.title||t,e.cwd||e.workspace].filter(Boolean).join(` · `),commandTitle:``,detailLabel:a,turnActive:!1,statusIndicatorVisible:!1,pinned:e.pinned===!0,unread:e.unread===!0,forkedToNewWorktree:!1,requiresResume:!0,scheduled:!!e.schedule,scheduleTitle:i,ageLabel:o,ageVisible:!!o,ageTitle:zM(r)}}function KM(e,t=Date.now()){return e.kind===`agent`?WM(e.agent,t):GM(e.session,e.fallbackTitle,t)}function qM({query:e,displayedProjects:t,hasQuery:n,loading:r,resultCount:i,selectedAgentId:a,selectedSessionHandle:o,inputRef:s,onQueryChange:c,onKeyDown:l,onClearSearch:u,onBack:d,onOpenAgent:f,onOpenSession:p,copy:m}){return(0,G.useEffect)(()=>{let e=s.current;e&&window.requestAnimationFrame(()=>{e.focus({preventScroll:!0})})},[s]),(0,K.jsxs)(`div`,{className:`code-search-panel`,"data-testid":`code-search-panel`,children:[(0,K.jsxs)(`div`,{className:`code-search-panel-header`,children:[(0,K.jsxs)(`div`,{className:`code-side-view-heading`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-side-view-back`,"data-testid":`code-search-back`,"aria-label":m.back,title:m.back,onClick:d,children:(0,K.jsx)(nt,{})}),(0,K.jsx)(`h2`,{children:m.search})]}),n?(0,K.jsx)(`span`,{children:m.resultsCount(i)}):null]}),(0,K.jsxs)(`div`,{className:`code-search-panel-input`,"data-testid":`code-search-box`,children:[(0,K.jsx)(`span`,{className:`code-search-panel-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Oe,{})}),(0,K.jsx)(`input`,{ref:s,type:`text`,role:`searchbox`,name:`farming-workspace-search`,inputMode:`search`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`search`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:e,onChange:e=>c(e.currentTarget.value),onKeyDown:l,placeholder:m.searchProjectsOrAgents,"aria-label":m.searchProjectsOrAgents}),e&&(0,K.jsx)(`button`,{type:`button`,onClick:u,"aria-label":m.clearSearch,children:(0,K.jsx)(pt,{})})]}),n&&r&&i===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-search-loading`,children:(0,K.jsx)(`h2`,{children:m.searching})}):n&&i===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-empty-search`,children:(0,K.jsx)(`h2`,{children:m.noMatchingAgents})}):n?(0,K.jsx)(`div`,{className:`code-search-results`,children:t.map(e=>(0,K.jsxs)(`section`,{className:`code-search-result-group`,children:[(0,K.jsx)(`h3`,{children:e.name}),e.agents.map(e=>(0,K.jsx)(JM,{agent:e,selected:e.id===a,onOpen:()=>f(e.id)},e.id)),e.agentSessions.map(e=>{let t=OA(e),n=[e.providerName||e.provider,e.model,e.effort?CA(e.effort):``].filter(Boolean).join(` · `)||kA(e);return(0,K.jsx)(`button`,{type:`button`,className:`code-search-result code-session-result ${t===o?`active`:``}`,"data-testid":`code-session-search-result`,onClick:()=>p(e),children:(0,K.jsxs)(`span`,{className:`code-search-result-copy`,children:[(0,K.jsx)(`strong`,{children:e.title||m.sessionFallbackTitle(e.providerName)}),(0,K.jsx)(`span`,{children:n})]})},t)})]},e.id))}):null]})}function JM({agent:e,selected:t,onOpen:n}){let r=KM({kind:`agent`,agent:e}),i=b(e.providerSessionProvider||e.command);return(0,K.jsxs)(`button`,{type:`button`,className:`code-search-result ${r.statusIndicatorVisible?``:`no-status`} ${t?`active`:``}`,"data-testid":`code-search-result`,title:r.rowTitle||r.title,onClick:n,children:[r.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-agent-dot ${r.lifecycleStatus} ${r.turnActive?`turn-active`:``}`}),(0,K.jsxs)(`span`,{className:`code-search-result-copy`,children:[(0,K.jsx)(`strong`,{children:r.title}),(0,K.jsx)(`span`,{children:i||SA(bA(e))})]})]})}var YM=[`skill`,`mcp`,`hook`,`plugin`,`command`],XM=[`farming`,`homes`,`extensions`],ZM=15e3,QM=`https://docs.docker.com/desktop/setup/install/mac-install/`,$M=`https://docs.docker.com/engine/install/`;async function eN(e,t){let n=new AbortController,r=window.setTimeout(()=>n.abort(),ZM);try{return await fetch(e,{...t,signal:n.signal})}finally{window.clearTimeout(r)}}function tN(e){let t=e===`zh`;return{title:t?`插件`:`Plugins`,description:t?`管理 Farming 和 Agent 可以使用的能力。`:`Manage capabilities available to Farming and Agents.`,back:t?`返回工作区`:`Back to workspace`,tabs:{farming:`Farming`,homes:`Agent Homes`,extensions:t?`扩展`:`Extensions`},farmingBuiltIn:t?`Farming 内置`:`Built into Farming`,farmingBuiltInDescription:t?`由 Farming 提供并统一管理的能力。`:`Capabilities provided and managed by Farming.`,agentHomes:`Agent Homes`,agentHomesDescription:t?`配置来自各自 Home;Farming 只显示可安全识别的摘要。`:`Configuration comes from each Home; Farming only shows safe recognized summaries.`,agentExtensions:t?`Agent 扩展`:`Agent extensions`,agentExtensionsDescription:t?`按 Home 查看发现的 Skill、MCP、Hook、插件和命令。`:`Skills, MCPs, hooks, plugins, and commands discovered in each Agent Home.`,searchExtensions:t?`搜索扩展`:`Search extensions`,refresh:t?`刷新`:`Refresh`,noMatchingExtensions:t?`没有匹配的扩展。`:`No matching extensions.`,addAgent:t?`添加 Agent`:`Add Agent`,edit:t?`编辑配置`:`Edit configuration`,remove:t?`删除`:`Remove`,save:t?`保存`:`Save`,cancel:t?`取消`:`Cancel`,moveUp:t?`上移`:`Move up`,moveDown:t?`下移`:`Move down`,dragToReorder:t?`拖动调整 Agent 顺序`:`Drag to reorder Agents`,unavailableAgent:t?`未安装`:`Not installed`,model:t?`模型`:`Model`,provider:t?`提供方`:`Provider`,reasoning:t?`推理强度`:`Reasoning`,serviceTier:t?`服务等级`:`Service tier`,approval:t?`审批`:`Approval`,sandbox:t?`沙箱`:`Sandbox`,permission:t?`权限`:`Permission`,homeConfiguration:t?`Home 配置`:`Home configuration`,inheritConfiguration:e=>t?`继承 ${e}`:`Inherited from ${e}`,missingConfiguration:e=>t?`未找到 ${e};编辑后首次保存会创建它。`:`${e} was not found; the first save after editing will create it.`,agentProvider:t?`Agent 类型`:`Agent provider`,homeName:t?`Home 名称`:`Home name`,homePath:t?`Home 路径`:`Home path`,homeNamePlaceholder:t?`例如 work`:`e.g. work`,homePathPlaceholder:`~/.codex-work`,invalidHome:t?`请输入有效且不重复的 Home 名称和路径。`:`Enter a valid, unique Home name and path.`,saveAgentFailed:t?`Agent 设置保存失败`:`Failed to save Agent settings`,confirmRemoveAgent:e=>t?`删除 ${e}?`:`Remove ${e}?`,loadingAgentExtensions:t?`正在读取 Agent 扩展…`:`Loading Agent extensions…`,agentExtensionsFailed:t?`Agent 扩展读取失败`:`Failed to load Agent extensions`,noAgentExtensions:t?`没有发现扩展。`:`No extensions found.`,unsupportedDiscovery:t?`这个 Agent 还没有统一的扩展发现接口。`:`This Agent does not expose a unified extension discovery interface yet.`,home:`Home`,count:e=>t?`${e} 项`:`${e} items`,kind:{skill:`Skill`,mcp:`MCP`,hook:`Hook`,plugin:t?`插件`:`Plugin`,command:t?`命令`:`Command`},kindTabs:{skill:`Skills`,mcp:`MCPs`,hook:`Hooks`,plugin:t?`插件`:`Plugins`,command:t?`命令`:`Commands`},extensionDetails:t?`扩展详情`:`Extension details`,closeDetails:t?`关闭详情`:`Close details`,source:t?`来源`:`Source`,openSource:t?`打开来源文件`:`Open source file`,extensionStatus:{configured:t?`已配置`:`Configured`,enabled:t?`已启用`:`Enabled`,disabled:t?`已停用`:`Disabled`},browser:t?`浏览器`:`Browser`,browserDescription:t?`让 Agent 操作网页,并在 Farming 中查看同一个浏览器。`:`Let Agents operate webpages and view the same browser in Farming.`,enabled:t?`已启用`:`Enabled`,disabled:t?`已停用`:`Disabled`,unavailable:t?`未就绪`:`Not ready`,checking:t?`正在检查…`:`Checking…`,checkFailed:t?`检查失败`:`Check failed`,browserCheckFailed:t?`浏览器当前状态检查失败。`:`Failed to check the current Browser status.`,computerCheckFailed:t?`Computer Use 当前状态检查失败。`:`Failed to check the current Computer Use status.`,noSystemBrowser:t?`未发现系统 Chromium`:`No system Chromium detected`,isolatedBrowser:t?`隔离浏览器`:`Isolated Browser`,isolatedBrowserRequiresDocker:t?`隔离浏览器(需要 Docker)`:`Isolated Browser (requires Docker)`,isolatedBrowserNotInstalled:t?`隔离浏览器(未安装)`:`Isolated Browser (not installed)`,isolatedBrowserUnavailable:t?`隔离浏览器(暂不可用)`:`Isolated Browser (unavailable)`,browserChoice:t?`浏览器来源`:`Browser source`,applyBrowser:t?`应用`:`Apply`,prepareIsolatedBrowser:t?`准备隔离浏览器`:`Prepare isolated Browser`,preparingIsolatedBrowser:t?`正在下载并验证…`:`Downloading and verifying…`,isolatedBrowserHint:t?`显式下载固定版本的 Computer/CUA 镜像和独立 Chromium 缓存(合计约 2 GB);之后由 Farming 自动管理容器和 CDP,不需要配置端口。`:`Explicitly downloads the pinned Computer/CUA image and a separate Chromium cache (about 2 GB total); Farming then manages the container and CDP without port configuration.`,isolatedBrowserPrepareFailed:t?`隔离浏览器准备失败`:`Failed to prepare isolated Browser`,isolatedBrowserDockerRequired:t?`安装并启动 Docker 后,才能准备隔离浏览器。`:`Install and start Docker before preparing the isolated Browser.`,dockerMacGuidance:t?`普通网页操作直接使用本机浏览器即可。需要隔离浏览器、并行桌面或 CUA 时,建议安装并启动 Docker Desktop;完成后重新打开插件页。`:`Use a local browser for ordinary webpage work. Install and start Docker Desktop only when you need an isolated Browser, parallel desktops, or CUA; then reopen Plugins.`,dockerHostGuidance:t?`普通网页操作直接使用本机浏览器即可。需要隔离浏览器、并行桌面或 CUA 时,请安装并启动 Docker;完成后重新打开插件页。`:`Use a local browser for ordinary webpage work. Install and start Docker only when you need an isolated Browser, parallel desktops, or CUA; then reopen Plugins.`,installDockerDesktop:t?`安装 Docker Desktop`:`Install Docker Desktop`,viewDockerInstallGuide:t?`查看 Docker 安装说明`:`View Docker installation guide`,isolatedCompatibilityRequired:t?`这台旧版 Docker 需要显式启用兼容模式后再重试。`:`This older Docker Engine requires compatibility mode before retrying.`,browserChangeHint:t?`切换后,正在运行的浏览器会停止。`:`Changing this stops running Browsers.`,unavailableHint:t?`可以选择本机 Chromium,或准备由 Farming 管理的隔离浏览器。`:`Choose a local Chromium browser or prepare the Farming-managed isolated Browser.`,enable:t?`启用`:`Enable`,disable:t?`停用`:`Disable`,saveFailed:t?`浏览器插件设置保存失败`:`Failed to save Browser plugin settings`,computer:`Computer Use`,computerDescription:t?`让 Agent 查看并操作桌面,你可以在 Farming 中观察或接管。`:`Let Agents see and operate desktops that you can observe or take over in Farming.`,dockerUnavailable:t?`未检测到 Docker`:`Docker not available`,computerRuntimeReady:t?`隔离桌面已安装`:`Isolated Desktop installed`,computerRuntimeMissing:t?`隔离桌面未安装`:`Isolated Desktop not installed`,desktopTargets:t?`桌面`:`Desktops`,isolatedDesktop:t?`隔离桌面`:`Isolated Desktop`,isolatedDesktopDescription:t?`独立的 Linux 桌面,适合并行任务。需要 Docker。`:`An independent Linux desktop for parallel work. Requires Docker.`,prepareComputer:t?`安装隔离桌面`:`Install isolated desktop`,preparingComputer:t?`正在下载并验证…`:`Downloading and verifying…`,computerRuntimeHint:t?`显式下载固定版本的官方 CUA XFCE 镜像(下载约 472 MB,本地约 1.3 GB)。`:`Explicitly downloads the pinned official CUA XFCE image (about 472 MB download and 1.3 GB on disk).`,compatibilityMode:t?`旧版 Docker 兼容模式`:`Legacy Docker compatibility mode`,compatibilityHint:t?`仅在旧 Docker 的 seccomp 阻止 CUA 启动时启用;该模式会对隔离容器关闭 seccomp。`:`Enable only when old Docker seccomp blocks CUA startup; this disables seccomp for the isolated container.`,computerSaveFailed:t?`Computer Use 插件设置保存失败`:`Failed to save Computer Use plugin settings`,computerPrepareFailed:t?`隔离桌面安装失败`:`Failed to install Isolated Desktop`}}function nN(e,t){return e?.browser?e.browser.kind===`isolated-computer`?t.isolatedBrowser:rN(e.browser.kind):``}function rN(e){return e===`chrome`?`Google Chrome`:e===`brave`?`Brave`:e===`edge`?`Microsoft Edge`:`Chromium`}function iN(e){return e.id===`codex`?`Codex`:e.id===`claude`?`Claude Code`:e.id===`opencode`?`OpenCode`:e.id===`qoder`?`Qoder`:e.id===`qwen`?`Qwen Code`:e.name||e.id}function aN(e,t){return e===`skill`||e===`mcp`||e===`hook`||e===`plugin`||e===`command`?t.kind[e]:e.split(/[-_.]+/).filter(Boolean).map(e=>e.slice(0,1).toUpperCase()+e.slice(1)).join(` `)||e}function oN(e){return e===`skill`?(0,K.jsx)(it,{}):e===`mcp`?(0,K.jsx)(rt,{}):e===`hook`?(0,K.jsx)(Ne,{}):e===`command`?(0,K.jsx)(ot,{}):(0,K.jsx)(ht,{})}function sN(e,t){return{approval:t.approval,model:t.model,permission:t.permission,provider:t.provider,reasoning:t.reasoning,sandbox:t.sandbox,serviceTier:t.serviceTier}[e]}function cN(e,t){return e===`skill`||e===`mcp`||e===`hook`||e===`plugin`||e===`command`?t.kindTabs[e]:aN(e,t)}function lN(e,t){return`${e}:${t}`}function uN(e){return e.flatMap(e=>e.homes.map(t=>({provider:e,home:t}))).sort((e,t)=>e.home.order-t.home.order||e.provider.id.localeCompare(t.provider.id)||e.home.id.localeCompare(t.home.id))}function dN(e){let t=0;return e.map(e=>({...e,available:e.available!==!1,homes:(e.homes||[]).map(e=>({...e,path:String(e.path||``),order:Number.isFinite(Number(e.order))?Number(e.order):t++,newAgentDefaults:{model:`inherit`,reasoning:`inherit`,fast:`inherit`},configuration:{exists:e.configuration?.exists===!0,filePath:String(e.configuration?.filePath||``),rootId:String(e.configuration?.rootId||``),summary:Array.isArray(e.configuration?.summary)?e.configuration.summary:[]},extensions:Array.isArray(e.extensions)?e.extensions.map(t=>{let n=t.status===`enabled`||t.status===`disabled`?t.status:`configured`;return{...t,id:String(t.id||``),name:String(t.name||``),description:String(t.description||``),kind:String(t.kind||`plugin`),scope:String(t.scope||``),status:n,sourceFile:String(t.sourceFile||``),rootId:String(t.rootId||e.configuration?.rootId||``)}}):[]}))}))}function fN(e){return Object.fromEntries(e.map(e=>[e.id,e.homes.map(e=>({id:e.id,path:e.path,order:e.order,newAgentDefaults:{model:`inherit`,reasoning:`inherit`,fast:`inherit`}}))]))}function pN(e){let t=e.trim().replace(/\/+$/,``).split(`/`).filter(Boolean);return(t[t.length-1]||`home`).replace(/^\.+/,``).replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/^[.-]+|[.-]+$/g,``).slice(0,64)||`home`}function mN({capability:e,loading:t,capabilityError:n,computerCapability:i,computerLoading:a,computerCapabilityError:o,onPrepareComputer:s,language:c,onBack:l,onOpenAgentHomeConfiguration:u,onRefreshCapability:d}){let f=(0,G.useMemo)(()=>tN(c),[c]),p=typeof navigator<`u`&&/Mac/.test(navigator.platform||navigator.userAgent),m=p?QM:$M,h=p?f.installDockerDesktop:f.viewDockerInstallGuide,[_,v]=(0,G.useState)(e?.enabled===!0),[y,b]=(0,G.useState)(i?.enabled===!0),[x,S]=(0,G.useState)(i?.compatibilityMode===!0),[C,w]=(0,G.useState)(!1),[T,E]=(0,G.useState)(!1),[D,O]=(0,G.useState)(``),[k,A]=(0,G.useState)(!1),[j,M]=(0,G.useState)(!1),[N,P]=(0,G.useState)(!1),[F,ee]=(0,G.useState)(``),[I,L]=(0,G.useState)(`system:`),te=(0,G.useRef)(!1),[R,ne]=(0,G.useState)([]),[re,z]=(0,G.useState)(!1),[ie,ae]=(0,G.useState)(``),[B,oe]=(0,G.useState)(!1),[V,se]=(0,G.useState)(null),[ce,le]=(0,G.useState)(``),[ue,de]=(0,G.useState)(null),[fe,pe]=(0,G.useState)(`farming`),[me,he]=(0,G.useState)(``),[ge,H]=(0,G.useState)(`skill`),[_e,ve]=(0,G.useState)(``),ye=(0,G.useRef)(0),be=(0,G.useRef)(null),xe=(0,G.useRef)(0),Se=(0,G.useRef)(!1),U=(0,G.useRef)({mounted:!0,generation:0});(0,G.useEffect)(()=>{if(!e||te.current)return;v(e.enabled);let t=e.selection;L(t?.source===`isolated`?`isolated`:`system:${t?.executablePath||``}`)},[e]),(0,G.useEffect)(()=>{i&&(b(i.enabled),S(i.compatibilityMode))},[i]);let Ce=(0,G.useCallback)(async(e={})=>{if(!U.current.mounted||be.current)return;let t=U.current.generation,n=ye.current+1;ye.current=n,z(!0),e.preserveError||ae(``);try{let e=await eN(r(`/api/agent-extensions`),{headers:{Accept:`application/json`}}),i=await e.json().catch(()=>({}));if(!e.ok)throw Error(i.error||f.agentExtensionsFailed);if(ye.current!==n||U.current.generation!==t||!U.current.mounted||be.current)return;Se.current=!1,ne(dN(Array.isArray(i.agents)?i.agents:[]))}catch(e){if(ye.current!==n||U.current.generation!==t||!U.current.mounted||be.current)return;if(!g().connected){Se.current=!0;return}ae(e instanceof Error?e.message:f.agentExtensionsFailed)}finally{ye.current===n&&U.current.generation===t&&U.current.mounted&&!be.current&&!Se.current&&z(!1)}},[f.agentExtensionsFailed]);(0,G.useEffect)(()=>{U.current.mounted=!0;let e=()=>{Se.current&&(Se.current=!1,Ce())};return window.addEventListener(`farming:backend-connected`,e),()=>{U.current={mounted:!1,generation:U.current.generation+1},ye.current+=1,Se.current=!1,window.removeEventListener(`farming:backend-connected`,e)}},[Ce]),(0,G.useEffect)(()=>{fe!==`farming`&&Ce()},[fe,Ce]);let we=(0,G.useCallback)(async e=>{if(!U.current.mounted||be.current)return!1;let t=U.current.generation,n=xe.current+1;xe.current=n,be.current=n,ye.current+=1,oe(!0),z(!1),ae(``);let i=!1;try{let i=await eN(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({agentHomes:fN(e)})}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a.error||f.saveAgentFailed);return be.current!==n||U.current.generation!==t||!U.current.mounted?!1:(ne(e),window.dispatchEvent(new CustomEvent(`farming-agent-homes-saved`)),be.current=null,await Ce(),!0)}catch(e){return i=!0,be.current===n&&U.current.generation===t&&U.current.mounted&&ae(e instanceof Error?e.message:f.saveAgentFailed),!1}finally{be.current===n&&(be.current=null),U.current.generation===t&&U.current.mounted&&(oe(!1),i&&Ce({preserveError:!0}))}},[f.saveAgentFailed,Ce]),Ee=(0,G.useCallback)(()=>{if(!V||B)return;let e=V.provider,t=R.find(t=>t.id===e),n=V.path.trim(),r=(V.id.trim()||pN(n)).slice(0,64);if(!t||!n||!/^[A-Za-z0-9._-]+$/.test(r)||t.homes.some(e=>e.id.toLowerCase()===r.toLowerCase())){ae(f.invalidHome);return}let i=uN(R).reduce((e,t)=>Math.max(e,t.home.order),-1)+1;we(R.map(t=>t.id===e?{...t,homes:[...t.homes,{id:r,path:n,order:i,newAgentDefaults:{model:`inherit`,reasoning:`inherit`,fast:`inherit`},configuration:{exists:!1,filePath:``,rootId:``,summary:[]},extensions:[]}]}:t)).then(e=>{e&&se(null)})},[V,R,B,f.invalidHome,we]),De=(0,G.useCallback)((e,t)=>{if(t===`default`||B)return;let n=`${iN({id:e,name:e})} · ${t}`;window.confirm(f.confirmRemoveAgent(n))&&we(R.map(n=>n.id===e?{...n,homes:n.homes.filter(e=>e.id!==t)}:n))},[R,B,f,we]),Oe=(0,G.useCallback)((e,t)=>{if(!e||e===t||B)return;let n=uN(R),r=n.findIndex(t=>lN(t.provider.id,t.home.id)===e),i=n.findIndex(e=>lN(e.provider.id,e.home.id)===t);if(r<0||i<0)return;let[a]=n.splice(r,1);if(!a)return;n.splice(i,0,a);let o=new Map(n.map((e,t)=>[lN(e.provider.id,e.home.id),t]));we(R.map(e=>({...e,homes:e.homes.map(t=>({...t,order:o.get(lN(e.id,t.id))??t.order}))})))},[R,B,we]),Ae=(0,G.useCallback)((e,t)=>{let n=uN(R),r=n.findIndex(t=>lN(t.provider.id,t.home.id)===e),i=n[r+t];r<0||!i||Oe(e,lN(i.provider.id,i.home.id))},[R,Oe]),je=async()=>{if(k||!e?.browser&&!_)return;let t=!_;A(!0),ee(``);try{let e=await fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({browserExtensionEnabled:t})}),n=await e.json().catch(()=>({}));if(!e.ok)throw Error(n.error||f.saveFailed);v(n.settings?.browserExtensionEnabled===!0),d()}catch(e){ee(e instanceof Error?e.message:f.saveFailed)}finally{A(!1)}},Me=async()=>{if(k||!Re)return;let e=I===`isolated`?`isolated`:`system`,t=e===`system`?I.slice(7):``;A(!0),ee(``);try{let n=await fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({browserSource:e,browserExecutablePath:t})}),i=await n.json().catch(()=>({}));if(!n.ok)throw Error(i.error||f.saveFailed);te.current=!1,d()}catch(e){ee(e instanceof Error?e.message:f.saveFailed)}finally{A(!1)}},Ne=async()=>{if(!j){M(!0),P(!1),ee(``);try{let e=await fetch(r(`/api/browsers/isolated/prepare`),{method:`POST`,headers:{Accept:`application/json`}}),t=await e.json().catch(()=>({}));if(!e.ok)throw P(t.compatibilityRequired===!0),Error(t.error||f.isolatedBrowserPrepareFailed);d()}catch(e){ee(e instanceof Error?e.message:f.isolatedBrowserPrepareFailed),d()}finally{M(!1)}}},Pe=async e=>{if(!C){w(!0),O(``);try{let t=await fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));if(!t.ok)throw Error(n.error||f.computerSaveFailed);b(n.settings?.computerExtensionEnabled===!0),S(n.settings?.computerCompatibilityMode===!0),d()}catch(e){O(e instanceof Error?e.message:f.computerSaveFailed)}finally{w(!1)}}},Fe=async()=>{if(!T){E(!0),O(``);try{await s(),d()}catch(e){O(e instanceof Error?e.message:f.computerPrepareFailed),d()}finally{E(!1)}}},Ie=!!e?.browser,Re=I!==(e?.selection?.source===`isolated`?`isolated`:`system:${e?.selection?.executablePath||``}`),ze=e?.isolated?.imageReady===!0,Be=I===`isolated`,Ve=e?.isolated?.dockerAvailable===!0,He=Be&&!ze&&Ve,Ue=e?.isolated?.dockerAvailable===!1?f.isolatedBrowserRequiresDocker:e?.isolated?.dockerAvailable===!0?ze?f.isolatedBrowser:f.isolatedBrowserNotInstalled:f.isolatedBrowserUnavailable,We=t&&e===null?f.checking:n?f.checkFailed:Ie?_?f.enabled:f.disabled:f.unavailable,Ge=a&&i===null?f.checking:o?f.checkFailed:i?.dockerAvailable?i.imageReady?y?f.enabled:f.disabled:f.computerRuntimeMissing:f.dockerUnavailable,Ke=(0,G.useMemo)(()=>uN(R),[R]),qe=(0,G.useMemo)(()=>Ke.map(({provider:e,home:t})=>{let n=lN(e.id,t.id);return{key:n,domId:`${e.id}-${t.id}`,label:`${iN(e)} · ${t.id}`,extensions:t.extensions.map(r=>({...r,agentName:`${iN(e)} · ${t.id}`,homeKey:n,homeId:t.id}))}}),[Ke]),Xe=qe.find(e=>e.key===me)||qe[0],Ze=(0,G.useMemo)(()=>qe.flatMap(e=>e.extensions),[qe]),Qe=(0,G.useMemo)(()=>{let e=new Map;return Xe?.extensions.forEach(t=>{e.set(t.kind,(e.get(t.kind)||0)+1)}),e},[Xe]),$e=(0,G.useMemo)(()=>{let e=[...Qe.keys()].filter(e=>!YM.includes(e)).sort((e,t)=>e.localeCompare(t));return[...YM,...e].map(e=>({kind:e,count:Qe.get(e)||0}))},[Qe]),et=Qe.get(ge)?ge:$e.find(e=>e.count>0)?.kind||ge,tt=(0,G.useMemo)(()=>{let e=_e.trim().toLocaleLowerCase(),t=(Xe?.extensions||[]).filter(e=>e.kind===et);return e?t.filter(t=>[t.name,t.description,t.sourceFile,t.kind,t.scope,t.agentName].some(t=>t.toLocaleLowerCase().includes(e))):t},[_e,Xe,et]),W=(0,G.useCallback)(e=>{let t=qe.findIndex(e=>e.key===Xe?.key),n=t;if(e.key===`ArrowRight`)n=(t+1)%qe.length;else if(e.key===`ArrowLeft`)n=(t-1+qe.length)%qe.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=qe.length-1;else return;let r=qe[n];r&&(e.preventDefault(),he(r.key),ve(``),window.requestAnimationFrame(()=>{document.getElementById(`code-plugin-extension-home-${r.domId}`)?.focus()}))},[qe,Xe?.key]),rt=(0,G.useCallback)(e=>{let t=$e.filter(e=>e.count>0),n=t.findIndex(e=>e.kind===et),r=n;if(e.key===`ArrowRight`)r=(n+1)%t.length;else if(e.key===`ArrowLeft`)r=(n-1+t.length)%t.length;else if(e.key===`Home`)r=0;else if(e.key===`End`)r=t.length-1;else return;let i=t[r];i&&(e.preventDefault(),H(i.kind),ve(``),window.requestAnimationFrame(()=>{document.getElementById(`code-plugin-extension-kind-${i.kind}`)?.focus()}))},[$e,et]),it=(0,G.useCallback)(e=>{pe(e),de(null)},[]),ot=(0,G.useCallback)(e=>{let t=XM.indexOf(fe),n=t;if(e.key===`ArrowRight`)n=(t+1)%XM.length;else if(e.key===`ArrowLeft`)n=(t-1+XM.length)%XM.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=XM.length-1;else return;e.preventDefault();let r=XM[n];r&&(it(r),window.requestAnimationFrame(()=>{document.getElementById(`code-plugin-tab-${r}`)?.focus()}))},[fe,it]);return(0,K.jsxs)(`div`,{className:`code-plugins-panel`,"data-testid":`code-plugins-panel`,children:[(0,K.jsxs)(`header`,{className:`code-plugins-panel-header`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:l,"aria-label":f.back,title:f.back,children:(0,K.jsx)(nt,{})}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h2`,{children:f.title}),(0,K.jsx)(`p`,{children:f.description})]})]}),(0,K.jsx)(`div`,{className:`code-plugin-tabs`,role:`tablist`,"aria-label":f.title,children:XM.map(e=>{let t=e===`farming`?2:e===`homes`?Ke.length:Ze.length;return(0,K.jsxs)(`button`,{id:`code-plugin-tab-${e}`,type:`button`,role:`tab`,"data-testid":`code-plugin-tab-${e}`,"aria-selected":fe===e,"aria-controls":`code-plugin-panel-${e}`,tabIndex:fe===e?0:-1,onClick:()=>it(e),onKeyDown:ot,children:[(0,K.jsx)(`span`,{children:f.tabs[e]}),(0,K.jsx)(`small`,{children:t})]},e)})}),fe===`farming`?(0,K.jsxs)(`section`,{id:`code-plugin-panel-farming`,className:`code-plugin-section code-plugin-tab-panel`,"data-testid":`code-plugin-section-farming`,role:`tabpanel`,"aria-labelledby":`code-plugin-tab-farming`,children:[(0,K.jsx)(`header`,{className:`code-plugin-section-header`,children:(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:f.farmingBuiltIn}),(0,K.jsx)(`p`,{children:f.farmingBuiltInDescription})]})}),(0,K.jsxs)(`article`,{className:`code-plugin-card`,"data-testid":`code-plugin-browser`,children:[(0,K.jsx)(`span`,{className:`code-plugin-card-icon`,"aria-hidden":`true`,children:(0,K.jsx)(at,{})}),(0,K.jsxs)(`div`,{className:`code-plugin-card-copy`,children:[(0,K.jsxs)(`div`,{className:`code-plugin-card-title`,children:[(0,K.jsx)(`h3`,{children:f.browser}),(0,K.jsx)(`span`,{className:`code-plugin-status ${Ie&&_?`enabled`:``}`,children:We})]}),(0,K.jsx)(`p`,{children:f.browserDescription}),(0,K.jsxs)(`div`,{className:`code-plugin-browser-settings`,children:[(0,K.jsx)(gt,{className:`code-plugin-select`,label:f.browserChoice,value:t&&e===null?`system:`:I,disabled:t&&e===null||k||j,options:[...(e?.options||[]).length===0?[{value:`system:`,label:f.noSystemBrowser,disabled:!0}]:[],...(e?.options||[]).map(e=>({value:`system:${e.path}`,label:rN(e.kind)})),{value:`isolated`,label:Ue,disabled:!Ve}],onChange:e=>{te.current=!0,L(e),ee(``)}}),(0,K.jsx)(`button`,{type:`button`,className:`code-plugin-browser-apply`,disabled:k||j||!Re||I===`isolated`&&!ze,onClick:()=>void Me(),children:f.applyBrowser}),He?(0,K.jsx)(`button`,{type:`button`,className:`code-plugin-browser-install`,disabled:j,onClick:()=>void Ne(),children:j?f.preparingIsolatedBrowser:f.prepareIsolatedBrowser}):null]}),(0,K.jsx)(`small`,{children:t&&e===null?f.checking:(0,K.jsxs)(K.Fragment,{children:[Ie?nN(e,f):f.unavailableHint,` · `,f.browserChangeHint]})}),He?(0,K.jsx)(`small`,{children:f.isolatedBrowserHint}):null,e?.isolated?.dockerAvailable===!1?(0,K.jsxs)(`small`,{children:[f.isolatedBrowserDockerRequired,` `,(0,K.jsx)(`a`,{className:`code-plugin-help-link`,href:m,target:`_blank`,rel:`noreferrer`,children:h})]}):null,N?(0,K.jsxs)(`div`,{className:`code-plugin-computer-settings`,children:[(0,K.jsx)(`small`,{children:f.isolatedCompatibilityRequired}),(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:x,disabled:C||T||y,onChange:e=>{let t=e.currentTarget.checked;S(t),Pe({computerCompatibilityMode:t})}}),(0,K.jsx)(`span`,{children:f.compatibilityMode})]}),(0,K.jsx)(`small`,{children:f.compatibilityHint})]}):null,(F||n||e?.isolated?.dockerAvailable!==!1&&e?.isolated?.error)&&(0,K.jsx)(`div`,{className:`code-plugin-error`,role:`alert`,children:F||(n?f.browserCheckFailed:``)||e?.isolated?.error})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-plugin-toggle ${_?`active`:``}`,"aria-pressed":t||n?!1:_,disabled:!!n||t||k||j||!Ie&&!_,onClick:()=>void je(),children:t?f.checking:n?f.checkFailed:_?f.disable:f.enable})]}),(0,K.jsxs)(`article`,{className:`code-plugin-card`,"data-testid":`code-plugin-computer`,children:[(0,K.jsx)(`span`,{className:`code-plugin-card-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Te,{})}),(0,K.jsxs)(`div`,{className:`code-plugin-card-copy`,children:[(0,K.jsxs)(`div`,{className:`code-plugin-card-title`,children:[(0,K.jsx)(`h3`,{children:f.computer}),(0,K.jsx)(`span`,{className:`code-plugin-status ${i?.imageReady&&y?`enabled`:``}`,children:Ge})]}),(0,K.jsx)(`p`,{children:f.computerDescription}),(0,K.jsxs)(`div`,{className:`code-plugin-desktop-targets`,children:[(0,K.jsx)(`strong`,{children:f.desktopTargets}),(0,K.jsx)(`div`,{className:`code-plugin-desktop-target`,children:(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:f.isolatedDesktop}),(0,K.jsx)(`small`,{children:f.isolatedDesktopDescription})]})})]}),(0,K.jsxs)(`div`,{className:`code-plugin-computer-settings`,children:[(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:x,disabled:C||T||y,onChange:e=>{let t=e.currentTarget.checked;S(t),Pe({computerCompatibilityMode:t})}}),(0,K.jsx)(`span`,{children:f.compatibilityMode})]}),(0,K.jsx)(`small`,{children:f.compatibilityHint}),!i?.imageReady&&(0,K.jsx)(`button`,{type:`button`,disabled:T||C||!i?.dockerAvailable,onClick:()=>void Fe(),children:T?f.preparingComputer:f.prepareComputer})]}),(0,K.jsx)(`small`,{children:f.computerRuntimeHint}),i?.dockerAvailable===!1?(0,K.jsxs)(`small`,{children:[p?f.dockerMacGuidance:f.dockerHostGuidance,` `,(0,K.jsx)(`a`,{className:`code-plugin-help-link`,href:m,target:`_blank`,rel:`noreferrer`,children:h})]}):null,(D||o)&&(0,K.jsx)(`div`,{className:`code-plugin-error`,role:`alert`,children:D||(o?f.computerCheckFailed:``)})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-plugin-toggle ${y?`active`:``}`,"aria-pressed":a||o?!1:y,disabled:!!o||a||C||T||!i?.imageReady&&!y,onClick:()=>void Pe({computerExtensionEnabled:!y}),children:a?f.checking:o?f.checkFailed:y?f.disable:f.enable})]})]}):null,fe===`homes`?(0,K.jsxs)(`div`,{id:`code-plugin-panel-homes`,className:`code-plugin-agent-sections code-plugin-tab-panel`,"data-testid":`code-plugin-agent-sections`,role:`tabpanel`,"aria-labelledby":`code-plugin-tab-homes`,children:[(0,K.jsxs)(`header`,{className:`code-plugin-agent-sections-header`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:f.agentHomes}),(0,K.jsx)(`p`,{children:f.agentHomesDescription})]}),(0,K.jsxs)(`button`,{type:`button`,className:`code-plugin-agent-add`,disabled:B||R.length===0,onClick:()=>{ae(``),se(e=>e?null:{provider:R.find(e=>e.available)?.id||R[0]?.id||`codex`,id:``,path:``})},children:[(0,K.jsx)(Le,{}),(0,K.jsx)(`span`,{children:f.addAgent})]})]}),V?(0,K.jsxs)(`div`,{className:`code-plugin-agent-form`,"data-testid":`code-plugin-agent-form`,children:[(0,K.jsx)(gt,{className:`code-plugin-select`,label:f.agentProvider,value:V.provider,disabled:B,options:R.filter(e=>e.available).map(e=>({value:e.id,label:iN(e)})),onChange:e=>se(t=>t&&{...t,provider:e})}),(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:f.homePath}),(0,K.jsx)(`input`,{type:`text`,value:V.path,placeholder:f.homePathPlaceholder,disabled:B,onChange:e=>se(t=>t&&{...t,path:e.target.value})})]}),(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:f.homeName}),(0,K.jsx)(`input`,{type:`text`,value:V.id,placeholder:f.homeNamePlaceholder,disabled:B,onChange:e=>se(t=>t&&{...t,id:e.target.value})})]}),(0,K.jsxs)(`div`,{className:`code-plugin-agent-form-actions`,children:[(0,K.jsx)(`button`,{type:`button`,disabled:B,onClick:()=>se(null),children:f.cancel}),(0,K.jsx)(`button`,{type:`button`,className:`primary`,disabled:B,onClick:Ee,children:f.save})]})]}):null,ie?(0,K.jsx)(`div`,{className:`code-plugin-error`,role:`alert`,children:ie}):null,re?(0,K.jsx)(`p`,{className:`code-plugin-empty`,children:f.loadingAgentExtensions}):Ke.map((e,t,n)=>{let{provider:r,home:i}=e,a=lN(r.id,i.id),o=i.extensions.length,s=i.configuration.summary.length>0?i.configuration.summary.map(e=>`${sN(e.key,f)}: ${e.value}`).join(` · `):i.configuration.exists?f.inheritConfiguration(i.configuration.filePath):f.missingConfiguration(i.configuration.filePath);return(0,K.jsxs)(`section`,{className:`code-plugin-section code-plugin-agent-section ${ce===a?`dragging`:``}`,"data-testid":`code-plugin-section-agent-${r.id}-${i.id}`,draggable:!B,onDragStart:e=>{le(a),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,a)},onDragEnd:()=>le(``),onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`},onDrop:e=>{e.preventDefault();let t=e.dataTransfer.getData(`text/plain`)||ce;le(``),Oe(t,a)},children:[(0,K.jsxs)(`header`,{className:`code-plugin-section-header code-plugin-agent-header`,children:[(0,K.jsx)(`span`,{className:`code-plugin-agent-drag`,"aria-hidden":`true`,title:f.dragToReorder,children:`⋮⋮`}),(0,K.jsxs)(`div`,{className:`code-plugin-agent-identity`,children:[(0,K.jsxs)(`h3`,{children:[iN(r),(0,K.jsx)(`span`,{children:i.id}),r.available?null:(0,K.jsx)(`em`,{children:f.unavailableAgent}),(0,K.jsx)(`small`,{children:f.count(o)})]}),(0,K.jsx)(`p`,{children:(0,K.jsx)(`code`,{children:i.path})})]}),(0,K.jsxs)(`div`,{className:`code-plugin-agent-actions`,children:[(0,K.jsx)(`button`,{type:`button`,disabled:B||t===0,"aria-label":f.moveUp,title:f.moveUp,onClick:()=>Ae(a,-1),children:(0,K.jsx)(Ye,{})}),(0,K.jsx)(`button`,{type:`button`,disabled:B||t===n.length-1,"aria-label":f.moveDown,title:f.moveDown,onClick:()=>Ae(a,1),children:(0,K.jsx)(Je,{})}),(0,K.jsx)(`button`,{type:`button`,disabled:B||!i.configuration.rootId||!i.configuration.filePath,"aria-label":f.edit,title:f.edit,onClick:()=>u(i.configuration),children:(0,K.jsx)(ke,{})}),i.id===`default`?null:(0,K.jsx)(`button`,{type:`button`,disabled:B,"aria-label":f.remove,title:f.remove,onClick:()=>De(r.id,i.id),children:(0,K.jsx)(pt,{})})]})]}),(0,K.jsxs)(`div`,{className:`code-plugin-agent-configuration`,children:[(0,K.jsx)(`strong`,{children:f.homeConfiguration}),(0,K.jsx)(`span`,{children:s})]}),r.discoverySupported?null:(0,K.jsx)(`p`,{className:`code-plugin-agent-note`,children:f.unsupportedDiscovery})]},a)})]}):null,fe===`extensions`?(0,K.jsxs)(`section`,{id:`code-plugin-panel-extensions`,className:`code-plugin-extensions code-plugin-tab-panel`,"data-testid":`code-plugin-extensions`,role:`tabpanel`,"aria-labelledby":`code-plugin-tab-extensions`,children:[(0,K.jsxs)(`header`,{className:`code-plugin-extensions-header`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:f.agentExtensions}),(0,K.jsx)(`p`,{children:f.agentExtensionsDescription})]}),(0,K.jsxs)(`div`,{className:`code-plugin-extension-tools`,children:[(0,K.jsxs)(`label`,{className:`code-plugin-extension-search`,children:[(0,K.jsx)(`span`,{children:f.searchExtensions}),(0,K.jsx)(`input`,{type:`search`,value:_e,placeholder:f.searchExtensions,"aria-label":f.searchExtensions,onChange:e=>ve(e.target.value)})]}),(0,K.jsx)(`button`,{type:`button`,disabled:re||B,onClick:()=>void Ce(),children:f.refresh})]})]}),ie?(0,K.jsx)(`div`,{className:`code-plugin-error`,role:`alert`,children:ie}):null,re?(0,K.jsx)(`p`,{className:`code-plugin-empty`,children:f.loadingAgentExtensions}):qe.length===0?(0,K.jsx)(`p`,{className:`code-plugin-empty`,children:f.noAgentExtensions}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`code-plugin-extension-home-tabs`,role:`tablist`,"aria-label":f.agentHomes,children:qe.map(e=>(0,K.jsxs)(`button`,{id:`code-plugin-extension-home-${e.domId}`,type:`button`,role:`tab`,"data-testid":`code-plugin-extension-home-${e.domId}`,"aria-selected":Xe?.key===e.key,tabIndex:Xe?.key===e.key?0:-1,onClick:()=>{he(e.key),ve(``)},onKeyDown:W,children:[(0,K.jsx)(`span`,{children:e.label}),(0,K.jsx)(`small`,{children:e.extensions.length})]},e.key))}),(0,K.jsx)(`div`,{className:`code-plugin-extension-kind-tabs`,role:`tablist`,"aria-label":f.agentExtensions,children:$e.map(e=>(0,K.jsxs)(`button`,{id:`code-plugin-extension-kind-${e.kind}`,type:`button`,role:`tab`,"data-testid":`code-plugin-extension-kind-${e.kind}`,"aria-selected":et===e.kind,disabled:e.count===0,tabIndex:et===e.kind?0:-1,onClick:()=>{H(e.kind),ve(``)},onKeyDown:rt,children:[(0,K.jsx)(`span`,{children:cN(e.kind,f)}),(0,K.jsx)(`small`,{children:e.count})]},e.kind))}),tt.length===0?(0,K.jsx)(`p`,{className:`code-plugin-empty`,children:_e.trim()?f.noMatchingExtensions:f.noAgentExtensions}):(0,K.jsx)(`section`,{className:`code-plugin-extension-group`,"data-kind":et,role:`tabpanel`,"aria-labelledby":`code-plugin-extension-kind-${et}`,children:(0,K.jsx)(`div`,{className:`code-plugin-extension-list`,children:tt.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-plugin-extension`,onClick:()=>de(e),children:[(0,K.jsx)(`span`,{className:`code-plugin-extension-icon`,"aria-hidden":`true`,children:oN(e.kind)}),(0,K.jsxs)(`span`,{className:`code-plugin-extension-copy`,children:[(0,K.jsxs)(`span`,{className:`code-plugin-extension-title`,children:[(0,K.jsx)(`strong`,{children:e.name}),(0,K.jsx)(`span`,{children:aN(e.kind,f)})]}),(0,K.jsxs)(`span`,{className:`code-plugin-extension-meta`,children:[(0,K.jsx)(`code`,{children:e.sourceFile}),e.scope?(0,K.jsx)(`span`,{children:e.scope}):null,(0,K.jsx)(`span`,{className:`code-plugin-extension-status ${e.status}`,children:f.extensionStatus[e.status]})]}),(0,K.jsx)(`span`,{className:`code-plugin-extension-description`,children:e.description})]}),(0,K.jsx)(`span`,{className:`code-plugin-extension-owner`,children:e.agentName})]},`${e.agentName}:${e.id}`))})})]})]}):null,ue?(0,K.jsx)(`div`,{className:`code-plugin-detail-backdrop`,role:`presentation`,onPointerDown:()=>de(null),children:(0,K.jsxs)(`section`,{className:`code-plugin-detail-dialog`,"data-testid":`code-plugin-detail-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-plugin-detail-title`,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),de(null))},children:[(0,K.jsxs)(`header`,{children:[(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`small`,{children:[ue.agentName,` · `,f.extensionDetails]}),(0,K.jsx)(`h3`,{id:`code-plugin-detail-title`,children:ue.name})]}),(0,K.jsx)(`button`,{type:`button`,autoFocus:!0,"aria-label":f.closeDetails,title:f.closeDetails,onClick:()=>de(null),children:(0,K.jsx)(pt,{})})]}),(0,K.jsxs)(`div`,{className:`code-plugin-detail-meta`,children:[(0,K.jsx)(`span`,{children:aN(ue.kind,f)}),ue.scope?(0,K.jsx)(`span`,{children:ue.scope}):null,(0,K.jsx)(`span`,{children:f.extensionStatus[ue.status]}),ue.homeId===`default`?null:(0,K.jsxs)(`span`,{children:[f.home,`: `,ue.homeId]})]}),(0,K.jsx)(`p`,{children:ue.description}),(0,K.jsxs)(`div`,{className:`code-plugin-detail-source`,children:[(0,K.jsx)(`span`,{children:f.source}),(0,K.jsx)(`code`,{children:ue.sourceFile})]}),(0,K.jsxs)(`button`,{type:`button`,className:`code-plugin-detail-open`,disabled:!ue.rootId||!ue.sourceFile,onClick:()=>u({exists:!0,filePath:ue.sourceFile,rootId:ue.rootId}),children:[(0,K.jsx)(ke,{}),(0,K.jsx)(`span`,{children:f.openSource})]})]})}):null]})}var hN=`farming.code.terminalComposerCollapsed.v1`;function gN(){try{return window.localStorage.getItem(hN)===`true`}catch{return!1}}function _N(e){try{window.localStorage.setItem(hN,String(e))}catch{}}function vN(){return typeof window<`u`&&window.matchMedia(`(hover: hover) and (pointer: fine)`).matches&&!de()}function yN(e,t){return!e||!t?!1:e.id===t||e.restartedFromAgentId===t||e.restartedFromAgentIds?.includes(t)===!0}var bN=`farming.code.fileEditor.chunk-recovery`,xN=null,SN=null;function CN(){if(typeof window>`u`)return!1;try{return window.sessionStorage.getItem(bN)===`1`?!1:(window.sessionStorage.setItem(bN,`1`),window.location.reload(),!0)}catch{return!1}}function wN(){return xN||=Promise.all([s(()=>import(`./FileEditorPane-BX-Wjg9U.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])),s(()=>import(`./workspace-editor-monaco-N641qPjX.js`).then(e=>{e.preloadWorkspaceEditorMonaco()}),__vite__mapDeps([18,10,1,3,11,12,13,14,15,8,7]))]).then(([e])=>{try{window.sessionStorage.removeItem(bN)}catch{}return SN=e.FileEditorPane,{default:SN}}),xN}function TN(e){wN().then(t=>{e(t.default)}).catch(()=>{})}function EN(){return wN().catch(e=>{if(CN())return new Promise(()=>{});throw e})}function DN(e){return e.split(`/`).filter(Boolean).pop()||e}function ON(e){return e.split(`/`).filter(Boolean)}function kN(e){return e?e.replace(/\\/g,`/`).split(`/`).filter(Boolean).pop()||`/`:``}function AN({openFile:e,onChangeDraft:t,copy:n}){let r=ON(e.file.path),i=kN(e.workspaceRoot),a=!e.file.preview&&!Ft(e.file.path)&&!Pt(e.file.path)&&!It(e.file.path),o=e.workspaceRoot?`${e.workspaceRoot.replace(/[\\/]+$/,``)}/${e.file.path}`:e.file.path;return(0,K.jsxs)(`section`,{className:`code-file-editor fallback`,"data-testid":`code-file-editor`,"aria-label":n.editorFor(e.file.path),children:[(0,K.jsxs)(`header`,{className:`code-file-editor-header`,children:[(0,K.jsx)(`div`,{className:`code-file-editor-tab-strip`,children:(0,K.jsx)(`div`,{className:`code-file-editor-tabs`,role:`tablist`,children:(0,K.jsxs)(`div`,{className:`code-file-editor-tab active ${e.dirty?`dirty`:``} ${e.externalChanged?`warning`:``}`,title:e.file.path,role:`tab`,"aria-selected":`true`,children:[(0,K.jsx)(`span`,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`code-file-editor-tab-name`,children:DN(e.file.path)}),(0,K.jsx)(`span`,{className:`code-file-editor-tab-tail`,children:(e.dirty||e.externalChanged)&&(0,K.jsx)(`span`,{className:`code-file-editor-dirty`,title:e.externalChanged?n.changedOnDisk:n.unsavedChanges})})]})})}),a&&(0,K.jsxs)(`div`,{className:`code-file-editor-bar`,children:[(0,K.jsxs)(`nav`,{className:`code-file-editor-breadcrumbs`,title:o,"aria-label":n.filePath,children:[i&&(0,K.jsxs)(`span`,{className:`code-file-editor-breadcrumb root`,children:[(0,K.jsx)(`span`,{className:`code-file-editor-breadcrumb-name`,children:i}),(0,K.jsx)(`span`,{className:`code-file-editor-breadcrumb-separator`,"aria-hidden":`true`})]}),r.map((e,t)=>(0,K.jsxs)(`span`,{className:`code-file-editor-breadcrumb ${t===r.length-1?`current`:``}`,children:[(0,K.jsx)(`span`,{className:`code-file-editor-breadcrumb-name`,children:e}),t<r.length-1&&(0,K.jsx)(`span`,{className:`code-file-editor-breadcrumb-separator`,"aria-hidden":`true`})]},`${t}-${e}`))]}),(0,K.jsx)(`div`,{className:`code-file-editor-actions`,children:e.dirty&&(0,K.jsx)(`span`,{className:`code-file-editor-status`,children:n.unsavedChanges})})]})]}),(0,K.jsx)(`textarea`,{className:`code-file-editor-fallback-textarea`,"data-testid":`code-file-editor-fallback-textarea`,name:`farming-file-editor-fallback`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,value:e.draft,onChange:e=>t(e.currentTarget.value),spellCheck:!1,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,"aria-label":n.editorFor(e.file.path)}),(0,K.jsx)(`footer`,{className:`code-file-editor-statusbar`,children:(0,K.jsx)(`span`,{className:`code-file-editor-cursor-position`,children:n.cursorPosition(1,1)})})]})}function jN(e,t){return t===`search`?e.search:t===`history`?e.history:t===`plugins`?e.plugins:`Farming`}function MN({action:e}){return e===`new-agent`?(0,K.jsx)(Ee,{}):e===`plugins`?(0,K.jsx)(ht,{}):e===`search`?(0,K.jsx)(Oe,{}):e===`history`?(0,K.jsx)(Ie,{}):e===`share`?(0,K.jsx)(He,{}):(0,K.jsx)(Ce,{})}function NN({agentCreationWorkspace:e,onNewAgent:t,onOpenHistory:n,onOpenPlugins:r,onOpenSearch:i,onOpenShare:a,onOpenAppMode:o,copy:s}){let c=(0,G.useRef)(null),l=(0,G.useRef)(null),u=(0,G.useRef)(null),[d,f]=(0,G.useState)(null),p=[{action:`search`,title:s.search,description:s.emptyWorkspaceSearchDescription,onClick:i},{action:`share`,title:s.sharePage,description:s.emptyWorkspaceShareDescription,onClick:a},{action:`focus`,title:s.emptyWorkspaceFocus,description:s.emptyWorkspaceFocusDescription,onClick:o},{action:`plugins`,title:s.plugins,description:s.emptyWorkspacePluginsDescription,onClick:r}];return(0,G.useLayoutEffect)(()=>{let e=c.current,t=l.current,n=u.current;if(!e||!t||!n)return;let r=()=>{let r=e.getBoundingClientRect(),i=t.getBoundingClientRect(),a=n.getBoundingClientRect();if(r.width===0||i.width===0||a.width===0){f(null);return}let o=i.right-r.left+5,s=i.top+i.height/2-r.top,c=a.left-r.left-o,l=a.top+a.height/2-r.top-s;if(c<=0||l<=0){f(null);return}f(e=>{let t={height:l,left:o,top:s,width:c};return e&&e.height===t.height&&e.left===t.left&&e.top===t.top&&e.width===t.width?e:t})};r();let i=new ResizeObserver(r);return i.observe(e),i.observe(t),i.observe(n),()=>i.disconnect()},[]),(0,K.jsxs)(`div`,{ref:c,className:`code-empty-home`,children:[(0,K.jsx)(`span`,{ref:l,className:`code-empty-home-brace`,"data-testid":`code-empty-home-brace`,"aria-hidden":`true`,children:(0,K.jsx)(`svg`,{viewBox:`0 0 12 28`,children:(0,K.jsx)(`path`,{d:`M2 1.25h1.2c2.25 0 3.2 1.55 3.2 4.1v4.05c0 2.5 1.05 4.05 3.6 4.6-2.55.55-3.6 2.1-3.6 4.6v4.05c0 2.55-.95 4.1-3.2 4.1H2`})})}),d&&(0,K.jsxs)(`svg`,{className:`code-empty-home-connector`,viewBox:`0 0 100 100`,preserveAspectRatio:`none`,style:d,"aria-hidden":`true`,children:[(0,K.jsxs)(`defs`,{children:[(0,K.jsxs)(`linearGradient`,{id:`code-empty-home-connector-weight`,x1:`0`,y1:`0`,x2:`0`,y2:`1`,children:[(0,K.jsx)(`stop`,{offset:`0`,stopColor:`white`,stopOpacity:`0`}),(0,K.jsx)(`stop`,{offset:`0.56`,stopColor:`white`,stopOpacity:`0.65`}),(0,K.jsx)(`stop`,{offset:`0.78`,stopColor:`white`,stopOpacity:`1`}),(0,K.jsx)(`stop`,{offset:`1`,stopColor:`white`,stopOpacity:`1`})]}),(0,K.jsx)(`mask`,{id:`code-empty-home-connector-mask`,maskUnits:`objectBoundingBox`,children:(0,K.jsx)(`rect`,{width:`100%`,height:`100%`,fill:`url(#code-empty-home-connector-weight)`})})]}),(0,K.jsx)(`path`,{className:`code-empty-home-connector-base`,d:`M0 0C200 0-100 100 100 100`}),(0,K.jsx)(`path`,{className:`code-empty-home-connector-growth`,d:`M0 0C200 0-100 100 100 100`,mask:`url(#code-empty-home-connector-mask)`})]}),(0,K.jsxs)(`header`,{className:`code-empty-home-header`,children:[(0,K.jsx)(`h2`,{children:s.emptyWorkspaceWelcome}),(0,K.jsx)(`p`,{children:s.emptyWorkspaceWelcomeDescription})]}),(0,K.jsxs)(`div`,{className:`code-empty-home-action-map`,children:[(0,K.jsx)(`span`,{ref:u,className:`code-empty-home-target-brace`,"data-testid":`code-empty-home-target-brace`,"aria-hidden":`true`,children:(0,K.jsx)(`svg`,{viewBox:`0 0 30 100`,preserveAspectRatio:`none`,children:(0,K.jsx)(`path`,{d:`M28 1h-2.4C16 1 14 8.5 14 20v14c0 8.6-4 13.9-14 16 10 2.1 14 7.4 14 16v14c0 11.5 2 19 11.6 19H28`})})}),(0,K.jsxs)(`div`,{className:`code-empty-home-actions`,children:[(0,K.jsxs)(`div`,{className:`code-empty-home-primary`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-empty-home-card primary history`,"data-testid":`code-empty-home-history`,onClick:n,children:[(0,K.jsx)(`span`,{className:`code-empty-home-card-icon`,children:(0,K.jsx)(MN,{action:`history`})}),(0,K.jsx)(`strong`,{children:s.emptyWorkspaceContinue}),(0,K.jsx)(`span`,{children:s.emptyWorkspaceContinueDescription})]}),(0,K.jsxs)(`button`,{type:`button`,className:`code-empty-home-card primary`,"data-testid":`code-empty-home-new-agent`,onClick:()=>t(e),children:[(0,K.jsx)(`span`,{className:`code-empty-home-card-icon`,children:(0,K.jsx)(MN,{action:`new-agent`})}),(0,K.jsx)(`strong`,{children:s.newAgent}),(0,K.jsx)(`span`,{children:s.emptyWorkspaceNewAgentDescription})]})]}),(0,K.jsx)(`div`,{className:`code-empty-home-utilities`,children:p.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-empty-home-card utility`,"data-testid":`code-empty-home-${e.action}`,onClick:e.onClick,children:[(0,K.jsx)(`span`,{className:`code-empty-home-card-icon`,children:(0,K.jsx)(MN,{action:e.action})}),(0,K.jsxs)(`span`,{className:`code-empty-home-card-copy`,children:[(0,K.jsx)(`strong`,{children:e.title}),(0,K.jsx)(`span`,{children:e.description})]})]},e.action))})]})]})]})}function PN({activeView:e,activeBrowserResource:t,browserController:n,onBackFromBrowser:r,onOpenBrowserResource:i,activeComputerResource:a,computerController:o,onBackFromComputer:s,language:c,showFileEditor:l,openWorkspaceFile:u,openWorkspaceFiles:d,openAgentsCount:f,openAgents:p,activeTerminalId:m,permissionSwitchingAgentId:h,agentSwitchingKind:g,terminalFocusRequest:_,agentCreationWorkspace:v,displayedProjects:y,searchQuery:b,searchHasQuery:x,searchLoading:S,visibleSearchTargetCount:C,selectedSearchAgentId:w,selectedSearchSessionHandle:T,searchInputRef:E,archivedRuns:D,archivedAgents:O,historyAgentSessions:k,historyAgentSessionsLoading:A,historyAgentSessionsError:j,providerSessionTotal:M,canLoadMoreHistoryAgentSessions:N,now:P,composerProps:F,acpComposerProps:ee,onNewAgent:I,onOpenHistory:L,onOpenPlugins:te,onOpenAgentHomeConfiguration:R,onOpenSearch:ne,onOpenShare:re,onOpenAppMode:z,onOpenTerminal:ie,onOpenTerminalPath:B,onResolveTerminalPath:oe,onSearchTerminalWord:V,onTerminalFollowOutputChange:se,onAgentReadLatest:ce,onRuntimeModeChange:le,onForkAgent:ue,onSessionOutput:de,onOpenSearchAgent:fe,onOpenSearchSession:pe,onSearchQueryChange:me,onSearchKeyDown:he,onCloseSearch:ge,onBackToProjects:H,onLoadMoreHistoryAgentSessions:_e,onSearchHistoryAgentSessions:ve,onResumeHistorySession:ye,onContinueArchivedRun:be,onOpenArchivedAgent:xe,onRestoreArchivedAgent:Se,onChangeWorkspaceFileDraft:U,onUpdateOpenWorkspaceFile:Ce,onSelectOpenWorkspaceFile:we,onOpenWorkspaceFilePath:Te,onOpenUrlInFarming:De,canNavigateWorkspaceBack:Oe,canNavigateWorkspaceForward:ke,onNavigateWorkspaceHistory:Ae,onCloseOpenWorkspaceFile:je,onCloseOpenWorkspaceFiles:Me,onReorderOpenWorkspaceFile:Ne,onRevealWorkspaceFileInExplorer:Pe,onFocusWorkspaceFilesSearch:Fe,onRecordWorkspaceNavigationCursor:Le,onBackToAgentFromFile:Re,copy:ze}){let[Be,Ve]=(0,G.useState)(gN),[He,Ue]=(0,G.useState)(!1),[We,Ke]=(0,G.useState)(null),[Je,Ye]=(0,G.useState)(``),Xe=(0,G.useRef)({agentId:null,kind:null}),[Ze,Qe]=(0,G.useState)(vN),[$e,et]=(0,G.useState)(()=>SN),[tt,nt]=(0,G.useState)(null),W=$e??SN,rt=l&&u!==null;(0,G.useEffect)(()=>{let e=!0;return TN(t=>{e&&et(()=>t)}),()=>{e=!1}},[]),(0,G.useEffect)(()=>{if(!rt||W)return;let e=!0;return EN().then(t=>{e&&et(()=>t.default)}).catch(t=>{e&&nt(t)}),()=>{e=!1}},[W,rt]);let it=m&&p.find(e=>e.id===m)||null,at=e===`projects`&&t!==null,ot=e===`projects`&&a!==null,st=e===`projects`&&!at&&!ot&&!(l&&u),ct=mr(it),lt=it?(n.byAgentId.get(it.id)??[]).filter(e=>e.status===`running`).sort((e,t)=>t.updatedAt-e.updatedAt)[0]??null:null,ut=lt?`${lt.id}:${lt.generation}`:``,dt=it?.runtimeBinding.kind===`terminal`,ft=dt?We===it?.id?!1:Be:He,pt=Ze&&e===`projects`&&!l&&f>0,mt=pt&&ft;(0,G.useLayoutEffect)(()=>{let e=Xe.current,t=ct?`acp`:dt?`terminal`:null;e.kind===`acp`&&t===`terminal`&&it?.id&&yN(it,e.agentId)&&Ke(it.id),Xe.current={agentId:it?.id??null,kind:t}},[ct,it?.id,dt]),(0,G.useEffect)(()=>{let e=window.matchMedia(`(hover: hover) and (pointer: fine)`),t=()=>Qe(vN());return t(),e.addEventListener(`change`,t),window.addEventListener(`resize`,t),()=>{e.removeEventListener(`change`,t),window.removeEventListener(`resize`,t)}},[]),(0,G.useEffect)(()=>{!pt&&He&&Ue(!1)},[pt,He]);let gt=(0,G.useCallback)(()=>{n.refreshCapability(),o.refreshCapability()},[n.refreshCapability,o.refreshCapability]),_t=(0,G.useCallback)(e=>{if(dt){Ke(null),Ve(e),_N(e);return}Ue(e)},[dt]),vt=(0,G.useCallback)(e=>{if(!ae())return;let t=e.target;if(t instanceof Element&&t.closest(`.code-composer`))return;let n=document.activeElement;n instanceof HTMLElement&&n.closest(`.code-composer`)&&(n instanceof HTMLTextAreaElement||n.isContentEditable||n.getAttribute(`role`)===`textbox`)&&n.blur()},[]);if(tt)throw tt;return(0,K.jsxs)(`main`,{className:`code-main`,"data-testid":`code-main`,onPointerDownCapture:vt,onTouchStartCapture:vt,children:[e===`projects`?at?(0,K.jsx)(zT,{resource:t,controller:n,language:c,onResource:n.mergeResource,onOpenResource:i,onBackToAgent:r}):ot?(0,K.jsx)(UT,{resource:a,controller:o,language:c,onBackToAgent:s}):l&&u?W?(0,K.jsx)(W,{openFile:u,openFiles:d,onChangeDraft:U,onUpdateOpenFile:Ce,onSelectOpenFile:we,onOpenFilePath:Te,canNavigateBack:Oe,canNavigateForward:ke,onNavigateHistory:Ae,onCloseOpenFile:je,onCloseOpenFiles:Me,onReorderOpenFile:Ne,onRevealInExplorer:Pe,onFocusFilesSearch:Fe,onRecordNavigationCursor:Le,onBackToAgent:Re,copy:ze}):(0,K.jsx)(AN,{openFile:u,onChangeDraft:U,copy:ze}):null:(0,K.jsx)(`section`,{className:`code-side-view-panel ${e===`search`?`code-search-view`:``} ${e===`history`?`code-history-view`:``} ${e===`plugins`?`code-plugins-view`:``}`,"data-testid":`code-side-view-panel`,children:e===`search`?(0,K.jsx)(qM,{query:b,displayedProjects:y,hasQuery:x,loading:S,resultCount:C,selectedAgentId:w,selectedSessionHandle:T,inputRef:E,onQueryChange:me,onKeyDown:he,onClearSearch:ge,onBack:ge,onOpenAgent:fe,onOpenSession:pe,copy:ze}):e===`history`?(0,K.jsx)(PM,{archivedRuns:D,archivedAgents:O,agentSessions:k,loading:A,error:j,providerSessionTotal:M,now:P,onResumeSession:ye,onContinueRun:be,onOpenArchivedAgent:xe,onRestoreArchivedAgent:Se,searchAgentSessions:ve,canLoadMoreAgentSessions:N,onLoadMoreAgentSessions:_e,onBack:H,copy:ze}):e===`plugins`?(0,K.jsx)(mN,{capability:n.capability,loading:n.loading,capabilityError:n.capabilityError,computerCapability:o.capability,computerLoading:o.loading,computerCapabilityError:o.capabilityError,onPrepareComputer:o.prepare,language:c,onBack:H,onOpenAgentHomeConfiguration:R,onRefreshCapability:gt}):(0,K.jsx)(`h2`,{children:jN(ze,e)})}),(0,K.jsx)(`div`,{className:`code-terminal-grid panes-1`,"data-testid":`code-terminal-grid`,hidden:!st,children:f===0?(0,K.jsxs)(`div`,{className:`code-empty-workspace code-empty-home-state`,"data-testid":`code-empty-workspace`,children:[(0,K.jsx)(NN,{agentCreationWorkspace:v,onNewAgent:I,onOpenHistory:L,onOpenPlugins:te,onOpenSearch:ne,onOpenShare:re,onOpenAppMode:z,copy:ze}),(0,K.jsxs)(`div`,{className:`code-empty-workspace-compact`,children:[(0,K.jsx)(`h2`,{children:ze.startOrSelectAgent}),(0,K.jsx)(`p`,{children:ze.startOrSelectAgentDescription}),(0,K.jsxs)(`div`,{className:`code-empty-workspace-compact-actions`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-empty-home-card compact-primary`,"data-testid":`code-empty-compact-history`,onClick:L,children:[(0,K.jsx)(`span`,{className:`code-empty-home-card-icon`,children:(0,K.jsx)(Ie,{})}),(0,K.jsxs)(`span`,{className:`code-empty-home-card-copy`,children:[(0,K.jsx)(`strong`,{children:ze.emptyWorkspaceContinue}),(0,K.jsx)(`span`,{children:ze.history})]})]}),(0,K.jsxs)(`button`,{type:`button`,className:`code-empty-home-card compact-primary`,"data-testid":`code-empty-compact-new-agent`,onClick:()=>I(v),children:[(0,K.jsx)(`span`,{className:`code-empty-home-card-icon`,children:(0,K.jsx)(Ee,{})}),(0,K.jsxs)(`span`,{className:`code-empty-home-card-copy`,children:[(0,K.jsx)(`strong`,{children:ze.newAgent}),(0,K.jsx)(`span`,{children:ze.emptyWorkspaceNewAgentDescription})]})]}),(0,K.jsxs)(`button`,{type:`button`,className:`code-empty-home-card compact-primary`,"data-testid":`code-empty-compact-plugins`,onClick:te,children:[(0,K.jsx)(`span`,{className:`code-empty-home-card-icon`,children:(0,K.jsx)(ht,{})}),(0,K.jsxs)(`span`,{className:`code-empty-home-card-copy`,children:[(0,K.jsx)(`strong`,{children:ze.plugins}),(0,K.jsx)(`span`,{children:ze.emptyWorkspacePluginsDescription})]})]})]})]})]}):p.map(e=>(0,K.jsx)(hA,{agent:e,active:st&&e.id===m,viewportLayoutKey:mt?`composer-collapsed`:`composer-expanded`,switching:e.id===h,switchingKind:e.id===h?g:null,onActivate:ie,onOpenPath:B,onResolvePath:oe,onSearchTerminalWord:V,onOpenWorkspaceFilePath:Te,onOpenUrlInFarming:De,onFollowOutputChange:se,onReadLatest:ce,onRuntimeModeChange:le,onForkAgent:ue,onSessionOutput:de,focusSignal:_?.agentId===e.id?_.nonce:0,copy:ze},e.id))}),st&&lt&&ut!==Je?(0,K.jsx)(NT,{resource:lt,language:c,onOpen:()=>i(lt),onDismiss:()=>Ye(ut)}):null,st?mt?(0,K.jsx)(`div`,{className:`code-composer-restore-bar`,"data-testid":`code-composer-restore-bar`,children:(0,K.jsx)(`button`,{type:`button`,className:`code-composer-restore`,"data-testid":`code-composer-restore`,"aria-label":ze.restoreComposer,title:ze.restoreComposer,onClick:()=>_t(!1),children:(0,K.jsx)(qe,{})})}):(0,K.jsxs)(`div`,{className:`code-composer-shell ${pt?`collapsible`:``}`,children:[pt?(0,K.jsx)(`div`,{className:`code-composer-collapse-zone`,"aria-hidden":`false`,children:(0,K.jsx)(`button`,{type:`button`,className:`code-composer-collapse`,"data-testid":`code-composer-collapse`,"aria-label":ze.collapseComposer,title:ze.collapseComposer,onClick:()=>_t(!0),children:(0,K.jsx)(Ge,{})})}):null,ct?(0,K.jsx)(qj,{...ee,copy:ze}):(0,K.jsx)(mj,{...F,copy:ze})]}):null]})}function FN(){return{entries:[],cursor:null}}function IN(e,t,n=100){let r=t.trimEnd();if(!r)return{...e,cursor:null};let i=Math.max(1,n);return{entries:e.entries[e.entries.length-1]===r?e.entries:[...e.entries,r].slice(-i),cursor:null}}function LN(e){let t=e.value||``,n=Math.max(0,Math.min(e.selectionStart,t.length));return n===Math.max(0,Math.min(e.selectionEnd,t.length))?e.direction===`previous`?t.lastIndexOf(`
206
+ `,Math.max(0,n-1))===-1:t.indexOf(`
207
+ `,n)===-1:!1}function RN(e,t,n){if(e.entries.length===0)return{history:{...e,cursor:null},value:n,changed:!1};let r=e.cursor,i=r!==null&&e.entries[r]===n;if(!i&&!(r===null&&n===``))return{history:{...e,cursor:null},value:n,changed:!1};if(t===`previous`){let t=i?Math.max(0,r):e.entries.length-1,a=i?Math.max(0,t-1):t,o=e.entries[a]||``;return{history:{...e,cursor:a},value:o,changed:o!==n||e.cursor!==a}}if(!i||r===null)return{history:{...e,cursor:null},value:n,changed:!1};let a=r+1;if(a>=e.entries.length)return{history:{...e,cursor:null},value:``,changed:n!==``||e.cursor!==null};let o=e.entries[a]||``;return{history:{...e,cursor:a},value:o,changed:o!==n||e.cursor!==a}}var zN={plusMenuOpen:!1,approvalMenuOpen:!1,modelMenuOpen:!1,modelPickerPane:null},BN=VN();function VN(){return{draft:``,attachments:[],mode:`default`,history:FN(),ui:{...zN}}}function HN(e,t=[],n=e,r=`default`){return{id:`pending-${typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}`,text:e,createdAt:Date.now(),...t.length>0?{attachments:t}:{},...n===e?{}:{editableText:n},...r===`default`?{}:{composerMode:r}}}function UN(e,t){let n=e.pendingFollowUp?.messages.find(e=>e.id===t);if(!n)return e;let r=n.editableText??n.text,i=r?e.draft.trim()?e.draft===r||e.draft.startsWith(`${r}\n`)?e.draft:`${r}\n${e.draft}`:r:e.draft,a=(n.attachments||[]).map((e,t)=>({...e,id:`restored-${n.id}-${t}`,status:`ready`}));return{...e,draft:i,attachments:[...e.attachments,...a],mode:e.draft.trim()?e.mode:n.composerMode??`default`,history:{...e.history,cursor:null},pendingFollowUp:WN(e.pendingFollowUp,t)}}function WN(e,t){if(!e)return;let n=e.messages.filter(e=>e.id!==t);return n.length>0?{...e,messages:n}:void 0}function GN(e,t){if(!e)return;let n=e.filter(e=>e.id!==t);return n.length>0?n:void 0}function KN(e){return!e.ui.plusMenuOpen&&!e.ui.approvalMenuOpen&&!e.ui.modelMenuOpen&&e.ui.modelPickerPane===null?e:{...e,ui:{...zN}}}function qN(e){return!e.plusMenuOpen&&!e.approvalMenuOpen&&!e.modelMenuOpen&&e.modelPickerPane===null}function JN(e,t){let n=new Map;for(let e of t.pendingFollowUp?.messages||[])n.set(e.id,e);for(let t of e.pendingFollowUp?.messages||[])n.set(t.id,t);let r=Array.from(n.values()).sort((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id)),i=Math.min(e.pendingFollowUp?.createdAt??1/0,t.pendingFollowUp?.createdAt??1/0),a=new Map;for(let n of[...t.submissions||[],...e.submissions||[]])a.set(n.id,n);let o=Array.from(a.values()).sort((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id));return{...e,draft:e.draft||t.draft,attachments:[...t.attachments,...e.attachments],mode:e.mode===`default`?t.mode:e.mode,history:{entries:[...t.history.entries,...e.history.entries].slice(-100),cursor:null},pendingFollowUp:r.length>0?{messages:r,createdAt:Number.isFinite(i)?i:Date.now()}:void 0,submissions:o.length>0?o:void 0,ui:qN(e.ui)?t.ui:e.ui}}function YN(e){return!e||e.providerSessionTemporary===!0?``:e.providerSessionKey?e.providerSessionKey:e.providerSessionProvider&&e.providerSessionId?OA({provider:e.providerSessionProvider,id:e.providerSessionId,providerHomeId:e.providerHomeId}):iM(e.source)}function XN(e){return e?YN(e)||e.restartedFromAgentIds?.[0]||e.id:``}function ZN(e){let t=new Set;e.id&&t.add(e.id),e.restartedFromAgentIds?.forEach(e=>t.add(e)),e.providerSessionKey&&t.add(e.providerSessionKey),e.providerSessionProvider&&e.providerSessionId&&t.add(OA({provider:e.providerSessionProvider,id:e.providerSessionId,providerHomeId:e.providerHomeId}));let n=iM(e.source);return n&&t.add(n),Array.from(t)}var QN=5e4,$N={goal:`Goal mode: Treat the following as the working goal for this agent. Track progress toward it and report clearly when it is complete or blocked.`,plan:`Plan mode: Inspect the relevant context first and respond with a concise plan before making code changes. Do not edit files until the plan is clear.`};function eP(e){return!e||e===`/`?``:e.endsWith(`/`)?e.slice(0,-1):e}function tP(e=`/`){let t=eP(`/farming/`),n=e.startsWith(`/`)?e:`/${e}`;return t?`${t}${n}`:n}function nP(e,t){let n=t.trimEnd();if(!n)return e;let r=e.trim()?`
208
+
209
+ `:``;return`${e.trimEnd()}${r}${n}`}function rP(e,t=`attachment`){return e.name||t}function iP(e){return typeof e.type==`string`&&e.type.startsWith(`image/`)}function aP(e){return typeof e.type==`string`&&e.type.startsWith(`audio/`)}function oP(e,t){let n=t.length>QN,r=n?t.slice(0,QN):t,i=n?`\n\n[File truncated after ${QN} characters]`:``;return`Attached file: ${rP(e)}\n\n${r}${i}`}function sP(e){return`Attached image: ${e.name}\n\nImage path: ${e.path}`}function cP(e){return`Attached audio: ${e.name}\n\nAudio path: ${e.path}`}function lP(e){let t=Math.random().toString(36).slice(2,8),n=aP(e)?`audio`:`image`;return`${n}-${Date.now()}-${rP(e,`pasted-${n}`)}-${t}`}function uP(e){if(!(typeof URL>`u`||typeof URL.createObjectURL!=`function`))return URL.createObjectURL(e)}function dP(e){!e.previewUrl||typeof URL>`u`||typeof URL.revokeObjectURL!=`function`||URL.revokeObjectURL(e.previewUrl)}function fP(e){return e.map(e=>e.messageBlock||``).filter(Boolean)}function pP(e,t){let n=fP(t);return nP(e.trimEnd(),n.join(`
210
+
211
+ `)).trimEnd()}function mP(e,t){let n=t.filter(e=>!e.path).map(e=>e.messageBlock||``).filter(Boolean);return nP(e.trimEnd(),n.join(`
212
+
213
+ `)).trimEnd()}function hP(e){return e.flatMap(e=>e.status===`ready`&&e.path?[{kind:e.kind,path:e.path,name:e.name,type:e.type,size:e.size}]:[])}function gP(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>n(r.error??Error(`File read failed`)),r.onload=()=>t(typeof r.result==`string`?r.result:``),r.readAsText(e)})}async function _P(e){let t=aP(e)?`/api/attachments/audio`:`/api/attachments/image`,n=await fetch(tP(t),{method:`POST`,headers:{"Content-Type":e.type||(aP(e)?`audio/wav`:`image/png`)},body:e});if(!n.ok)throw Error(`Image upload failed: ${n.status}`);return n.json()}async function vP(e){if(iP(e))return sP(await _P(e));if(aP(e))return cP(await _P(e));try{return oP(e,await gP(e))}catch{return`Attached file: ${rP(e)}\n\n[Unable to read this file as text]`}}function yP(e){return iP(e)?`Attached image: ${rP(e,`pasted image`)}\n\n[Unable to upload this image]`:aP(e)?`Attached audio: ${rP(e,`pasted audio`)}\n\n[Unable to upload this audio]`:`Attached file: ${rP(e)}\n\n[Unable to read this file as text]`}function bP(e){if(!e)return[];let t=Array.from(e.files??[]).filter(e=>iP(e)||aP(e));return t.length>0?t:Array.from(e.items??[]).filter(e=>e.kind===`file`&&/^(image|audio)\//.test(e.type)).map(e=>e.getAsFile()).filter(e=>!!(e&&(iP(e)||aP(e))))}function xP(e,t){return e===`default`?t:`${$N[e]}\n\n${t}`}function SP(e,t,n){if(e!==`goal`||n.runtimeBinding.kind!==`terminal`)return xP(e,t);let r=n.providerCapabilities.goalSubmission?.terminal;return r?.kind===`command`?`${r.prefix} ${t}`:xP(e,t)}function CP(e){return!!(e&&e.runtimeBinding.kind===`acp`&&e.status===`running`&&e.requiresProcessExitAcknowledgement!==!0)}function wP(e,t,n){return(t?e===`queue`?`steer`:`queue`:e)===`steer`&&n?`steer`:`queue`}function TP({agent:e,composerKey:t,draft:n,attachments:r,composerMode:i,turnActive:a,followUpBehavior:o=`queue`,sendMessage:s,updateComposerState:c}){let l=hP(r),u=xP(i,mP(n,r).trim());if(!u&&l.length===0||!e||!CP(e)||!t)return!1;let d=e=>e.draft===n&&e.attachments.length===r.length&&e.attachments.every((e,t)=>e.id===r[t]?.id)?{...e,draft:``,attachments:[],mode:e.mode===i?`default`:e.mode}:e,f=()=>(c(t,e=>{let t=d(e);return t===e?e:(r.forEach(dP),{...t,history:IN(t.history,n),pendingFollowUp:{messages:[...t.pendingFollowUp?.messages||[],HN(u,l,n,i)],createdAt:t.pendingFollowUp?.createdAt||Date.now()}})}),!0);if(a&&o===`queue`)return f();let p=e=>e?(c(t,e=>{let t=d(e);return t!==e&&r.forEach(dP),{...t,history:IN(t.history,n)}}),!0):!1,m;try{m=s(e,u,l,void 0,a?`steer`:`prompt`)}catch{return!1}return typeof m==`boolean`?p(m):m.then(p,()=>!1)}function EP(e,t,n,i=!1){return fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-permission`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t,optionId:n,cancelled:i})})}function DP(e,t,n,i){return fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-elicitation`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t,action:n,content:i})})}var OP=`acp:`;function kP(e){let t=XN(e);return t?`${OP}${t}`:``}function AP(e){return ZN(e).map(e=>`${OP}${e}`)}function jP(e){return e.startsWith(OP)}function MP(){return typeof window>`u`?!1:navigator.standalone===!0||window.matchMedia(`(display-mode: standalone)`).matches}function NP(){return(0,K.jsx)(`svg`,{viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M10 13V3m0 0L6.5 6.5M10 3l3.5 3.5M4 9v6.5A1.5 1.5 0 0 0 5.5 17h9a1.5 1.5 0 0 0 1.5-1.5V9`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function PP(){return(0,K.jsxs)(`svg`,{viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:[(0,K.jsx)(`rect`,{x:`3`,y:`3`,width:`14`,height:`14`,rx:`3`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`}),(0,K.jsx)(`path`,{d:`M10 6.5v7M6.5 10h7`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`})]})}function FP(){return(0,K.jsxs)(`svg`,{viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:[(0,K.jsx)(`rect`,{x:`6.5`,y:`6.5`,width:`9`,height:`9`,rx:`2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,K.jsx)(`path`,{d:`M13.5 6.5v-2A1.5 1.5 0 0 0 12 3H4.5A1.5 1.5 0 0 0 3 4.5V12A1.5 1.5 0 0 0 4.5 13.5h2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})]})}function IP({copy:e,title:t,url:n,onClose:r}){let i=MP(),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(!1);zn(r),(0,G.useEffect)(()=>{if(!a&&!s)return;let e=window.setTimeout(()=>{o(!1),c(!1)},1800);return()=>window.clearTimeout(e)},[a,s]);let l=(0,G.useCallback)(async()=>{let e=await Se(n);o(e),c(!e)},[n]);return(0,K.jsx)(`div`,{className:`code-mobile-share-backdrop`,"data-testid":`code-mobile-share-sheet`,role:`presentation`,onPointerDown:r,children:(0,K.jsxs)(`section`,{className:`code-mobile-share-sheet`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-mobile-share-title`,onPointerDown:e=>e.stopPropagation(),children:[(0,K.jsxs)(`header`,{className:`code-mobile-share-header`,children:[(0,K.jsx)(`h2`,{id:`code-mobile-share-title`,children:e.mobileShareTitle}),(0,K.jsx)(`button`,{type:`button`,"aria-label":e.cancel,onClick:r,children:`×`})]}),(0,K.jsxs)(`section`,{className:`code-mobile-share-choice code-mobile-share-forward`,children:[(0,K.jsxs)(`div`,{className:`code-mobile-share-choice-copy`,children:[(0,K.jsx)(`h3`,{children:e.mobileForwardTitle}),(0,K.jsx)(`p`,{children:e.mobileForwardHint})]}),(0,K.jsxs)(`div`,{className:`code-mobile-share-link-row`,children:[(0,K.jsx)(`span`,{className:`code-mobile-share-link`,title:t,children:n}),(0,K.jsxs)(`button`,{type:`button`,"data-testid":`code-mobile-share-copy-action`,onClick:()=>void l(),children:[(0,K.jsx)(FP,{}),(0,K.jsx)(`span`,{children:a?e.mobileShareCopied:e.mobileShareCopyAction})]})]}),s&&(0,K.jsx)(`span`,{className:`code-mobile-share-status`,role:`status`,children:e.copyFailed})]}),(0,K.jsxs)(`section`,{className:`code-mobile-share-choice code-mobile-share-install-guide`,children:[(0,K.jsx)(`h3`,{children:e.mobileInstallTitle}),i?(0,K.jsx)(`p`,{className:`code-mobile-install-complete`,children:e.mobileShareInstalled}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`p`,{className:`code-mobile-install-hint`,children:e.mobileInstallChromeHint}),(0,K.jsxs)(`div`,{className:`code-mobile-install-steps`,children:[(0,K.jsxs)(`div`,{className:`code-mobile-install-step`,children:[(0,K.jsxs)(`span`,{className:`code-mobile-install-controls`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{className:`code-mobile-install-control`,children:(0,K.jsx)(NP,{})}),(0,K.jsx)(`span`,{className:`code-mobile-install-or`,children:`/`}),(0,K.jsx)(`span`,{className:`code-mobile-install-control code-mobile-install-more`,children:`•••`})]}),(0,K.jsxs)(`span`,{children:[e.mobileInstallShareStep,(0,K.jsx)(`small`,{children:e.mobileInstallMoreStep})]})]}),(0,K.jsxs)(`div`,{className:`code-mobile-install-step`,children:[(0,K.jsx)(`span`,{className:`code-mobile-install-controls`,"aria-hidden":`true`,children:(0,K.jsx)(`span`,{className:`code-mobile-install-control`,children:(0,K.jsx)(PP,{})})}),(0,K.jsxs)(`span`,{children:[e.mobileInstallAddStep,(0,K.jsx)(`small`,{children:e.mobileInstallOpenStep})]})]})]})]})]})]})})}function LP(e){let t=e.filter(e=>!e.hidden),n=[];for(t.forEach(e=>{e.type===`separator`&&(n.length===0||n[n.length-1]?.type===`separator`)||n.push(e)});n[n.length-1]?.type===`separator`;)n.pop();return n}function RP({contextMenuAgent:e,contextMenuAgentSession:t,contextMenuProject:n,agentMenu:r,projectMenu:i,agentSessionMenu:a,renameDialog:o,killDialog:s,deleteWorktreeDialog:c,copyNotice:l,contextMenuRef:u,renameDialogRef:d,renameInputRef:f,killDialogRef:p,killCancelButtonRef:m,deleteWorktreeDialogRef:h,deleteWorktreeCancelButtonRef:g,onContextMenuKeyDown:_,runtimeSwitchDisabled:v,canCreateAgentBrowser:y,canCreateAgentDesktop:b,onSwitchAgentRuntime:x,onCreateAgentBrowser:S,onCreateAgentDesktop:C,onUpdateAgentFlags:w,onRenameAgent:T,onRenameProject:E,onCopyAgentWorkingDirectory:D,onForkAgent:O,onKillAgent:k,onOpenSession:A,onToggleSessionPinned:j,onArchiveSession:M,onCopySessionWorkingDirectory:N,onToggleProjectPinned:P,onRevealProject:F,onCreatePermanentWorktree:ee,onMarkProjectRead:I,onArchiveProject:L,onRemoveProject:te,onDeleteWorktree:R,onCloseRenameDialog:ne,onRenameDialogTitleChange:re,onSubmitRenameDialog:z,onCloseKillDialog:ie,onSubmitKillDialog:ae,onCloseDeleteWorktreeDialog:B,onSubmitDeleteWorktreeDialog:oe,copy:V}){let se=lA(e),ce=fA(n),le=pA(n),ue=!!n?.agents.some(e=>e.unread),de=e?.runtimeBinding.kind!==`terminal`,fe=LP([{type:`item`,id:`switch-agent-runtime`,label:de?V.switchToTerminal:V.switchToChat,trailingIcon:de?`terminal`:`chat`,hidden:!uA(e),disabled:v||tA(e),onSelect:()=>{e&&x(e.id,de?`terminal`:`chat`)}},{type:`separator`,id:`agent-runtime-separator`},{type:`item`,id:`create-agent-browser`,label:V.createBrowser,trailingIcon:`browser`,hidden:!y,onSelect:S},{type:`item`,id:`create-agent-desktop`,label:V.createIsolatedDesktop,trailingIcon:`desktop`,hidden:!b,onSelect:C},{type:`separator`,id:`agent-resource-separator`},{type:`item`,id:`pin-agent`,label:e?.pinned?V.unpinAgent:V.pinAgent,hidden:!se.actions.pin,onSelect:()=>w({pinned:!e?.pinned})},{type:`item`,id:`rename-agent`,label:V.renameAgent,hidden:!se.actions.rename,onSelect:T},{type:`item`,id:`archive-agent`,label:V.archiveAgent,hidden:!se.actions.archive,onSelect:()=>w({archived:!0})},{type:`item`,id:`toggle-agent-unread`,label:e?.unread?V.markAsRead:V.markAsUnread,hidden:!se.actions.markUnread,onSelect:()=>w({unread:!e?.unread})},{type:`separator`,id:`agent-copy-separator`},{type:`item`,id:`copy-agent-working-directory`,label:V.copyWorkingDirectory,hidden:!se.actions.copyWorkingDirectory,onSelect:D},{type:`separator`,id:`agent-fork-separator`},{type:`item`,id:`fork-same-worktree`,label:V.forkSameWorktree,hidden:!se.actions.forkSameWorktree,onSelect:()=>O(`same-worktree`)},{type:`item`,id:`fork-new-worktree`,label:V.forkNewWorktree,hidden:!se.actions.forkNewWorktree,onSelect:()=>O(`new-worktree`)},{type:`item`,id:`kill-agent`,label:V.killAgent,danger:!0,hidden:!se.actions.kill,onSelect:k}]),pe=LP([{type:`item`,id:`open-session`,label:V.openSession,onSelect:()=>{t&&A(t.provider,t.id)}},{type:`item`,id:`toggle-session-pinned`,label:t?.pinned?V.unpinChat:V.pinChat,onSelect:j},{type:`item`,id:`archive-session`,label:V.archiveChat,onSelect:M},{type:`item`,id:`copy-session-working-directory`,label:V.copyWorkingDirectory,onSelect:N}]),me=LP([{type:`item`,id:`pin-project`,label:n?.pinned?V.unpinProject:V.pinProject,icon:n?.pinned?`unpin`:`pin`,hidden:!n?.workspace,onSelect:P},{type:`item`,id:`reveal-project`,label:V.revealInFinder,icon:`folder`,hidden:!n?.workspace||n.workspace===`/`||n.hasMain,onSelect:F},{type:`item`,id:`create-permanent-worktree`,label:V.createPermanentWorktree,icon:`worktree`,hidden:!n?.workspace||n.workspace===`/`||n.hasMain,onSelect:ee},{type:`separator`,id:`project-primary-separator`},{type:`item`,id:`rename-project`,label:V.renameProject,icon:`rename`,hidden:!n?.workspace,onSelect:E},{type:`item`,id:`mark-project-read`,label:V.markAllAsRead,icon:`check`,disabled:!ue,onSelect:I},{type:`item`,id:`archive-project`,label:V.archiveChats,icon:`archive`,disabled:!ce,onSelect:L},{type:`separator`,id:`project-destructive-separator`},{type:`item`,id:`remove-project`,label:V.removeProject,removeIcon:!0,hidden:!n?.workspace||n.hasMain,disabled:!!(n&&(n.agents.length>0||n.agentSessions.length>0||n.hasOpenFile)),onSelect:te},{type:`item`,id:`delete-worktree`,label:V.deleteWorktree,icon:`trash`,danger:!0,hidden:!le,onSelect:R}]);return(0,K.jsxs)(K.Fragment,{children:[e&&(0,K.jsx)(`div`,{className:`code-context-menu`,"data-testid":`code-agent-context-menu`,style:{left:r?.x??0,top:r?.y??0},role:`menu`,ref:u,onKeyDownCapture:_,onKeyDown:_,children:(0,K.jsx)(zP,{entries:fe})}),t&&(0,K.jsx)(`div`,{className:`code-context-menu`,"data-testid":`code-session-context-menu`,style:{left:a?.x??0,top:a?.y??0},role:`menu`,ref:u,onKeyDownCapture:_,onKeyDown:_,children:(0,K.jsx)(zP,{entries:pe})}),n&&(0,K.jsx)(`div`,{className:`code-context-menu code-project-context-menu`,"data-testid":`code-project-context-menu`,style:{left:i?.x??0,top:i?.y??0},role:`menu`,ref:u,onKeyDownCapture:_,onKeyDown:_,children:(0,K.jsx)(zP,{entries:me})}),o&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-rename-backdrop`,onMouseDown:ne,children:(0,K.jsxs)(`form`,{className:`code-rename-dialog`,"data-testid":`code-rename-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-rename-title`,ref:d,onMouseDown:e=>e.stopPropagation(),onKeyDownCapture:e=>HP(e,d.current),onKeyDown:e=>HP(e,d.current),onSubmit:e=>{e.preventDefault(),z()},children:[(0,K.jsx)(`label`,{id:`code-rename-title`,htmlFor:`code-rename-input`,children:o.kind===`project`?V.renameProject:V.renameAgent}),(0,K.jsx)(`input`,{id:`code-rename-input`,ref:f,"data-testid":`code-rename-input`,type:`text`,name:`farming-rename-title`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:o.title,onChange:e=>re(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),ne())}}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:ne,children:V.cancel}),(0,K.jsx)(`button`,{type:`submit`,className:`primary`,disabled:!o.title.trim(),children:V.save})]})]})}),s&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-kill-backdrop`,onMouseDown:ie,children:(0,K.jsxs)(`div`,{className:`code-rename-dialog code-kill-dialog`,"data-testid":`code-kill-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-kill-title`,ref:p,onMouseDown:e=>e.stopPropagation(),onKeyDownCapture:e=>HP(e,p.current),onKeyDown:e=>HP(e,p.current),children:[(0,K.jsx)(`h2`,{id:`code-kill-title`,children:V.killAgentQuestion}),(0,K.jsx)(`p`,{children:s.acknowledgeUnprovenAcpExit?V.acknowledgeUnprovenAcpExitDescription(s.title):V.stopAgentDescription(s.title)}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,ref:m,onClick:ie,autoFocus:!0,children:V.cancel}),(0,K.jsx)(`button`,{type:`button`,className:`danger`,onClick:ae,children:s.acknowledgeUnprovenAcpExit?V.acknowledgeUnprovenAcpExit:V.killAgent})]})]})}),c&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-delete-worktree-backdrop`,onMouseDown:B,children:(0,K.jsxs)(`div`,{className:`code-rename-dialog code-kill-dialog`,"data-testid":`code-delete-worktree-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-delete-worktree-title`,ref:h,onMouseDown:e=>e.stopPropagation(),onKeyDownCapture:e=>HP(e,h.current),onKeyDown:e=>HP(e,h.current),children:[(0,K.jsx)(`h2`,{id:`code-delete-worktree-title`,children:V.deleteWorktreeQuestion}),(0,K.jsx)(`p`,{children:V.deleteWorktreeDescription}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,ref:g,onClick:B,autoFocus:!0,children:V.cancel}),(0,K.jsx)(`button`,{type:`button`,className:`danger`,onClick:oe,children:V.forceDelete})]})]})}),l&&(0,K.jsx)(`div`,{className:`code-copy-toast ${l.kind}`,"data-testid":`code-copy-toast`,role:`status`,children:l.message})]})}function zP({entries:e}){return(0,K.jsx)(K.Fragment,{children:e.map(e=>e.type===`separator`?(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`},e.id):(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,className:e.danger?`danger`:void 0,disabled:e.disabled,onClick:e.onSelect,children:[(e.icon||e.removeIcon)&&(0,K.jsx)(`span`,{className:`code-context-menu-icon`,"aria-hidden":`true`,children:e.removeIcon?(0,K.jsx)(BP,{}):(0,K.jsx)(VP,{kind:e.icon})}),(0,K.jsx)(`span`,{children:e.label}),e.trailingIcon&&(0,K.jsx)(`span`,{className:`code-context-menu-icon trailing`,"aria-hidden":`true`,children:(0,K.jsx)(VP,{kind:e.trailingIcon})})]},e.id))})}function BP(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M4.354 3.646a.5.5 0 0 0-.708.708L7.293 8l-3.647 3.646a.5.5 0 0 0 .708.708L8 8.707l3.646 3.647a.5.5 0 0 0 .708-.708L8.707 8l3.647-3.646a.5.5 0 0 0-.708-.708L8 7.293 4.354 3.646Z`})})}function VP({kind:e}){return e===`browser`?(0,K.jsx)(at,{}):e===`desktop`?(0,K.jsx)(ze,{}):e===`chat`?(0,K.jsx)(Qe,{}):e===`terminal`?(0,K.jsx)(ot,{}):e===`pin`?(0,K.jsx)(`svg`,{"data-icon-kind":`pin`,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M10.0589 2.44511C9.34701 1.73063 8.14697 1.90829 7.67261 2.79839L5.6526 6.58878L2.8419 7.52568C2.6775 7.58048 2.5532 7.71649 2.51339 7.88514C2.47357 8.0538 2.52392 8.23104 2.64646 8.35357L4.79291 10.5L2.14645 13.1465L2 14L2.85356 13.8536L5.50002 11.2071L7.64646 13.3536C7.76899 13.4761 7.94623 13.5265 8.11489 13.4866C8.28354 13.4468 8.41955 13.3225 8.47435 13.1581L9.41143 10.3469L13.1897 8.32423C14.0759 7.84982 14.2538 6.6551 13.5443 5.94305L10.0589 2.44511ZM8.55511 3.2687C8.71323 2.972 9.11324 2.91278 9.35055 3.15094L12.836 6.64889C13.0725 6.88624 13.0131 7.28448 12.7178 7.44262L8.76403 9.55921C8.65137 9.61952 8.56608 9.72068 8.52567 9.84191L7.7815 12.0744L3.92562 8.21853L6.15812 7.47436C6.27966 7.43385 6.38101 7.34823 6.44126 7.23518L8.55511 3.2687Z`})}):e===`unpin`?(0,K.jsx)(`svg`,{"data-icon-kind":`unpin`,width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M9.56016 10.2673L14.1464 14.8536C14.3417 15.0488 14.6583 15.0488 14.8536 14.8536C15.0488 14.6583 15.0488 14.3417 14.8536 14.1464L1.85355 1.14645C1.65829 0.951184 1.34171 0.951184 1.14645 1.14645C0.951184 1.34171 0.951184 1.65829 1.14645 1.85355L5.73223 6.43934L5.6526 6.58876L2.8419 7.52566C2.6775 7.58046 2.5532 7.71648 2.51339 7.88513C2.47357 8.05378 2.52392 8.23102 2.64646 8.35356L4.79291 10.5L2.14645 13.1465L2 14L2.85356 13.8536L5.50002 11.2071L7.64646 13.3536C7.76899 13.4761 7.94623 13.5264 8.11489 13.4866C8.28354 13.4468 8.41955 13.3225 8.47435 13.1581L9.41143 10.3469L9.56016 10.2673ZM8.82138 9.52849L8.76403 9.5592C8.65137 9.61951 8.56608 9.72066 8.52567 9.84189L7.7815 12.0744L3.92562 8.21851L6.15812 7.47435C6.27966 7.43383 6.38101 7.34822 6.44126 7.23516L6.47143 7.17854L8.82138 9.52849ZM12.7178 7.4426L10.6636 8.54227L11.4024 9.28105L13.1897 8.32422C14.0759 7.84981 14.2538 6.65509 13.5443 5.94304L10.0589 2.44509C9.34701 1.73062 8.14697 1.90828 7.67261 2.79838L6.71556 4.59421L7.45476 5.33341L8.55511 3.26869C8.71323 2.97199 9.11324 2.91277 9.35055 3.15093L12.836 6.64888C13.0725 6.88623 13.0131 7.28446 12.7178 7.4426Z`})}):e===`folder`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M2 4.5V9.10022L2.92389 7.5C3.45979 6.5718 4.45017 6 5.52196 6L11.9146 6C11.7087 5.4174 11.1531 5 10.5 5H7C6.86739 5 6.74021 4.94732 6.64645 4.85355L4.93934 3.14645C4.84557 3.05268 4.71839 3 4.58579 3H3.5C2.67157 3 2 3.67157 2 4.5ZM7.06895 13.9953C7.04641 13.9984 7.02339 14 7 14H3.5C2.11929 14 1 12.8807 1 11.5V4.5C1 3.11929 2.11929 2 3.5 2H4.58579C4.98361 2 5.36514 2.15804 5.64645 2.43934L7.20711 4H10.5C11.724 4 12.7426 4.87965 12.958 6.04127C14.605 6.34148 15.5443 8.22106 14.6616 9.75L13.0766 12.4953C12.5407 13.4235 11.5503 13.9953 10.4785 13.9953H7.06895ZM5.52196 7C4.80743 7 4.14718 7.3812 3.78991 8L2.20492 10.7453C1.62757 11.7453 2.34926 12.9953 3.50396 12.9953L10.4785 12.9953C11.193 12.9953 11.8533 12.6141 12.2105 11.9953L13.7955 9.25C14.3729 8.25 13.6512 7 12.4965 7L5.52196 7Z`})}):e===`worktree`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M14 5.5C14 4.121 12.879 3 11.5 3C10.121 3 9 4.121 9 5.5C9 6.682 9.826 7.669 10.93 7.928C10.744 8.546 10.177 9 9.5 9H6.5C5.935 9 5.419 9.195 5 9.512V4.949C6.14 4.717 7 3.707 7 2.5C7 1.121 5.879 0 4.5 0C3.121 0 2 1.121 2 2.5C2 3.708 2.86 4.717 4 4.949V11.05C2.86 11.282 2 12.292 2 13.499C2 14.878 3.121 15.999 4.5 15.999C5.879 15.999 7 14.878 7 13.499C7 12.317 6.174 11.33 5.07 11.071C5.256 10.453 5.823 9.999 6.5 9.999H9.5C10.723 9.999 11.74 9.115 11.954 7.953C13.116 7.738 14 6.723 14 5.5ZM3 2.5C3 1.673 3.673 1 4.5 1C5.327 1 6 1.673 6 2.5C6 3.327 5.327 4 4.5 4C3.673 4 3 3.327 3 2.5ZM6 13.5C6 14.327 5.327 15 4.5 15C3.673 15 3 14.327 3 13.5C3 12.673 3.673 12 4.5 12C5.327 12 6 12.673 6 13.5ZM11.5 7C10.673 7 10 6.327 10 5.5C10 4.673 10.673 4 11.5 4C12.327 4 13 4.673 13 5.5C13 6.327 12.327 7 11.5 7Z`})}):e===`check`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M13.6572 3.13573C13.8583 2.9465 14.175 2.95614 14.3643 3.15722C14.5535 3.35831 14.5438 3.675 14.3428 3.86425L5.84277 11.8642C5.64597 12.0494 5.33756 12.0446 5.14648 11.8535L1.64648 8.35351C1.45121 8.15824 1.45121 7.84174 1.64648 7.64647C1.84174 7.45121 2.15825 7.45121 2.35351 7.64647L5.50976 10.8027L13.6572 3.13573Z`})}):e===`archive`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M6.5 8C6.22386 8 6 8.22386 6 8.5C6 8.77614 6.22386 9 6.5 9H9.5C9.77614 9 10 8.77614 10 8.5C10 8.22386 9.77614 8 9.5 8H6.5ZM1 3.5C1 2.67157 1.67157 2 2.5 2H13.5C14.3284 2 15 2.67157 15 3.5V4.5C15 5.15311 14.5826 5.70873 14 5.91465V11.5C14 12.8807 12.8807 14 11.5 14H4.5C3.11929 14 2 12.8807 2 11.5V5.91465C1.4174 5.70873 1 5.15311 1 4.5V3.5ZM2.5 3C2.22386 3 2 3.22386 2 3.5V4.5C2 4.77614 2.22386 5 2.5 5H13.5C13.7761 5 14 4.77614 14 4.5V3.5C14 3.22386 13.7761 3 13.5 3H2.5ZM3 6V11.5C3 12.3284 3.67157 13 4.5 13H11.5C12.3284 13 13 12.3284 13 11.5V6H3Z`})}):e===`trash`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M6.25 2h3.5l.5 1H13v1H3V3h2.75l.5-1ZM4.2 5h7.6l-.48 8.1A1 1 0 0 1 10.32 14H5.68a1 1 0 0 1-1-.9L4.2 5Zm2.05 1 .35 7h.95L7.2 6h-.95Zm2.2 0v7h.95V6h-.95Z`})}):(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M11.3536 1.64645C10.963 1.25592 10.3299 1.25592 9.93934 1.64645L3.14645 8.43934C3.05268 8.53311 2.99999 8.66029 2.99999 8.79289V11.5C2.99999 11.7761 3.22385 12 3.49999 12H6.2071C6.33971 12 6.46689 11.9473 6.56066 11.8536L13.3536 5.06066C13.7441 4.67014 13.7441 4.037 13.3536 3.64645L11.3536 1.64645ZM3.99999 9L8.99999 4L11 6L6 11H3.99999V9ZM9.7071 3.29289L10.6464 2.35355L12.6464 4.35355L11.7071 5.29289L9.7071 3.29289ZM2.5 14C2.22386 14 2 14.2239 2 14.5C2 14.7761 2.22386 15 2.5 15H13.5C13.7761 15 14 14.7761 14 14.5C14 14.2239 13.7761 14 13.5 14H2.5Z`})})}function HP(e,t){if(e.key!==`Tab`||!t)return;let n=Array.from(t.querySelectorAll(`button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [href], [tabindex]:not([tabindex="-1"])`)).filter(e=>e.offsetParent!==null);if(n.length===0){e.preventDefault();return}let r=n[0],i=n[n.length-1];!r||!i||(e.shiftKey&&document.activeElement===r?(e.preventDefault(),i.focus()):!e.shiftKey&&document.activeElement===i&&(e.preventDefault(),r.focus()))}function UP({canInstall:e,canFullscreen:t,fullscreenActive:n,installUnavailableReason:i,copy:a,onClose:o,onInstall:s,onToggleFullscreen:c}){let l=(0,G.useRef)(null);return zn(o),(0,G.useEffect)(()=>{let e=document.activeElement instanceof HTMLElement?document.activeElement:null;return l.current?.focus({preventScroll:!0}),()=>{e?.focus({preventScroll:!0})}},[o]),(0,nE.createPortal)((0,K.jsx)(`div`,{className:`code-app-mode-backdrop`,"data-testid":`code-app-mode-dialog`,role:`presentation`,onPointerDown:o,children:(0,K.jsxs)(`section`,{className:`code-app-mode-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-app-mode-title`,onPointerDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`button`,{ref:l,type:`button`,className:`code-app-mode-close`,"aria-label":a.cancel,onClick:o,children:`×`}),(0,K.jsxs)(`header`,{className:`code-app-mode-heading`,children:[(0,K.jsx)(`img`,{src:r(`/farming-2/app-icon-v2-180.png`),alt:``,"aria-hidden":`true`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h2`,{id:`code-app-mode-title`,children:a.appModeTitle}),(0,K.jsx)(`p`,{children:a.appModeDescription})]})]}),e?(0,K.jsxs)(`section`,{className:`code-app-mode-choice recommended`,children:[(0,K.jsx)(`span`,{className:`code-app-mode-recommended`,children:a.appModeRecommended}),(0,K.jsx)(`h3`,{children:a.appModeInstallTitle}),(0,K.jsx)(`p`,{children:a.appModeInstallDescription}),(0,K.jsx)(`button`,{type:`button`,className:`code-app-mode-install`,"data-testid":`code-app-mode-install`,onClick:s,children:a.appModeInstallAction}),(0,K.jsxs)(`ol`,{className:`code-app-mode-install-steps`,children:[(0,K.jsx)(`li`,{children:a.appModeInstallStepOne}),(0,K.jsx)(`li`,{children:a.appModeInstallStepTwo})]})]}):(0,K.jsxs)(`section`,{className:`code-app-mode-choice unavailable`,"data-testid":`code-app-mode-install-unavailable`,children:[(0,K.jsx)(`h3`,{children:a.appModeInstallUnavailableTitle}),(0,K.jsx)(`p`,{children:i})]}),t&&(0,K.jsxs)(`section`,{className:`code-app-mode-choice temporary`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:a.appModeFullscreenTitle}),(0,K.jsx)(`p`,{children:a.appModeFullscreenDescription})]}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-app-mode-fullscreen`,onClick:c,children:n?a.exitFocusMode:a.enterFocusMode})]})]})}),document.body)}var WP=`https://github.com/zhuwenzhuang/farming`;function GP({copy:e,version:t,onClose:n,returnFocusRef:i}){let a=(0,G.useRef)(null);return zn(n),(0,G.useEffect)(()=>(a.current?.focus({preventScroll:!0}),()=>{i.current?.focus({preventScroll:!0})}),[n,i]),(0,nE.createPortal)((0,K.jsx)(`div`,{className:`code-brand-backdrop`,"data-testid":`code-brand-dialog`,role:`presentation`,onPointerDown:n,children:(0,K.jsxs)(`section`,{className:`code-brand-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-brand-title`,onPointerDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`button`,{ref:a,type:`button`,className:`code-brand-close`,"aria-label":e.cancel,onClick:n,children:`×`}),(0,K.jsx)(`img`,{className:`code-brand-logo`,src:r(`/farming-2/app-icon-v2-180.png`),alt:``,"aria-hidden":`true`}),(0,K.jsxs)(`div`,{className:`code-brand-heading`,children:[(0,K.jsx)(`h2`,{id:`code-brand-title`,children:`Farming Code`}),t&&(0,K.jsx)(`span`,{children:t})]}),(0,K.jsxs)(`div`,{className:`code-brand-story`,children:[(0,K.jsx)(`p`,{children:e.brandStoryOrigin}),(0,K.jsx)(`p`,{children:e.brandStoryPurpose})]}),(0,K.jsx)(`a`,{className:`code-brand-github`,href:WP,target:`_blank`,rel:`noreferrer`,children:e.brandGithub})]})}),document.body)}var KP=80;function qP({copy:e,instanceName:t,onClose:n,onSave:r,returnFocusRef:i}){let[a,o]=(0,G.useState)(t),[s,c]=(0,G.useState)(!1),[l,u]=(0,G.useState)(!1),d=(0,G.useRef)(null);return zn(n,!s),(0,G.useEffect)(()=>(d.current?.focus({preventScroll:!0}),d.current?.select(),()=>{i.current?.focus({preventScroll:!0})}),[n,i]),(0,nE.createPortal)((0,K.jsx)(`div`,{className:`code-brand-backdrop`,"data-testid":`code-instance-name-dialog`,role:`presentation`,onPointerDown:()=>!s&&n(),children:(0,K.jsxs)(`form`,{className:`code-brand-dialog code-instance-name-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-instance-name-title`,onPointerDown:e=>e.stopPropagation(),onSubmit:async e=>{if(e.preventDefault(),!s){if(c(!0),u(!1),await r(a)){n();return}c(!1),u(!0)}},children:[(0,K.jsx)(`h2`,{id:`code-instance-name-title`,children:e.instanceNameTitle}),(0,K.jsx)(`p`,{children:e.instanceNameDescription}),(0,K.jsx)(`input`,{ref:d,value:a,maxLength:KP,placeholder:e.instanceNamePlaceholder,"aria-label":e.instanceNameTitle,onChange:e=>o(e.target.value)}),l&&(0,K.jsx)(`p`,{className:`code-instance-name-error`,role:`alert`,children:e.instanceNameSaveFailed}),(0,K.jsxs)(`div`,{className:`code-instance-name-actions`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:n,disabled:s,children:e.cancel}),(0,K.jsx)(`button`,{type:`submit`,className:`primary`,disabled:s,children:e.save})]})]})}),document.body)}var JP=8,YP=26,XP=11,ZP=10;function QP(){return typeof window>`u`?{width:220+JP*2,height:ZP+JP*2}:{width:window.innerWidth,height:window.innerHeight}}function $P(e,t=0){return ZP+e*YP+t*XP}function eF(e,t,n,r=QP(),i=220){let a=Math.max(JP,r.width-i-JP),o=Math.max(JP,r.height-n-JP);return{x:Math.max(JP,Math.min(e,a)),y:Math.max(JP,Math.min(t,o))}}function tF(e,t,n=QP(),r=220){let i=e.right+JP,a=e.left-r-JP,o=i+r<=n.width-JP?i:a>=JP?a:eF(i,e.top,t,n,r).x;return{x:o,y:eF(o,e.top,t,n,r).y}}function nF(e,t,n=QP(),r=220){let i=Math.max(JP,n.width-r-JP),a=Math.max(JP,Math.min(e.right-r,i)),o=e.bottom+6,s=Math.max(JP,n.height-t-JP),c=e.top-t-6;return{x:a,y:o<=s?o:Math.max(JP,Math.min(c,s))}}function rF(e){let t=mA(e);return $P(t.itemCount,t.separatorCount)}var iF=140,aF=264,oF=340,sF=4,cF=null;function lF(e){if(typeof e==`function`)return e;if(typeof e.default==`function`)return e.default;if(typeof e.qrcode==`function`)return e.qrcode;throw Error(`QR renderer failed to load`)}function uF(){return cF||=s(()=>import(`./qrcode-DJDTdjL7.js`).then(e=>lF(e)),[]),cF}function dF(e){let t=Math.max(0,Math.ceil(e/1e3)),n=Math.floor(t/60),r=t%60;return`${n}:${String(r).padStart(2,`0`)}`}function fF(e,t){return!!(e&&e.expiresAt>t+1e3)}function pF(e){return e.split(`-`).map(e=>e.trim()).filter(Boolean)}async function mF(e){e?.code&&await fetch(r(`/api/share/qr-ticket/${encodeURIComponent(e.code)}`),{method:`DELETE`}).catch(()=>{})}function hF(e,t,n){let r=e<7,i=t<7,a=t>=n-7,o=e>=n-7;return r&&i||r&&a||o&&i}function gF(e,t,n,r){let i=Math.floor((n-r)/2),a=i+r;return e>=i&&e<a&&t>=i&&t<a}function _F(e,t){return(e+t)%11==0?`#6d8a63`:(e*3+t)%17==0?`#9b7a35`:`#263327`}function vF(e,t,n){return(0,K.jsxs)(`g`,{children:[(0,K.jsx)(`rect`,{x:e,y:t,width:`7`,height:`7`,rx:`1.45`,fill:`#263327`}),(0,K.jsx)(`rect`,{x:e+1,y:t+1,width:`5`,height:`5`,rx:`1`,fill:`#fbfaf2`}),(0,K.jsx)(`rect`,{x:e+2,y:t+2,width:`3`,height:`3`,rx:`0.72`,fill:`#263327`}),(0,K.jsx)(`rect`,{x:e+3.05,y:t+3.05,width:`0.9`,height:`0.9`,rx:`0.32`,fill:`#d9a735`})]},n)}function yF({value:e,badgeUrl:t,qrCodeFactory:n}){let r=(0,G.useId)().replace(/:/g,``),i=(0,G.useMemo)(()=>{let t=n(0,`H`);return t.addData(e),t.make(),t},[n,e]),a=i.getModuleCount(),o=a+sF*2,s=Math.max(7,Math.min(11,Math.floor(a*.26)|1)),c=s+1.4,l=sF+(a-c)/2,u=sF+(a-c)/2,d=`farming-qr-badge-${r}`,f=[];for(let e=0;e<a;e+=1)for(let t=0;t<a;t+=1)i.isDark(e,t)&&(hF(e,t,a)||gF(e,t,a,s)||f.push((0,K.jsx)(`rect`,{x:sF+t+.14,y:sF+e+.14,width:`0.72`,height:`0.72`,rx:`0.24`,fill:_F(e,t)},`${e}-${t}`)));return(0,K.jsxs)(`svg`,{className:`code-share-qr-svg`,viewBox:`0 0 ${o} ${o}`,role:`img`,"aria-label":`QR code`,shapeRendering:`geometricPrecision`,children:[(0,K.jsx)(`defs`,{children:(0,K.jsx)(`clipPath`,{id:d,children:(0,K.jsx)(`rect`,{x:l+.55,y:u+.55,width:c-1.1,height:c-1.1,rx:`2.1`})})}),(0,K.jsx)(`rect`,{x:`0`,y:`0`,width:o,height:o,rx:`4`,fill:`#fbfaf2`}),f,vF(sF,sF,`top-left`),vF(sF+a-7,sF,`top-right`),vF(sF,sF+a-7,`bottom-left`),(0,K.jsx)(`rect`,{x:l,y:u,width:c,height:c,rx:`2.6`,fill:`#fbfaf2`}),(0,K.jsx)(`rect`,{x:l+.35,y:u+.35,width:c-.7,height:c-.7,rx:`2.25`,fill:`#ffffff`}),(0,K.jsx)(`image`,{href:t,x:l+.55,y:u+.55,width:c-1.1,height:c-1.1,preserveAspectRatio:`xMidYMid slice`,clipPath:`url(#${d})`})]})}function bF({copy:e,sidebarCollapsed:t,shareTarget:n,openRequest:i=0}){let[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(!1),[l,u]=(0,G.useState)(null),[d,f]=(0,G.useState)(!1),[p,m]=(0,G.useState)(``),[h,g]=(0,G.useState)(!1),[_,v]=(0,G.useState)(()=>Date.now()),[y,b]=(0,G.useState)({x:0,y:0}),x=(0,G.useRef)(null),S=(0,G.useRef)(null),C=(0,G.useRef)(null),T=(0,G.useRef)(null),E=(0,G.useRef)(null),O=(0,G.useRef)(0),k=(0,G.useRef)(null),A=(0,G.useRef)(null),j=(0,G.useRef)(0),[M,N]=(0,G.useState)(!0),[P,F]=(0,G.useState)(null),ee=r(`/farming-2/app-icon-v2-180.png`),I=D(n);(0,G.useEffect)(()=>{k.current=l},[l]);let L=(0,G.useCallback)(()=>{E.current!==null&&(window.clearTimeout(E.current),E.current=null)},[]),te=(0,G.useCallback)(()=>{let e=S.current?.getBoundingClientRect();if(!e)return;let t=e.right+8,n=e.left-aF-8;b({x:t+aF+10<=window.innerWidth?t:Math.max(8,n),y:Math.max(8,Math.min(e.top-4,window.innerHeight-oF-8))})},[]),R=(0,G.useCallback)(()=>{t||uF().then(e=>F(()=>e)).catch(()=>m(e.shareLinkFailed))},[e.shareLinkFailed,t]),ne=(0,G.useCallback)(async(t=!1)=>{let i=k.current;if(!t&&fF(i,Date.now()))return i;let a=O.current+1;O.current=a,f(!0),m(``);try{let t=w(n),i=await fetch(r(`/api/share/qr-ticket`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t?{target:t}:{})}),o=await i.json();if(!i.ok||!(`shortUrl`in o))throw Error(`error`in o&&o.error?o.error:e.shareLinkFailed);return a===O.current?(u(o),v(Date.now()),g(!1),o):(await mF(o),null)}catch(t){return a===O.current&&m(t instanceof Error?t.message:e.shareLinkFailed),null}finally{a===O.current&&f(!1)}},[e.shareLinkFailed,n,I]),re=(0,G.useCallback)(()=>{L(),O.current+=1,o(!1),c(!1),m(``),g(!1),f(!1);let e=k.current;k.current=null,u(null),mF(e)},[L]),z=(0,G.useCallback)((e,t=!1)=>{L(),te(),o(!0),c(e),R(),ne(t)},[L,ne,R,te]);(0,G.useEffect)(()=>{!i||j.current===i||(j.current=i,z(!0,!0))},[z,i]);let ie=(0,G.useCallback)(()=>{!a||s||(L(),E.current=window.setTimeout(()=>{E.current=null,re()},iF))},[L,re,a,s]),ae=(0,G.useCallback)(()=>{if(a&&s){re();return}z(!0,!0)},[re,a,z,s]),B=(0,G.useCallback)(async()=>{let t=fF(k.current,Date.now())?k.current:await ne(!0);if(t){if(!await Se(t.longUrl)){m(e.copyFailed);return}g(!0),A.current!==null&&window.clearTimeout(A.current),A.current=window.setTimeout(()=>{g(!1),A.current=null},1800)}},[e.copyFailed,ne]);(0,G.useLayoutEffect)(()=>{if(a)return te(),window.addEventListener(`resize`,te),()=>window.removeEventListener(`resize`,te)},[a,te]),(0,G.useEffect)(()=>{if(!a)return;let e=window.setInterval(()=>v(Date.now()),1e3);return()=>window.clearInterval(e)},[a]),(0,G.useEffect)(()=>{let e=k.current;e&&(k.current=null,u(null),g(!1),mF(e))},[I]),(0,G.useLayoutEffect)(()=>{if(!a)return;let e=()=>{let e=C.current,t=T.current;!e||!t||N(t.scrollWidth<=e.clientWidth+1)};e();let t=typeof ResizeObserver<`u`?new ResizeObserver(e):null;return t&&C.current&&t.observe(C.current),window.addEventListener(`resize`,e),()=>{t?.disconnect(),window.removeEventListener(`resize`,e)}},[a,l?.tokenLabel,l?.shortPath]),(0,G.useEffect)(()=>{if(!a)return;let e=e=>{let t=e.target;t instanceof Node&&x.current?.contains(t)||re()},t=e=>{e.key===`Escape`&&re()};return document.addEventListener(`pointerdown`,e,!0),document.addEventListener(`keydown`,t,!0),()=>{document.removeEventListener(`pointerdown`,e,!0),document.removeEventListener(`keydown`,t,!0)}},[re,a]),(0,G.useEffect)(()=>()=>{L(),A.current!==null&&window.clearTimeout(A.current),O.current+=1,mF(k.current)},[L]);let oe=!!(l&&l.expiresAt<=_),V=l?dF(l.expiresAt-_):``,se=l?.tokenLabel||l?.shortPath||e.copyFullShareLink,ce=pF(se),le=M||ce.length<=1?[se]:ce;return(0,K.jsxs)(`div`,{ref:x,className:`code-share-root`,onMouseEnter:R,onMouseLeave:ie,onFocus:()=>{L(),R()},onBlur:e=>{!e.currentTarget.contains(e.relatedTarget)&&!s&&re()},children:[(0,K.jsx)(`button`,{ref:S,type:`button`,className:`code-share-button`,"data-testid":`code-share-button`,"aria-label":e.sharePage,title:e.sharePage,"aria-haspopup":`dialog`,"aria-expanded":a,onClick:ae,children:(0,K.jsx)(He,{className:`code-share-icon`})}),a&&(0,K.jsxs)(`div`,{className:`code-share-popover`,"data-testid":`code-share-popover`,role:`dialog`,"aria-label":e.scanToOpenOnPhone,style:{left:y.x,top:y.y},onMouseEnter:()=>{L()},onMouseLeave:ie,onKeyDown:e=>{e.key===`Escape`&&(re(),S.current?.focus())},children:[(0,K.jsxs)(`div`,{className:`code-share-qr-frame`,"data-expired":oe?`true`:`false`,children:[(0,K.jsx)(`div`,{className:`code-share-qr-canvas`,children:l&&!d&&P?(0,K.jsx)(yF,{value:l.shortUrl,badgeUrl:ee,qrCodeFactory:P}):(0,K.jsx)(`div`,{className:`code-share-qr-loading`,children:d?e.loading:e.shareLinkFailed})}),l&&(0,K.jsx)(`div`,{className:`code-share-countdown`,children:oe?e.shareLinkExpired:V}),oe&&(0,K.jsx)(`button`,{type:`button`,className:`code-share-refresh`,onClick:()=>void ne(!0),children:e.refreshShareLink})]}),(0,K.jsxs)(`button`,{type:`button`,className:`code-share-copy-token`,"data-testid":`code-share-copy-link`,disabled:!l&&d,onClick:()=>void B(),children:[(0,K.jsxs)(`span`,{ref:C,className:`code-share-token ${M?`single-line`:``}`,"aria-label":se,children:[(0,K.jsx)(`span`,{ref:T,className:`code-share-token-measure`,"aria-hidden":`true`,children:se}),le.map((e,t)=>(0,K.jsx)(`span`,{className:`code-share-token-line`,children:e},`${t}-${e}`))]}),(0,K.jsx)(`span`,{className:`code-share-copy-action`,children:h?e.copiedShareLink:e.copyFullShareLink})]}),p&&(0,K.jsx)(`div`,{className:`code-share-error`,role:`status`,children:p})]})]})}function xF(e,t){return e&&t.some(t=>!t.isMain&&t.id===e)?e:t.find(e=>!e.isMain)?.id??null}function SF(e){return e&&(e.projectWorkspace||e.cwd)||``}function CF(e,t,n={},r=[],i=e,a=[],o=[]){let s=IA(e,t),c=new Map(s.map(e=>[e.workspace,e]));r.forEach(e=>{let t=e.sourceAgentId?i.find(t=>t.id===e.sourceAgentId):i.find(t=>t.id===e.agentId),n=e.workspaceRoot||(t?bA(t):``);if(!n)return;let r=c.get(n);if(r){r.hasOpenFile=!0,!r.gitWorktree&&t?.gitWorktree?.workspace&&(r.gitWorktree=t.gitWorktree);return}let a={id:n,name:xA(n),workspace:n,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1,hasOpenFile:!0,gitWorktree:t?.gitWorktree??null};s.push(a),c.set(n,a)}),a.forEach(e=>{if(!e||c.get(e))return;let t={id:e,name:xA(e),workspace:e,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1,gitWorktree:null};s.push(t),c.set(e,t)});let l=new Map(o.map((e,t)=>[e,t]));return s.map((e,t)=>{let r=e.workspace?n[e.workspace]?.trim():``,i=r&&!e.hasMain?{...e,name:r}:e,a=l.get(e.workspace);return{project:{...i,pinned:a!==void 0},pinIndex:a,sourceIndex:t}}).sort((e,t)=>e.pinIndex!==void 0&&t.pinIndex!==void 0?e.pinIndex-t.pinIndex:e.pinIndex===void 0?t.pinIndex===void 0?e.sourceIndex-t.sourceIndex:1:-1).map(e=>e.project)}function wF(e,t,n,r=new Set,i=new Set){return t?aM(e.map(e=>{let n=[e.name,e.workspace].some(e=>e.toLowerCase().includes(t)),a=n?e.agents:e.agents.filter(e=>i.has(e.id)||m(e).toLowerCase().includes(t)),o=n?e.agentSessions:e.agentSessions.filter(e=>r.has(OA(e))||e.title.toLowerCase().includes(t));return a.length>0||o.length>0||e.workspace&&n?{...e,agents:a,agentSessions:o}:null}).filter(e=>!!e),n,!0):e}function TF(e,t,n){return e.flatMap(e=>t.has(e.id)&&!n?[]:[...e.agents.map(e=>({kind:`agent`,id:e.id})),...e.agentSessions.map(e=>({kind:`agent-session`,provider:e.provider,id:e.id,...e.providerHomeId?{providerHomeId:e.providerHomeId}:{}}))])}var EF=`__agent_drop_at_end__`;function DF(e,t,n){let[r,i]=(0,G.useState)(null),a=()=>i(null),o=(e,t)=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),n(),i({agentId:t,targetAgentId:``,position:`before`})},s=(e,t)=>{if(!r||r.agentId===t)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let n=e.currentTarget.getBoundingClientRect(),a=e.clientY<n.top+n.height/2?`before`:`after`;r.targetAgentId===t&&r.position===a||i(e=>e?{...e,targetAgentId:t,position:a}:null)},c=n=>{if(!r)return;let i=e.filter(e=>e.id!==r.agentId),a=n?i.findIndex(e=>e.id===n):i.length;if(a<0)return;let o=n&&r.position===`after`?a+1:a;t(r.agentId,o>0?i[o-1]?.id??``:``,o<i.length?i[o]?.id??``:``)};return{agentDrag:r,beginAgentDrag:o,dropAgent:(e,t)=>{e.preventDefault(),r?.agentId!==t&&c(t),a()},dropAgentAtEnd:e=>{e.preventDefault(),c(),a()},droppingAtEnd:r?.targetAgentId===EF,finishAgentDrag:a,updateAgentDropTarget:s,updateAgentEndDropTarget:e=>{r&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,r.targetAgentId!==EF&&i(e=>e?{...e,targetAgentId:EF,position:`after`}:null))}}}function OF(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`Window`:t===10080?`Weekly`:t%1440==0?`${t/1440}d`:t%60==0?`${t/60}h`:`${t}m`}function kF(e){let t=Number(e);return Number.isFinite(t)?`${Math.round(t)}%`:`--`}function AF(e){let t=Number(e);if(!Number.isFinite(t))return`-- left`;let n=Math.max(0,Math.min(100,100-t));return`${Math.round(n)}% left`}function jF(e){let t=e.forecast?.remainingTokens,n=t==null?null:Number(t);return typeof n==`number`&&Number.isFinite(n)&&n>=0?`${PF(Math.round(n))} tok left`:AF(e.usedPercent)}function MF(e,t){let n=[e],r=kF(t.usedPercent),i=jF(t);return r!==`--`&&n.push(`${r} used`),i!==`-- left`&&n.push(i),n.filter(Boolean).join(` / `)}function NF(e,t){let n=Number(e);if(!Number.isFinite(n)||n<=0)return null;let r=Math.max(0,Math.round((n-t)/6e4));return r===0?`reset now`:r>=1440?`reset ${Math.floor(r/1440)}d ${Math.floor(r%1440/60)}h`:r>=60?`reset ${Math.floor(r/60)}h ${r%60}m`:`reset ${r}m`}function PF(e){if(e>=1e9){let t=e/1e9;return`${t>=10?Math.round(t):Math.round(t*10)/10}B`}if(e>=1e6){let t=e/1e6;return`${t>=10?Math.round(t):Math.round(t*10)/10}M`}if(e>=1e3){let t=e/1e3;return`${t>=10?Math.round(t):Math.round(t*10)/10}k`}return`${e}`}function FF(e,t=!1){let n=Number(e);if(!Number.isFinite(n))return`-- tok/min`;let r=n<10?Math.round(n*10)/10:Math.round(n);return`${t?`~`:``}${PF(r)} tok/min`}function IF(e){let t=e.auth?.status||``;return e.auth?.available?/logged in/i.test(t)?`logged in`:t||`available`:`offline`}function LF(e){if(e.tokenUsage.available===!1)return!1;let t=Number(e.tokenUsage.eventCount),n=Number(e.tokenUsage.totalTokens),r=Number.isFinite(t)&&t>0||Number.isFinite(n)&&n>0;return e.auth.available||r}function RF(e){return e?.providers.filter(LF)??[]}function zF(e){let t=RF(e);return t.length?t.reduce((e,t)=>{let n=Number(t.tokenUsage.tokensPerMinute);return e+(Number.isFinite(n)?n:0)},0):null}function BF(e){let t=e.forecast?.remainingPercent;if(typeof t==`number`&&Number.isFinite(t))return Math.max(0,Math.min(100,t));let n=Number(e.usedPercent);return Number.isFinite(n)?Math.max(0,Math.min(100,100-n)):null}function VF(e){let t=Number(e.windowMinutes);return Number.isFinite(t)&&t>=10020?0:Number.isFinite(t)&&t>=285&&t<=315?1:2}function HF(e){return[e.quota.primary,e.quota.secondary].filter(e=>!!e).map(e=>({label:OF(e.windowMinutes),limit:e,remaining:BF(e),exhaustedAt:typeof e.forecast?.projectedExhaustedAt==`number`&&Number.isFinite(e.forecast.projectedExhaustedAt)?e.forecast.projectedExhaustedAt:null})).filter(e=>e.remaining!==null).sort((e,t)=>VF(e.limit)-VF(t.limit))}function UF(e){let t=Number(e.tokenUsage.tokensPerMinute);return Number.isFinite(t)&&t>0}function WF(e){let t=RF(e);return t.length?t.filter(e=>UF(e)&&e.quota.available).map(e=>{let t=HF(e),n=t.filter(e=>e.remaining!==null&&e.remaining<50);return n.length?{provider:e,limits:t,earliestExhaustedAt:n.reduce((e,t)=>t.exhaustedAt===null?e:e===null?t.exhaustedAt:Math.min(e,t.exhaustedAt),null),lowestRemaining:n.reduce((e,t)=>Math.min(e,t.remaining??100),100)}:null}).filter(e=>!!e).sort((e,t)=>e.earliestExhaustedAt!==null&&t.earliestExhaustedAt!==null?e.earliestExhaustedAt-t.earliestExhaustedAt:e.earliestExhaustedAt===null?t.earliestExhaustedAt===null?e.lowestRemaining-t.lowestRemaining:1:-1)[0]??null:null}function GF(e,t){let n=WF(e);if(!n)return null;let r=[n.provider.providerName];return n.limits.forEach(e=>{r.push(`${e.label} ${Math.round(e.remaining??0)}%`);let n=NF(e.limit.resetsAt,t);n&&r.push(n)}),r.join(` · `)}function KF(e,t,n){let r=GF(e,n);if(r)return r;let i=[],a=zF(e);return a!==null&&i.push(FF(a)),t&&i.push(`CPU ${t.cpu}% / MEM ${t.memory.percentage}%`),i.join(` · `)||`5m`}function qF(e,t){return e??t?.systemStats??null}function JF({usageSummary:e,now:t}){let n=KF(e,qF(d(),e),t);return(0,K.jsx)(`span`,{className:`code-usage-summary`,"data-testid":`code-usage-summary`,title:n,children:n})}function YF({usageSummary:e}){let t=qF(d(),e);return t?(0,K.jsxs)(`div`,{className:`code-usage-row`,children:[(0,K.jsx)(`span`,{children:`System`}),(0,K.jsxs)(`strong`,{children:[`CPU `,t.cpu,`% / MEM `,t.memory.percentage,`%`]})]}):null}function XF(e){return new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}function ZF(e){return`${String(new Date(e).getHours()).padStart(2,`0`)}:00`}function QF(e){return Math.round(e).toLocaleString(`en-US`)}function $F(e){let t=e.map(e=>Math.max(0,Number(e)||0)).filter(e=>e>0).sort((e,t)=>e-t);if(!t.length)return[];let n=t[0],r=t[t.length-1];return n===r?[.2,.4,.6,.8].map(e=>r*e):[.2,.4,.6,.8].map(e=>{let n=(t.length-1)*e,r=Math.floor(n),i=Math.ceil(n),a=t[r];return a+(t[i]-a)*(n-r)})}function eI(e,t){let n=Math.max(0,Number(e)||0);return n<=0?0:Math.max(1,Math.min(5,1+t.filter(e=>n>e).length))}function tI(e){let t=e.timeline,n=Array.isArray(t?.points)?t.points:[];return n.length>0&&n.every((e,t)=>Number.isFinite(Number(e.startedAt))&&Number.isFinite(Number(e.endedAt))&&Number(e.endedAt)>Number(e.startedAt)&&Number.isFinite(Number(e.totalTokens))&&Number(e.totalTokens)>=0&&(t===0||Number(e.startedAt)>=Number(n[t-1].startedAt)))?n:null}function nI(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(n,r-1,i,12,0,0,0);return a.getFullYear()!==n||a.getMonth()!==r-1||a.getDate()!==i?null:a}function rI(e){let t=Array.isArray(e.daily?.points)?e.daily.points:[];return t.length>0&&t.every((e,n)=>!!nI(e.date)&&Number.isFinite(Number(e.totalTokens))&&Number(e.totalTokens)>=0&&(n===0||e.date>t[n-1].date))?t.slice(-364):null}function iI({usageSummary:e,points:t,onInspect:n}){let r=e.timeline,i=t.reduce((e,t)=>e+Number(t.totalTokens),0),a=OF(Number(r.windowMs)/6e4).toLowerCase(),o=[0,.25,.5,.75,1].map(e=>r.startAt+(r.endAt-r.startAt)*e),s=Math.max(0,...t.map(e=>Number(e.totalTokens))),c=t.map((e,n)=>({x:t.length>1?n/(t.length-1)*100:100/2,y:s>0?30-Number(e.totalTokens)/s*26-2:28})),l=c.reduce((e,t,n)=>{if(n===0)return`M ${t.x} ${t.y}`;let r=c[n-1],i=(r.x+t.x)/2;return`${e} C ${i} ${r.y}, ${i} ${t.y}, ${t.x} ${t.y}`},``);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`svg`,{className:`code-usage-sparkline`,"data-testid":`code-usage-sparkline`,viewBox:`0 0 100 30`,preserveAspectRatio:`none`,role:`img`,"aria-label":`Token activity over the last ${a}, ${PF(i)} tokens`,children:[(0,K.jsx)(`path`,{className:`code-usage-sparkline-line`,d:l,vectorEffect:`non-scaling-stroke`}),t.map((e,r)=>{let i=Number(e.totalTokens),a=`${XF(e.startedAt)}–${XF(e.endedAt)}`,o=`${a} · ${QF(i)} tokens`;return(0,K.jsx)(`rect`,{className:`code-usage-sparkline-hit`,"data-start":e.startedAt,x:r/t.length*100,y:`0`,width:100/t.length,height:30,"aria-label":o,onMouseEnter:()=>n({label:a,tokens:i})},`${e.startedAt}-${r}`)})]}),(0,K.jsx)(`div`,{className:`code-usage-time-axis`,"data-testid":`code-usage-time-axis`,"aria-hidden":`true`,children:o.map((e,t)=>(0,K.jsx)(`span`,{children:ZF(e)},`${e}-${t}`))})]})}var aI=(0,G.memo)(function({points:e,layout:t,peakDay:n,recentStartIndex:r,selectedDay:i,showDayHighlight:a,onInspect:o,onPreview:s,ariaLabel:c}){let l=nI(e[0].date),u=t===`calendar`?(l.getDay()+6)%7:0,d=t===`calendar`?Math.max(1,Math.ceil((u+e.length)/7)):Math.min(10,e.length),f=t===`calendar`?d*7-u-e.length:0,p=$F(e.map(e=>e.totalTokens)),m=new Map(e.map(e=>[e.date,e])),h=e=>{let t=e instanceof HTMLElement?e.closest(`.code-usage-daily-heatmap-cell`):null;return t?m.get(t.dataset.date||``)??null:null},g=e=>{let t=h(e);t&&o({label:t.date,tokens:t.totalTokens})};return(0,K.jsxs)(`div`,{className:`code-usage-daily-heatmap`,"data-layout":t,"data-testid":`code-usage-daily-heatmap`,role:a?`group`:`img`,"aria-label":c,style:{gridTemplateColumns:`repeat(${d}, minmax(2px, 1fr))`},onClick:a?e=>g(e.target):void 0,onFocus:a?e=>{let t=h(e.target);t&&s({label:t.date,tokens:t.totalTokens})}:void 0,onBlur:a?e=>{e.currentTarget.contains(e.relatedTarget)||s(null)}:void 0,onKeyDown:a?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),g(e.target))}:void 0,onPointerOver:a?e=>{let t=h(e.target);t&&s({label:t.date,tokens:t.totalTokens})}:void 0,onPointerLeave:a?()=>s(null):void 0,children:[Array.from({length:u},(e,t)=>(0,K.jsx)(`span`,{className:`code-usage-daily-spacer`,"aria-hidden":`true`},`leading-${t}`)),e.map((e,t)=>{let s=Number(e.totalTokens),c=e.date===n?.date,l=s>1e9,u=c?`Token king`:l?`Over 1B tokens`:``,d=`${e.date} · ${PF(s)} tokens${u?` · ${u}`:``}`,f=`${e.date} · ${QF(s)} tokens${u?` · ${u}`:``}`;return(0,K.jsx)(`span`,{className:`code-usage-heatmap-cell code-usage-daily-heatmap-cell`,"data-date":e.date,"data-level":eI(s,p),"data-peak":c?`true`:void 0,"data-billion":l?`true`:void 0,"data-shape":c?`crown`:l?`flame`:void 0,"data-recent":t>=r?`true`:void 0,"data-selected":e.date===i?.date?`true`:void 0,title:a?void 0:d,"aria-label":f,role:a?`button`:void 0,tabIndex:a?0:void 0,onMouseEnter:a?void 0:()=>o({label:e.date,tokens:s})},e.date)}),Array.from({length:f},(e,t)=>(0,K.jsx)(`span`,{className:`code-usage-daily-spacer`,"aria-hidden":`true`},`trailing-${t}`))]})});function oI({points:e,onInspect:t,inspection:n=null,layout:r=`calendar`,rangeLabel:i=`52w`,peakDay:a,showDayHighlight:o=!1}){let[s,c]=(0,G.useState)(null),l=e.filter(e=>e.totalTokens>0).length,u=Math.max(0,e.length-7),d=e.slice(u).reduce((e,t)=>e+t.totalTokens,0),f=e.reduce((e,t)=>!e||t.totalTokens>e.totalTokens?t:e,null),p=f&&f.totalTokens>0?f:null,m=a===void 0?p:a,h=n?e.find(e=>e.date===n.label)??null:null,g=s?e.find(e=>e.date===s.label)??null:null,_=e[e.length-1]??null,v=g??h??_,y=!!(v&&v.date===m?.date),b=!!(g&&g.date!==h?.date);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`code-usage-activity-heading`,children:[(0,K.jsxs)(`span`,{children:[i,` · daily`]}),o&&v?(0,K.jsxs)(`div`,{className:`code-usage-detail-day-highlight`,"data-state":b?`preview`:h?`selected`:`today`,"data-testid":`code-usage-detail-day-highlight`,children:[(0,K.jsxs)(`span`,{children:[(g||h)&&y?`Top · `:``,lI(v.date)]}),(0,K.jsx)(`strong`,{children:PF(v.totalTokens)}),(0,K.jsx)(`small`,{children:`tokens`})]}):(0,K.jsxs)(`span`,{children:[`7d `,PF(d)]})]}),(0,K.jsx)(aI,{points:e,layout:r,peakDay:m,recentStartIndex:u,selectedDay:h,showDayHighlight:o,onInspect:t,onPreview:c,ariaLabel:`Daily token activity over ${i}, ${l} active days`}),o&&(h??_)&&(0,K.jsxs)(`label`,{className:`code-usage-mobile-date-picker`,children:[(0,K.jsx)(`span`,{children:`Selected day`}),(0,K.jsx)(`input`,{type:`date`,min:e[0].date,max:_?.date,value:(h??_).date,"data-testid":`code-usage-mobile-date-picker`,onChange:n=>{let r=e.find(e=>e.date===n.currentTarget.value);r&&t({label:r.date,tokens:r.totalTokens})}})]})]})}function sI(e){return e.reduce((e,t)=>e+Number(t.totalTokens),0)}function cI(e,t){if(t<=0)return e>0?`New`:`0%`;let n=Math.round((e-t)/t*100);return`${n>0?`+`:``}${n}%`}function lI(e){let t=nI(e);return t?t.toLocaleDateString([],{month:`short`,day:`numeric`}):e}function uI(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.date===t&&Array.isArray(n.hours)&&n.hours.length===24&&n.hours.every((e,t)=>e.hour===t&&Number.isFinite(Number(e.totalTokens))&&e.totalTokens>=0&&!!(e.agents&&typeof e.agents==`object`))&&Array.isArray(n.agents)&&n.agents.every(e=>!!(e.key&&e.label)&&Number.isFinite(Number(e.totalTokens))&&e.totalTokens>=0)}function dI(e,t){let[n,i]=(0,G.useState)(0),[a,o]=(0,G.useState)({date:``,detail:null,error:``,loading:!1});return(0,G.useEffect)(()=>{if(!e){o({date:``,detail:null,error:``,loading:!1});return}let n=new AbortController;o({date:e,detail:null,error:``,loading:!0});let i=new URLSearchParams({date:e});return t&&i.set(`live`,`1`),fetch(r(`/api/usage/day?${i.toString()}`),{signal:n.signal}).then(async t=>{let n=await t.json();if(!t.ok)throw Error(n.error||`Failed to load day activity`);if(!uI(n.detail,e))throw Error(`Day activity response was incomplete`);return n.detail}).then(t=>{n.signal.aborted||o({date:e,detail:t,error:``,loading:!1})}).catch(t=>{n.signal.aborted||o({date:e,detail:null,error:t instanceof Error?t.message:`Failed to load day activity`,loading:!1})}),()=>n.abort()},[e,t,n]),{...a,retry:()=>i(e=>e+1)}}var fI=[`#245f1d`,`#3b782f`,`#548f47`,`#70a766`,`#8dbc86`,`#aacda5`,`#486d42`,`#789473`];function pI(e){let t=0;for(let n of e)t=(t<<5)-t+n.charCodeAt(0)|0;return fI[Math.abs(t)%fI.length]}function mI({date:e,detail:t,error:n,loading:r,onRetry:i}){let[a,o]=(0,G.useState)(null);if((0,G.useEffect)(()=>o(null),[e]),r)return(0,K.jsx)(`div`,{className:`code-usage-day-breakdown loading`,"data-testid":`code-usage-day-histogram-loading`,children:(0,K.jsx)(`div`,{className:`code-usage-day-breakdown-status`,children:`Loading hourly Agent activity…`})});if(n)return(0,K.jsxs)(`div`,{className:`code-usage-day-breakdown error`,"data-testid":`code-usage-day-histogram-error`,children:[(0,K.jsx)(`span`,{children:n}),(0,K.jsx)(`button`,{type:`button`,onClick:i,children:`Retry`})]});if(!t)return null;let s=Math.max(0,...t.hours.map(e=>e.totalTokens)),c=Array.from(t.agents.reduce((e,t)=>{let n=e.get(t.provider);return n?n.totalTokens+=t.totalTokens:e.set(t.provider,{key:t.provider,label:b(t.provider),totalTokens:t.totalTokens}),e},new Map).values()).sort((e,t)=>t.totalTokens-e.totalTokens||e.label.localeCompare(t.label)),l=a?`${a.label} · ${PF(a.tokens)} tokens`:`${lI(t.date)} · ${PF(t.total.totalTokens)} tokens`;return(0,K.jsxs)(`div`,{className:`code-usage-day-breakdown`,"data-testid":`code-usage-day-histogram`,onMouseLeave:()=>o(null),children:[(0,K.jsxs)(`div`,{className:`code-usage-day-breakdown-heading`,children:[(0,K.jsx)(`span`,{children:`Hourly by Agent type`}),(0,K.jsx)(`strong`,{"data-testid":`code-usage-day-histogram-readout`,children:l})]}),(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-chart`,role:`img`,"aria-label":`Hourly token activity for ${t.date}, split across ${c.length} Agent types`,children:[(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-scale`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{children:PF(s)}),(0,K.jsx)(`span`,{children:`0`})]}),(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-plot`,children:[(0,K.jsx)(`div`,{className:`code-usage-day-histogram-bars`,children:t.hours.map(e=>{let n=s>0?e.totalTokens/s*100:0;return(0,K.jsx)(`div`,{className:`code-usage-day-histogram-column`,"data-hour":e.hour,title:`${e.label}:00 · ${PF(e.totalTokens)} tokens`,children:(0,K.jsx)(`div`,{className:`code-usage-day-histogram-stack`,style:{height:`${n}%`},children:c.map(n=>{let r=t.agents.reduce((t,r)=>r.provider===n.key?t+(Number(e.agents[r.key]?.totalTokens)||0):t,0);if(r<=0||e.totalTokens<=0)return null;let i=`${e.label}:00 · ${n.label}`,a=`${i} · ${PF(r)} tokens`;return(0,K.jsx)(`span`,{className:`code-usage-day-histogram-segment`,"data-agent-type":n.key,style:{backgroundColor:pI(n.key),height:`${r/e.totalTokens*100}%`},title:a,onMouseEnter:()=>o({label:i,tokens:r})},n.key)})})},e.hour)})}),(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-axis`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{children:`00:00`}),(0,K.jsx)(`span`,{children:`06:00`}),(0,K.jsx)(`span`,{children:`12:00`}),(0,K.jsx)(`span`,{children:`18:00`}),(0,K.jsx)(`span`,{children:`23:00`})]})]})]}),c.length>0&&(0,K.jsx)(`div`,{className:`code-usage-day-agent-legend`,"data-testid":`code-usage-day-agent-legend`,children:c.map(e=>(0,K.jsxs)(`span`,{title:`${e.label} · ${PF(e.totalTokens)} tokens`,children:[(0,K.jsx)(`i`,{style:{backgroundColor:pI(e.key)},"aria-hidden":`true`}),(0,K.jsx)(`b`,{children:e.label}),(0,K.jsx)(`small`,{children:PF(e.totalTokens)})]},e.key))})]})}function hI({label:e,value:t,detail:n}){return(0,K.jsxs)(`div`,{className:`code-usage-detail-stat`,children:[(0,K.jsx)(`span`,{children:e}),(0,K.jsx)(`strong`,{children:t}),n&&(0,K.jsx)(`small`,{children:n})]})}function gI({usageSummary:e,onClose:t}){let[n,r]=(0,G.useState)(null),i=rI(e),a=i?.reduce((e,t)=>!e||t.totalTokens>e.totalTokens?t:e,null)??null,o=i?.[i.length-1]??null,s=(i?.find(e=>e.date===n?.label)??null??o)?.date||``,c=dI(s,!!(s&&i&&s===i[i.length-1]?.date));if(zn(t),typeof document>`u`)return null;let l=i?.slice(-7)??[],u=i?.slice(-14,-7)??[],d=sI(l),f=sI(u),p=i?sI(i):0,m=i?.filter(e=>e.totalTokens>0).length??0,h=l.reduce((e,t)=>e+(Number(t.cacheReadTokens)||0)+(Number(t.cacheWriteTokens)||0),0),g=d>0?Math.min(100,Math.round(h/d*100)):0,_=n?`${n.label} · ${PF(n.tokens)} tokens`:`Last 52 weeks · ${PF(p)} tokens`;return(0,nE.createPortal)((0,K.jsx)(`div`,{className:`code-usage-detail-backdrop`,"data-testid":`code-usage-detail-backdrop`,onMouseDown:e=>{e.target===e.currentTarget&&t()},children:(0,K.jsxs)(`section`,{className:`code-usage-detail-dialog`,"data-testid":`code-usage-detail-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-usage-detail-title`,children:[(0,K.jsxs)(`header`,{className:`code-usage-detail-header`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`code-usage-detail-eyebrow`,children:`Local provider tokens`}),(0,K.jsx)(`h2`,{id:`code-usage-detail-title`,children:`Usage activity`})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-usage-detail-close`,"aria-label":`Close usage activity`,onClick:t,children:(0,K.jsx)(pt,{})})]}),(0,K.jsxs)(`div`,{className:`code-usage-detail-chart`,children:[i&&(0,K.jsx)(oI,{points:i,inspection:n,showDayHighlight:!0,onInspect:r}),(0,K.jsx)(mI,{date:s,detail:c.date===s?c.detail:null,error:c.date===s?c.error:``,loading:c.date===s?c.loading:!0,onRetry:c.retry}),(0,K.jsx)(`div`,{className:`code-usage-detail-readout`,"data-testid":`code-usage-detail-readout`,children:_})]}),(0,K.jsxs)(`div`,{className:`code-usage-detail-analysis`,"data-testid":`code-usage-detail-analysis`,children:[(0,K.jsx)(hI,{label:`Last 7 days`,value:PF(d)}),(0,K.jsx)(hI,{label:`Previous 7 days`,value:PF(f),detail:`${cI(d,f)} change`}),(0,K.jsx)(hI,{label:`Peak day`,value:a?lI(a.date):`--`,detail:a?`${PF(a.totalTokens)} tokens`:`no activity`}),(0,K.jsx)(hI,{label:`Active days`,value:`${m}`,detail:`within 52 weeks`}),(0,K.jsx)(hI,{label:`7-day cache share`,value:`${g}%`,detail:`read and write tokens`}),(0,K.jsx)(hI,{label:`52-week tokens`,value:PF(p)})]})]})}),document.body)}function _I({usageSummary:e}){let t=tI(e),n=rI(e),r=n?.slice(-30)??null,i=n?.reduce((e,t)=>!e||t.totalTokens>e.totalTokens?t:e,null)??null,[a,o]=(0,G.useState)(null),[s,c]=(0,G.useState)(!1);if(!t&&!n)return null;let l=t?.reduce((e,t)=>e+t.totalTokens,0)??0,u=OF(Number(e.timeline?.windowMs)/6e4).toLowerCase(),d=r?.slice(-7).reduce((e,t)=>e+t.totalTokens,0)??0,f=r?.reduce((e,t)=>e+t.totalTokens,0)??0,p=`${a?`${a.label} · ${PF(a.tokens)} tokens`:`${t?`${u} ${PF(l)}`:``}${t&&r?` · `:``}${r?`7d ${PF(d)} · 30d ${PF(f)}`:``}`}${e.daily?.syncing===!0?` · syncing history`:``}`;return(0,K.jsxs)(`div`,{className:`code-usage-activity`,onMouseLeave:()=>o(null),children:[t&&(0,K.jsxs)(`div`,{className:`code-usage-chart-summary`,"data-testid":`code-usage-day-summary`,children:[(0,K.jsxs)(`div`,{className:`code-usage-activity-heading`,children:[(0,K.jsxs)(`span`,{children:[u,` · activity`]}),(0,K.jsxs)(`span`,{children:[OF(e.timeline.bucketMs/6e4).toLowerCase(),` buckets`]})]}),(0,K.jsx)(iI,{usageSummary:e,points:t,onInspect:o})]}),r&&(0,K.jsx)(`button`,{type:`button`,className:`code-usage-chart-trigger`,"data-testid":`code-usage-open-year`,title:`Open 52-week usage details`,onClick:()=>c(!0),children:(0,K.jsx)(oI,{points:r,layout:`matrix`,rangeLabel:`30d`,peakDay:i,onInspect:o})}),(0,K.jsx)(`div`,{className:`code-usage-activity-readout`,"data-testid":`code-usage-activity-readout`,title:p,children:p}),s&&(0,K.jsx)(gI,{usageSummary:e,onClose:()=>c(!1)})]})}function vI({collapsed:e,mainAgent:t,now:n,usageSummary:r,onToggleCollapsed:i,onOpenMainAgent:a,onRestartMainAgent:o}){let s=RF(r),c=zF(r),[l,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(!1),m=u();if(!r&&!t&&!m)return null;let h=!!(r&&rI(r));return(0,K.jsxs)(`div`,{className:`code-usage-panel ${e?`collapsed`:``} ${h?``:`mobile-unavailable`}`,"data-testid":`code-usage-panel`,children:[h&&(0,K.jsxs)(`button`,{type:`button`,className:`code-usage-mobile-open`,"data-testid":`code-mobile-usage-open`,onClick:()=>p(!0),children:[(0,K.jsx)(`span`,{children:`Usage activity`}),(0,K.jsxs)(`span`,{children:[`52 Weeks`,(0,K.jsx)(mt,{})]})]}),(0,K.jsxs)(`button`,{type:`button`,className:`code-usage-header`,"data-testid":`code-usage-toggle`,"aria-expanded":!e,title:`Provider local token usage refreshes periodically.`,onClick:i,children:[(0,K.jsxs)(`span`,{className:`code-usage-title`,children:[(0,K.jsx)(`span`,{className:`code-usage-chevron ${e?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:e?(0,K.jsx)(mt,{}):(0,K.jsx)(Ge,{})}),(0,K.jsx)(`span`,{children:`Usage`})]}),(0,K.jsx)(`span`,{className:`code-usage-header-meta`,children:e?(0,K.jsx)(JF,{usageSummary:r,now:n}):(0,K.jsx)(`span`,{className:`code-usage-summary`,"data-testid":`code-usage-summary`,title:`5-minute rate · hourly and daily activity`,children:`5m rate · activity`})})]}),!e&&(0,K.jsxs)(K.Fragment,{children:[s.length>0&&r?.timeline&&(0,K.jsx)(_I,{usageSummary:r}),t&&(0,K.jsxs)(`div`,{className:`code-usage-main-agent-block`,children:[(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-main-agent`,title:`${A(t)} · ${t.command} · ${t.cwd}`,"data-testid":`code-main-agent-usage-row`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-usage-main-agent-open`,"data-testid":`code-main-agent-open`,onClick:a,children:[(0,K.jsx)(`span`,{children:`Main Agent`}),(0,K.jsx)(`strong`,{children:t.status===`pending`?`starting`:t.status===`dead`?`offline`:t.status})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-usage-main-agent-restart`,"data-testid":`code-main-agent-restart`,"aria-expanded":l,onClick:()=>d(e=>!e),children:`Restart`})]}),l&&(0,K.jsx)(`div`,{className:`code-main-agent-restart-menu`,"data-testid":`code-main-agent-restart-menu`,role:`menu`,children:[[`codex`,`Codex`],[`claude`,`Claude Code`],[`opencode`,`OpenCode`],[`qoder`,`Qoder`],[`qwen`,`Qwen Code`],[`bash`,`bash`],[`zsh`,`zsh`]].map(([e,t])=>(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-main-agent-restart-${e}`,onClick:()=>{d(!1),o(e)},children:t},e))})]}),s.map(e=>(0,K.jsx)(yI,{provider:e},e.provider)),s.length>1&&c!==null&&(0,K.jsxs)(`div`,{className:`code-usage-row`,title:`Sum of local token usage reported by providers.`,children:[(0,K.jsx)(`span`,{children:`Total local tokens`}),(0,K.jsx)(`strong`,{children:FF(c)})]}),(0,K.jsx)(YF,{usageSummary:r})]}),f&&h&&r&&(0,K.jsx)(gI,{usageSummary:r,onClose:()=>p(!1)})]})}function yI({provider:e}){let t=e.quota.primary??null,n=e.quota.secondary??null,r=e.quota.available?e.quota.source:e.quota.reason||e.quota.source;return(0,K.jsxs)(`div`,{className:`code-usage-provider`,children:[(0,K.jsxs)(`div`,{className:`code-usage-row`,children:[(0,K.jsx)(`span`,{children:e.providerName}),(0,K.jsx)(`strong`,{title:e.auth?.status,children:IF(e)})]}),e.quota.available&&(0,K.jsxs)(K.Fragment,{children:[t&&(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:MF(r,t),children:[(0,K.jsx)(`span`,{children:OF(t.windowMinutes)}),(0,K.jsx)(`strong`,{children:jF(t)})]}),n&&(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:MF(r,n),children:[(0,K.jsx)(`span`,{children:OF(n.windowMinutes)}),(0,K.jsx)(`strong`,{children:jF(n)})]})]}),(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:e.tokenUsage.source,children:[(0,K.jsx)(`span`,{children:`Local tokens`}),(0,K.jsx)(`strong`,{children:FF(e.tokenUsage.tokensPerMinute)})]})]})}function bI(e,t){return t===`appearance`?{kind:`notification`,notification:`rest-reminder-setup`,option:`appearance`}:e===null?{kind:`notification`,notification:`rest-reminder-setup`,option:`invitation`}:null}var xI=`farmingPetSettings`,SI=`farming-pet-settings`,CI=`farming-pet-appearance-preview`,wI=`farmingPetRestReminderRuntime`,TI=`farmingPetRestReminderInvitationRuntime`,EI=3e3,DI=30*6e4,OI=`petRestInvitationSeconds`,kI=[0,5,1500,1800,2400,EI,3600,5400];function AI(e=``,t=!1){if(!t)return DI;let n=new URLSearchParams(e).get(OI);if(n===null)return DI;let r=Number(n);return Number.isInteger(r)&&r>=1&&r<=1800?r*1e3:DI}function jI(e){return e>=5400?10:5}function MI(e){let t=e??0,n=kI.indexOf(t);if(n>=0)return n;let r=kI.findIndex(e=>e>t);if(r<0)return kI.length-1;if(r===0)return 0;let i=r-1,a=kI[i],o=kI[r];return i+(t-a)/(o-a)}function NI(e){return kI[Math.max(0,Math.min(kI.length-1,Math.round(e)))]??0}function PI(e){return e===5?5:30}function FI(e,t){typeof window>`u`||window.dispatchEvent(new CustomEvent(CI,{detail:{appearance:e,onEnd:t?.onEnd}}))}function II(e){return e===`glass`||e===`black-hole`?e:null}function LI(e){if(e===null)return null;try{return JSON.parse(e)}catch{return null}}function RI(e){if(e==null||e===``)return null;let t=Number(e);return Number.isInteger(t)&&(t===0||t===5||t>=60&&t<=14400&&t%60==0)?t:null}function zI(e){return RI(LI(e)?.capabilities?.restReminder?.intervalSeconds)}function BI(e){if(!e&&typeof window>`u`)return null;try{return zI((e??window.localStorage).getItem(xI))}catch{return null}}function VI(e,t=`glass`){if(!e&&typeof window>`u`)return t;try{return II(LI((e??window.localStorage).getItem(`farmingPetSettings`))?.appearance)??t}catch{return t}}function HI(e,t){window.dispatchEvent(new CustomEvent(SI,{detail:{capability:`rest-reminder`,intervalSeconds:e,appearance:t}}))}function UI(e,t,n=`glass`){let r=RI(e);if(r===null)return!1;let i=t??window.localStorage,a;try{let e=II(LI(i.getItem(xI))?.appearance);a=e??n;let t={version:1,...e?{appearance:e}:{},capabilities:{restReminder:{intervalSeconds:r}}};i.setItem(xI,JSON.stringify(t))}catch{return!1}return typeof window<`u`&&!t&&HI(r,a),!0}function WI(e,t){let n=t??window.localStorage,r=BI(n)??0,i={version:1,appearance:e,capabilities:{restReminder:{intervalSeconds:r}}};try{n.setItem(xI,JSON.stringify(i))}catch{return!1}return typeof window<`u`&&!t&&HI(r,e),!0}var GI=Promise.resolve(!0);async function KI(e){let t=await fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({restReminderIntervalSeconds:e})}),n=await t.json().catch(()=>null);if(!t.ok)throw Error(n?.error||`Could not save break reminder (${t.status})`);let i=RI(n?.settings?.restReminderIntervalSeconds);if(i===null)throw Error(`The saved break reminder setting is invalid.`);return i}function qI(e,t=`glass`){let n=RI(e);if(n===null)return Promise.resolve(!1);let r=async()=>{try{return UI(await KI(n),void 0,t)}catch{return!1}},i=GI.then(r,r);return GI=i.then(()=>!0,()=>!0),i}async function JI(e=`glass`){let t=BI();try{let n=await fetch(r(`/api/settings`));if(!n.ok)return t;let i=RI((await n.json()).settings?.restReminderIntervalSeconds);return i===null?t===null?null:(await qI(t,e),t):(UI(i,void 0,e),i)}catch{return t}}function YI(e){return e===xI}function XI(e){return{phase:`armed`,intervalSeconds:e,cycleStartedAt:null,backgroundedAt:null,snoozedUntil:null,restStartsAt:null,restUntil:null,snoozeUsed:!1}}function ZI(e,t){return{...XI(e.intervalSeconds),phase:`resting`,restUntil:t+jI(e.intervalSeconds)*6e4,snoozeUsed:e.snoozeUsed}}function QI(e,t){return{...e,phase:`due`,snoozedUntil:null,restStartsAt:t+PI(e.intervalSeconds)*1e3}}function $I(e,t){if(e.phase===`resting`)return e.restUntil!==null&&t>=e.restUntil?XI(e.intervalSeconds):e;if(e.backgroundedAt!==null)return e;if(e.phase===`working`&&e.cycleStartedAt!==null&&t-e.cycleStartedAt>=e.intervalSeconds*1e3){let n=QI(e,e.cycleStartedAt+e.intervalSeconds*1e3);if(n.restStartsAt!==null&&t>=n.restStartsAt){let r=ZI(n,n.restStartsAt);return r.restUntil!==null&&t>=r.restUntil?XI(e.intervalSeconds):r}return n}if(e.phase===`snoozed`&&e.snoozedUntil!==null&&t>=e.snoozedUntil){let n=QI(e,e.snoozedUntil);if(n.restStartsAt!==null&&t>=n.restStartsAt){let r=ZI(n,n.restStartsAt);return r.restUntil!==null&&t>=r.restUntil?XI(e.intervalSeconds):r}return n}if(e.phase===`due`&&e.restStartsAt!==null&&t>=e.restStartsAt){let n=ZI(e,e.restStartsAt);return n.restUntil!==null&&t>=n.restUntil?XI(e.intervalSeconds):n}return e}function eL(e,t,n){let r=RI(t);if(r===null||r<=0)throw Error(`A positive rest reminder interval is required.`);if(e.intervalSeconds===r)return e;let i={...e,intervalSeconds:r},a=i.backgroundedAt??n;return i.phase===`working`&&i.cycleStartedAt!==null&&a-i.cycleStartedAt>=r*1e3?QI(i,a):i}function tL(e,t){return{...XI(e.intervalSeconds),phase:`working`,cycleStartedAt:t}}function nL(e,t){if(e.phase===`resting`)return $I(e,t);if(e.phase===`armed`)return tL(e,t);if(e.backgroundedAt===null)return $I(e,t);let n=Math.max(0,t-e.backgroundedAt);return n>=3e5?tL(e,t):$I({...e,backgroundedAt:null,cycleStartedAt:e.cycleStartedAt===null?null:e.cycleStartedAt+n,snoozedUntil:e.snoozedUntil===null?null:e.snoozedUntil+n,restStartsAt:e.restStartsAt===null?null:e.restStartsAt+n},t)}function rL(e,t){if(t.type===`interaction`&&e.phase===`due`)return{...e,restStartsAt:t.now+PI(e.intervalSeconds)*1e3};if(t.type===`dismiss`)return tL(e,t.now);if(t.type===`snooze`&&e.phase===`due`&&!e.snoozeUsed)return{...XI(e.intervalSeconds),phase:`snoozed`,snoozedUntil:t.now+10*6e4,snoozeUsed:!0};if(t.type===`background`)return e.phase===`resting`||e.backgroundedAt!==null?e:{...e,backgroundedAt:t.now};if(t.type===`foreground`)return nL(e,t.now);let n=$I(e,t.now);return t.type===`deadline`?n:t.type===`interaction`&&n.phase===`due`?{...n,restStartsAt:t.now+PI(n.intervalSeconds)*1e3}:n}function iL(e){return e.phase===`resting`?e.restUntil:e.backgroundedAt===null?e.phase===`due`?e.restStartsAt:e.phase===`armed`?null:e.phase===`working`&&e.cycleStartedAt!==null?e.cycleStartedAt+e.intervalSeconds*1e3:e.phase===`snoozed`&&e.snoozedUntil!==null?e.snoozedUntil:null:null}function aL(e){return e===null||typeof e==`number`&&Number.isFinite(e)}function oL(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;if(![`armed`,`working`,`due`,`snoozed`,`resting`].includes(String(t.phase))||RI(t.intervalSeconds)!==t.intervalSeconds||!t.intervalSeconds||t.intervalSeconds<=0||!aL(t.cycleStartedAt)||!aL(t.backgroundedAt)||!aL(t.snoozedUntil)||!aL(t.restStartsAt)||!aL(t.restUntil)||typeof t.snoozeUsed!=`boolean`)return null;let n={phase:t.phase,intervalSeconds:t.intervalSeconds,cycleStartedAt:t.cycleStartedAt,backgroundedAt:t.backgroundedAt,snoozedUntil:t.snoozedUntil,restStartsAt:t.restStartsAt,restUntil:t.restUntil,snoozeUsed:t.snoozeUsed};return n.phase===`working`&&n.cycleStartedAt===null||n.phase===`due`&&n.restStartsAt===null||n.phase===`snoozed`&&n.snoozedUntil===null||n.phase===`resting`&&n.restUntil===null?null:n}function sL(e){return!e||typeof e!=`object`||Array.isArray(e)?null:oL({...e,backgroundedAt:null})}function cL(e,t=Date.now(),n){if(!n&&typeof window>`u`)return null;try{let r=(n??window.sessionStorage).getItem(wI);if(r===null)return null;let i=JSON.parse(r),a=i.version===2?oL(i.state):i.version===1?sL(i.state):null;return a?$I(eL(a,e,t),t):null}catch{return null}}function lL(e,t){if(!t&&typeof window>`u`)return!1;try{let n=t??window.sessionStorage;if(e===null)n.removeItem(wI);else{let t={version:2,state:e};n.setItem(wI,JSON.stringify(t))}return!0}catch{return!1}}var uL=840,dL=920,fL=72,pL=640,mL=.22,hL=.46,gL=2,_L=1e3,vL=1e4,yL=[`[data-pet-ui]`,`[data-pet-snapshot-exclude]`,`.code-pet-black-hole-rest`,`.code-pet-glass-rest-overlay`].join(`, `),bL=`img.code-file-type-icon`,xL=1792,SL=1.25,CL=15,wL=90,TL=4.8,EL=.01,DL=.5,OL=.02,kL=.33,AL=.014,jL=.052,ML=`#version 300 es
214
+ void main() {
215
+ vec2 position = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
216
+ gl_Position = vec4(position * 2.0 - 1.0, 0.0, 1.0);
217
+ }`,NL=`
218
+ const float B_CRIT = 2.5980762;
219
+
220
+ float hash21(vec2 p) {
221
+ p = fract(p * vec2(234.34, 435.345));
222
+ p += dot(p, p + 34.23);
223
+ return fract(p.x * p.y);
224
+ }
225
+
226
+ float wrappedNoise(vec2 p, float periodY) {
227
+ vec2 i = floor(p);
228
+ vec2 f = fract(p);
229
+ f = f * f * (3.0 - 2.0 * f);
230
+ float y0 = mod(i.y, periodY);
231
+ float y1 = mod(i.y + 1.0, periodY);
232
+ return mix(
233
+ mix(hash21(vec2(i.x, y0)), hash21(vec2(i.x + 1.0, y0)), f.x),
234
+ mix(hash21(vec2(i.x, y1)), hash21(vec2(i.x + 1.0, y1)), f.x),
235
+ f.y
236
+ );
237
+ }
238
+
239
+ vec2 rotate2d(vec2 value, float angle) {
240
+ float c = cos(angle);
241
+ float s = sin(angle);
242
+ return vec2(c * value.x - s * value.y, s * value.x + c * value.y);
243
+ }
244
+
245
+ vec3 blackbody(float temperature) {
246
+ float t = clamp(temperature, 1500.0, 40000.0) / 100.0;
247
+ float r = t <= 66.0
248
+ ? 1.0
249
+ : clamp(1.292936 * pow(t - 60.0, -0.1332047), 0.0, 1.0);
250
+ float g = t <= 66.0
251
+ ? clamp(0.3900816 * log(t) - 0.6318414, 0.0, 1.0)
252
+ : clamp(1.1298909 * pow(t - 60.0, -0.0755148), 0.0, 1.0);
253
+ float b = t >= 66.0
254
+ ? 1.0
255
+ : (t <= 19.0
256
+ ? 0.0
257
+ : clamp(0.5432068 * log(t - 10.0) - 1.1962540, 0.0, 1.0));
258
+ return vec3(r, g, b);
259
+ }
260
+
261
+ float smoother(float value) {
262
+ float t = clamp(value, 0.0, 1.0);
263
+ return t * t * t * (t * (t * 6.0 - 15.0) + 10.0);
264
+ }
265
+
266
+ float fieldFade(float radius) {
267
+ return 1.0 - smoother(
268
+ (radius - ${mL.toFixed(2)}) /
269
+ ${(hL-mL).toFixed(2)}
270
+ );
271
+ }
272
+ `,PL=`#version 300 es
273
+ precision highp float;
274
+
275
+ uniform vec2 uResolution;
276
+ uniform float uTime;
277
+ uniform float uOpacity;
278
+ uniform float uTemperature;
279
+ uniform float uInclination;
280
+ uniform float uRoll;
281
+ uniform float uInnerRadius;
282
+ uniform float uOuterRadius;
283
+ uniform float uDiskOpacity;
284
+ uniform float uDoppler;
285
+ uniform float uBeam;
286
+ uniform float uGain;
287
+ uniform float uContrast;
288
+ uniform float uWind;
289
+ uniform float uSpeed;
290
+ uniform float uExposure;
291
+ uniform float uStarField;
292
+ uniform float uFilamentDetail;
293
+ uniform float uMass;
294
+ uniform float uDiskFeed;
295
+ uniform float uHawking;
296
+ uniform float uFinalBurst;
297
+ out vec4 outColor;
298
+
299
+ ${NL}
300
+
301
+ vec3 stars(vec3 direction) {
302
+ vec2 sphere = vec2(
303
+ atan(direction.x, -direction.z),
304
+ asin(clamp(direction.y, -1.0, 1.0))
305
+ );
306
+ vec2 grid = sphere * 40.0;
307
+ vec2 id = floor(grid);
308
+ float h = hash21(id);
309
+ if (h < 0.94) return vec3(0.0);
310
+ vec2 offset = (vec2(hash21(id + 17.3), hash21(id + 31.7)) - 0.5) * 0.7;
311
+ float spark = smoothstep(0.10, 0.0, length(fract(grid) - 0.5 - offset));
312
+ float twinkle = 0.82 + 0.18 * sin(uTime * (0.5 + 1.4 * hash21(id + 5.1)) + 40.0 * h);
313
+ return mix(vec3(1.0, 0.82, 0.60), vec3(0.75, 0.85, 1.0), hash21(id + 2.9))
314
+ * spark * twinkle * ((h - 0.94) / 0.06) * 0.34 * uStarField;
315
+ }
316
+
317
+ vec4 evaporation(vec2 point, float baseHorizon, float horizon) {
318
+ if (uHawking <= 0.001 && uFinalBurst <= 0.001) return vec4(0.0);
319
+ float heat = clamp(uHawking, 0.0, 1.0);
320
+ float release = clamp(uFinalBurst, 0.0, 1.0);
321
+ float distanceFromCenter = length(point);
322
+ float pixel = 1.5 / uResolution.x;
323
+ float q = distanceFromCenter / max(horizon, baseHorizon * 0.018);
324
+ float heatEnvelope = smoother(heat / 0.10) * (1.0 - smoother(release));
325
+ vec3 heatColor = mix(
326
+ vec3(1.0, 0.48, 0.12),
327
+ vec3(0.72, 0.90, 1.0),
328
+ smoother(heat)
329
+ );
330
+
331
+ float photonRadius = horizon * mix(1.10, 1.34, heat);
332
+ float photonWidth = max(pixel, horizon * mix(0.075, 0.13, heat));
333
+ float photonRing = exp(-pow(
334
+ (distanceFromCenter - photonRadius) / photonWidth,
335
+ 2.0
336
+ ));
337
+ float secondaryRing = exp(-pow(
338
+ (distanceFromCenter - photonRadius - photonWidth * 2.35)
339
+ / max(pixel, photonWidth * 0.55),
340
+ 2.0
341
+ )) * mix(0.12, 0.34, heat);
342
+ float corona = exp(-q * 2.45) * pow(heat, 2.2) * 0.22;
343
+
344
+ float releaseProgress = smoother(release);
345
+ float echoRadius = baseHorizon * mix(0.12, 5.0, releaseProgress);
346
+ float echoWidth = max(pixel * 1.25, baseHorizon * mix(0.085, 0.026, releaseProgress));
347
+ float echoEnvelope =
348
+ smoother(release / 0.10) * pow(max(1.0 - release, 0.0), 0.72);
349
+ float echoRing = exp(-pow(
350
+ (distanceFromCenter - echoRadius) / echoWidth,
351
+ 2.0
352
+ )) * echoEnvelope;
353
+
354
+ float flashEnvelope = exp(-pow((release - 0.16) / 0.12, 2.0));
355
+ float flashRadius = baseHorizon * mix(0.12, 0.42, smoother(release / 0.35));
356
+ float flash = exp(-pow(
357
+ distanceFromCenter / max(flashRadius, pixel),
358
+ 2.0
359
+ )) * flashEnvelope;
360
+ vec3 color =
361
+ heatColor * heatEnvelope * (photonRing + secondaryRing + corona)
362
+ + vec3(0.76, 0.91, 1.0) * echoRing * 1.35
363
+ + vec3(0.90, 0.96, 1.0) * flash * 2.8;
364
+ return vec4(
365
+ color,
366
+ clamp(
367
+ heatEnvelope * (photonRing * 0.90 + secondaryRing * 0.55 + corona)
368
+ + echoRing * 0.78
369
+ + flash * 0.92,
370
+ 0.0,
371
+ 1.0
372
+ )
373
+ );
374
+ }
375
+
376
+ void main() {
377
+ vec2 uv = vec2(gl_FragCoord.x, uResolution.y - gl_FragCoord.y) / uResolution;
378
+ vec2 point = uv - 0.5;
379
+ float pointLength = length(point);
380
+ float baseHorizon = ${(fL/uL).toFixed(8)};
381
+ float horizon = baseHorizon * max(uMass, 0.015);
382
+ vec4 evaporationColor = evaporation(point, baseHorizon, horizon);
383
+ float window = exp(-pow(pointLength / (7.0 * horizon), 2.0)) * fieldFade(pointLength);
384
+ if (max(window, evaporationColor.a) < 0.002) {
385
+ outColor = vec4(0.0);
386
+ return;
387
+ }
388
+
389
+ float innerRadius = uInnerRadius;
390
+ float outerRadius = uOuterRadius;
391
+ float roll = uRoll;
392
+ float inclination = uInclination;
393
+ float diskOpacity = uDiskOpacity;
394
+ float doppler = uDoppler;
395
+ float beam = uBeam;
396
+ float gain = uGain;
397
+ float contrast = uContrast;
398
+ float wind = uWind;
399
+ float speed = uSpeed;
400
+ float exposure = uExposure;
401
+ float projection = B_CRIT / horizon;
402
+ vec2 projected = rotate2d(vec2(point.x, -point.y), roll) * projection;
403
+ float impact = length(projected);
404
+ float maxImpact = outerRadius + 3.0;
405
+ float zStart = max(14.0, outerRadius + 5.0);
406
+
407
+ if (impact >= maxImpact) {
408
+ vec3 direction = normalize(vec3(-(projected / impact) * (2.0 / impact), -1.0));
409
+ vec3 starColor = stars(direction) * window;
410
+ float starAlpha = max(max(starColor.r, starColor.g), starColor.b) * uOpacity;
411
+ outColor = vec4(
412
+ starColor + evaporationColor.rgb * (1.0 - starAlpha),
413
+ max(starAlpha, evaporationColor.a)
414
+ );
415
+ return;
416
+ }
417
+
418
+ vec3 position = vec3(projected, zStart);
419
+ vec3 velocity = vec3(0.0, 0.0, -1.0);
420
+ float angularMomentum = dot(projected, projected);
421
+ vec3 diskNormal = vec3(0.0, sin(inclination), cos(inclination));
422
+ vec3 diskAxis = vec3(0.0, cos(inclination), -sin(inclination));
423
+ vec3 emission = vec3(0.0);
424
+ float transmittance = 1.0;
425
+ bool captured = false;
426
+ float previousSide = dot(position, diskNormal);
427
+ vec3 previousPosition = position;
428
+
429
+ for (int step = 0; step < 48; step++) {
430
+ float radiusSquared = dot(position, position);
431
+ if (radiusSquared < 1.0) {
432
+ captured = true;
433
+ break;
434
+ }
435
+ if (position.z < -zStart && velocity.z < 0.0) break;
436
+ if (radiusSquared > 4.0 * zStart * zStart) break;
437
+
438
+ float radius = sqrt(radiusSquared);
439
+ float delta = clamp(0.16 * radius, 0.03, 1.5);
440
+ vec3 acceleration =
441
+ -1.5 * angularMomentum * position / (radiusSquared * radiusSquared * radius);
442
+ velocity += acceleration * (0.5 * delta);
443
+ position += velocity * delta;
444
+ radiusSquared = dot(position, position);
445
+ radius = sqrt(radiusSquared);
446
+ acceleration =
447
+ -1.5 * angularMomentum * position / (radiusSquared * radiusSquared * radius);
448
+ velocity += acceleration * (0.5 * delta);
449
+
450
+ float side = dot(position, diskNormal);
451
+ if (side * previousSide < 0.0 && transmittance > 0.02) {
452
+ float crossing = previousSide / (previousSide - side);
453
+ vec3 diskPoint = mix(previousPosition, position, crossing);
454
+ float diskRadius = length(diskPoint);
455
+ if (diskRadius > innerRadius && diskRadius < outerRadius) {
456
+ float band = smoothstep(innerRadius, innerRadius * 1.25, diskRadius)
457
+ * (1.0 - smoothstep(outerRadius * 0.70, outerRadius, diskRadius));
458
+ float phi = atan(dot(diskPoint, diskAxis), diskPoint.x);
459
+ float turns = phi / 6.2831853;
460
+ float kepler = pow(innerRadius / diskRadius, 1.5);
461
+ float gravity = sqrt(max(1.0 - 1.5 / diskRadius, 0.02));
462
+ float swirl = diskRadius * wind * 0.12 - uTime * kepler * gravity * speed * 0.38;
463
+ float fineFilament = wrappedNoise(
464
+ vec2(
465
+ diskRadius * 2.8 + 0.24 * sin(phi * 3.0 - swirl * 0.22),
466
+ turns * 19.0 + swirl * 3.0 + diskRadius * 0.72
467
+ ),
468
+ 19.0
469
+ );
470
+ float broadFilament = wrappedNoise(
471
+ vec2(
472
+ diskRadius * 1.35 + 0.38 * sin(phi * 2.0 + swirl * 0.16),
473
+ turns * 8.0 + swirl * 1.35 - diskRadius * 0.55
474
+ ),
475
+ 8.0
476
+ );
477
+ float flow = mix(broadFilament, fineFilament, uFilamentDetail);
478
+ float filament = smoother(flow);
479
+ float streaks = mix(0.84, 1.12 + contrast * 0.04, filament);
480
+ vec3 gasDirection = normalize(cross(diskNormal, diskPoint));
481
+ float beta = clamp(
482
+ inversesqrt(max(2.0 * (diskRadius - 1.0), 0.2)),
483
+ 0.0,
484
+ 0.99
485
+ );
486
+ float frequencyShift = gravity / max(
487
+ 1.0 + beta * dot(gasDirection, normalize(velocity)),
488
+ 0.05
489
+ );
490
+ frequencyShift = mix(1.0, frequencyShift, doppler);
491
+ float x = max(1.0 - sqrt(innerRadius / diskRadius), 0.0);
492
+ float temperatureProfile =
493
+ pow(innerRadius / diskRadius, 0.75) * pow(x, 0.25) / 0.488;
494
+ vec3 color = blackbody(uTemperature * temperatureProfile * frequencyShift);
495
+ float density = band * streaks * uDiskFeed;
496
+ emission += transmittance * color
497
+ * (gain * 2.2 * density * temperatureProfile * temperatureProfile
498
+ * pow(frequencyShift, beam));
499
+ transmittance *= 1.0 - clamp(diskOpacity * density, 0.0, 1.0);
500
+ }
501
+ }
502
+ previousSide = side;
503
+ previousPosition = position;
504
+ }
505
+
506
+ if (!captured && dot(position, position) < 4.0) captured = true;
507
+ vec3 starColor = vec3(0.0);
508
+ float shadowPixel = max(0.004, 1.25 * projection / uResolution.x);
509
+ float shadowCoverage =
510
+ 1.0 - smoothstep(B_CRIT - shadowPixel, B_CRIT + shadowPixel, impact);
511
+ float tracedCapture = captured ? 1.0 : 0.0;
512
+ float analyticEdge = 1.0 - smoothstep(
513
+ shadowPixel,
514
+ shadowPixel * 3.0,
515
+ abs(impact - B_CRIT)
516
+ );
517
+ float skyBlock = mix(tracedCapture, shadowCoverage, analyticEdge);
518
+ if (!captured) {
519
+ vec3 direction = normalize(velocity);
520
+ starColor = stars(direction) * window;
521
+ skyBlock = max(
522
+ skyBlock,
523
+ 1.0 - smoothstep(0.05, 0.35, -direction.z)
524
+ );
525
+ }
526
+ vec3 disk = vec3(1.0) - exp(-emission * exposure);
527
+ float alpha = clamp(skyBlock + (1.0 - transmittance), 0.0, 1.0) * uOpacity;
528
+ vec3 body = (starColor * transmittance + disk) * uOpacity;
529
+ outColor = vec4(
530
+ body + evaporationColor.rgb * (1.0 - alpha),
531
+ max(alpha, evaporationColor.a)
532
+ );
533
+ }`,FL=`#version 300 es
534
+ precision highp float;
535
+
536
+ uniform vec2 uResolution;
537
+ uniform float uByte;
538
+ out vec4 outColor;
539
+
540
+ ${NL}
541
+
542
+ void writeMap(vec2 displacement, float activity) {
543
+ float cap = ${pL.toFixed(1)} * 0.48;
544
+ vec2 limited = cap * tanh(displacement / cap);
545
+ vec2 packed = floor(
546
+ clamp(0.5 + limited / ${pL.toFixed(1)}, 0.0, 1.0) * 65535.0 + 0.5
547
+ );
548
+ vec2 highByte = floor(packed / 256.0);
549
+ vec2 lowByte = packed - highByte * 256.0;
550
+ outColor = vec4((uByte < 0.5 ? highByte : lowByte) / 255.0, activity, 1.0);
551
+ }
552
+
553
+ void main() {
554
+ vec2 css = vec2(
555
+ gl_FragCoord.x / uResolution.x * ${dL.toFixed(1)},
556
+ (uResolution.y - gl_FragCoord.y) / uResolution.y * ${dL.toFixed(1)}
557
+ );
558
+ vec2 point = (css - ${dL/2}.0) / ${uL.toFixed(1)};
559
+ float pointLength = length(point);
560
+ float edge = fieldFade(pointLength);
561
+ float horizon = ${(fL/uL).toFixed(8)};
562
+ if (pointLength < 0.00001 || edge <= 0.0) {
563
+ writeMap(vec2(0.0), 0.0);
564
+ return;
565
+ }
566
+
567
+ float projection = B_CRIT / horizon;
568
+ vec2 projected = rotate2d(vec2(point.x, -point.y), 0.10) * projection;
569
+ float impact = length(projected);
570
+ float outerRadius = 7.0;
571
+ float maxImpact = outerRadius + 3.0;
572
+ float blendInnerImpact = maxImpact - 1.5;
573
+ float blendOuterImpact = maxImpact + 1.5;
574
+ float zStart = max(14.0, outerRadius + 5.0);
575
+ vec2 sourcePoint = point;
576
+ bool valid = false;
577
+
578
+ float u = zStart * inversesqrt(zStart * zStart + impact * impact);
579
+ float farDeflection = (2.0 / (projection * projection))
580
+ / max(pointLength, 0.0001)
581
+ * (1.29 * u + 0.07)
582
+ * max(13.0 - 2.14 * u + 0.75, 0.0);
583
+ vec2 farSourcePoint =
584
+ point - point / max(pointLength, 0.00001) * farDeflection;
585
+
586
+ if (impact <= blendOuterImpact) {
587
+ vec3 position = vec3(projected, zStart);
588
+ vec3 velocity = vec3(0.0, 0.0, -1.0);
589
+ float angularMomentum = dot(projected, projected);
590
+ bool captured = false;
591
+ for (int step = 0; step < 48; step++) {
592
+ float radiusSquared = dot(position, position);
593
+ if (radiusSquared < 1.0) {
594
+ captured = true;
595
+ break;
596
+ }
597
+ if (position.z < -zStart && velocity.z < 0.0) break;
598
+ if (radiusSquared > 4.0 * zStart * zStart) break;
599
+ float radius = sqrt(radiusSquared);
600
+ float delta = clamp(0.16 * radius, 0.03, 1.5);
601
+ vec3 acceleration =
602
+ -1.5 * angularMomentum * position / (radiusSquared * radiusSquared * radius);
603
+ velocity += acceleration * (0.5 * delta);
604
+ position += velocity * delta;
605
+ radiusSquared = dot(position, position);
606
+ radius = sqrt(radiusSquared);
607
+ acceleration =
608
+ -1.5 * angularMomentum * position / (radiusSquared * radiusSquared * radius);
609
+ velocity += acceleration * (0.5 * delta);
610
+ }
611
+ if (!captured && dot(position, position) < 4.0) captured = true;
612
+ if (!captured) {
613
+ vec3 direction = normalize(velocity);
614
+ if (direction.z < -0.05) {
615
+ float planeDistance = (-13.0 - position.z) / direction.z;
616
+ vec3 hitPoint = position + direction * planeDistance;
617
+ vec2 unrotated = rotate2d(hitPoint.xy, -0.10) / projection;
618
+ vec2 tracedSourcePoint = vec2(unrotated.x, -unrotated.y);
619
+ // The numerical trace is most useful near the lens, while the
620
+ // far-field approximation is much cheaper outside it. A quintic
621
+ // blend has zero slope at both ends, so the displacement field does
622
+ // not develop a visible radial crease where the implementations meet.
623
+ float farMix = smoother(
624
+ (impact - blendInnerImpact) /
625
+ (blendOuterImpact - blendInnerImpact)
626
+ );
627
+ sourcePoint = mix(tracedSourcePoint, farSourcePoint, farMix);
628
+ valid = true;
629
+ }
630
+ }
631
+ }
632
+ if (!valid && impact >= blendInnerImpact) {
633
+ sourcePoint = farSourcePoint;
634
+ valid = true;
635
+ }
636
+
637
+ vec2 displacement = valid
638
+ ? (sourcePoint - point) * exp(-pow(pointLength / (7.0 * horizon), 2.0)) * edge
639
+ : vec2(0.0);
640
+ float offsetPixels = length(displacement) * ${uL.toFixed(1)};
641
+ writeMap(
642
+ displacement * ${uL.toFixed(1)},
643
+ smoother(offsetPixels / ${gL.toFixed(1)})
644
+ );
645
+ }`,IL=`#version 300 es
646
+ precision highp float;
647
+
648
+ uniform vec2 uResolution;
649
+ uniform vec2 uCenter;
650
+ uniform float uScale;
651
+ uniform float uOpacity;
652
+ uniform float uPixelRatio;
653
+ uniform sampler2D uScene;
654
+ uniform sampler2D uHigh;
655
+ uniform sampler2D uLow;
656
+ out vec4 outColor;
657
+
658
+ vec4 scene(vec2 pixel) {
659
+ vec2 uv = clamp(pixel / uResolution, vec2(0.0), vec2(1.0));
660
+ return texture(uScene, uv);
661
+ }
662
+
663
+ void main() {
664
+ vec2 fragment = gl_FragCoord.xy;
665
+ vec4 original = scene(fragment);
666
+ vec2 relative = fragment - uCenter;
667
+ float radius = length(relative) / (${uL.toFixed(1)} * uScale);
668
+ if (radius >= ${hL.toFixed(2)} || uOpacity <= 0.001) {
669
+ outColor = original;
670
+ return;
671
+ }
672
+ vec2 mapUv = relative / (${dL.toFixed(1)} * uScale) + 0.5;
673
+ vec4 high = texture(uHigh, mapUv);
674
+ vec4 low = texture(uLow, mapUv);
675
+ vec2 packed = high.rg * 255.0 * 256.0 + low.rg * 255.0;
676
+ vec2 displacement =
677
+ (packed / 65535.0 - 0.5) * ${pL.toFixed(1)} * uScale * uOpacity;
678
+ displacement.y = -displacement.y;
679
+ vec2 samplePixel = fragment + displacement;
680
+ float softness = high.b * uOpacity;
681
+ vec4 sharp = scene(samplePixel);
682
+ if (softness <= 0.01) {
683
+ outColor = sharp;
684
+ return;
685
+ }
686
+ vec2 offset = vec2(0.72) * uPixelRatio * softness;
687
+ vec4 soft = (
688
+ scene(samplePixel + vec2(offset.x, offset.y))
689
+ + scene(samplePixel + vec2(-offset.x, offset.y))
690
+ + scene(samplePixel + vec2(offset.x, -offset.y))
691
+ + scene(samplePixel - offset)
692
+ ) * 0.25;
693
+ outColor = mix(sharp, soft, softness * 0.72);
694
+ }`;function LL(e,t,n){let r=e.createShader(t);if(!r)throw Error(`Unable to create the black-hole shader.`);if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){let t=e.getShaderInfoLog(r)||`The black-hole shader did not compile.`;throw e.deleteShader(r),Error(t)}return r}function RL(e,t){let n=LL(e,e.VERTEX_SHADER,ML),r=LL(e,e.FRAGMENT_SHADER,t),i=e.createProgram();if(!i)throw Error(`Unable to create the black-hole program.`);if(e.attachShader(i,n),e.attachShader(i,r),e.linkProgram(i),e.deleteShader(n),e.deleteShader(r),!e.getProgramParameter(i,e.LINK_STATUS)){let t=e.getProgramInfoLog(i)||`The black-hole program did not link.`;throw e.deleteProgram(i),Error(t)}return i}function zL(e){let t=!!window.__FARMING_E2E__,n=e.getContext(`webgl2`,{alpha:!0,antialias:!1,premultipliedAlpha:!1,powerPreference:`high-performance`,preserveDrawingBuffer:t});if(!n)throw Error(`WebGL 2 is required for the black-hole appearance.`);let r=n,i=RL(r,PL),a=r.getUniformLocation(i,`uResolution`),o=r.getUniformLocation(i,`uTime`),s=r.getUniformLocation(i,`uOpacity`),c=r.getUniformLocation(i,`uTemperature`),l=r.getUniformLocation(i,`uInclination`),u=r.getUniformLocation(i,`uRoll`),d=r.getUniformLocation(i,`uInnerRadius`),f=r.getUniformLocation(i,`uOuterRadius`),p=r.getUniformLocation(i,`uDiskOpacity`),m=r.getUniformLocation(i,`uDoppler`),h=r.getUniformLocation(i,`uBeam`),g=r.getUniformLocation(i,`uGain`),_=r.getUniformLocation(i,`uContrast`),v=r.getUniformLocation(i,`uWind`),y=r.getUniformLocation(i,`uSpeed`),b=r.getUniformLocation(i,`uExposure`),x=r.getUniformLocation(i,`uStarField`),S=r.getUniformLocation(i,`uFilamentDetail`),C=r.getUniformLocation(i,`uMass`),w=r.getUniformLocation(i,`uDiskFeed`),T=r.getUniformLocation(i,`uHawking`),E=r.getUniformLocation(i,`uFinalBurst`),D=0,O=.68,k=new Uint8Array,A=0,j=0,M=0,N=t?r.getExtension(`EXT_disjoint_timer_query_webgl2`):null,P=[],F=[];t&&(e.dataset.radiationProbe=`armed`,e.dataset.gpuTimer=N?`warming`:`unavailable`),r.useProgram(i);function ee(){if(!N)return;for(;P.length>0;){let e=P[0];if(!e||!r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE))break;P.shift();let t=r.getParameter(N.GPU_DISJOINT_EXT),n=Number(r.getQueryParameter(e,r.QUERY_RESULT));r.deleteQuery(e),!(t||!Number.isFinite(n))&&(F.push(n/1e6),F.length>120&&F.shift())}if(F.length<24)return;let t=[...F].sort((e,t)=>e-t),n=t[Math.ceil(t.length*.95)-1]??0,i=F.reduce((e,t)=>e+t,0)/F.length;e.dataset.gpuTimer=`sampled`,e.dataset.gpuSamples=String(F.length),e.dataset.gpuMeanMs=i.toFixed(3),e.dataset.gpuP95Ms=n.toFixed(3)}return{resize(t){let n=Math.min(2,Math.max(1,window.devicePixelRatio||1)),r=Math.max(512,Math.round(t*n*SL)),i=Math.round(Math.min(xL,r)/16)*16;O=qL(.68,.52,GL(WL((r/xL-1)/.5,0,1))),e.style.width=`${t}px`,e.style.height=`${t}px`,D!==i&&(D=i,e.width=i,e.height=i)},draw(n,D,F,I){ee(),r.viewport(0,0,e.width,e.height),r.useProgram(i),r.uniform2f(a,e.width,e.height),r.uniform1f(o,n),r.uniform1f(s,D),r.uniform1f(c,F.temperature),r.uniform1f(l,F.inclination),r.uniform1f(u,F.roll),r.uniform1f(d,F.innerRadius),r.uniform1f(f,F.outerRadius),r.uniform1f(p,F.diskOpacity),r.uniform1f(m,F.doppler),r.uniform1f(h,F.beam),r.uniform1f(g,F.gain),r.uniform1f(_,F.contrast),r.uniform1f(v,F.wind),r.uniform1f(y,F.speed),r.uniform1f(b,F.exposure),r.uniform1f(x,F.starField),r.uniform1f(S,O),r.uniform1f(C,I.mass),r.uniform1f(w,I.diskFeed),r.uniform1f(T,I.hawking),r.uniform1f(E,I.burst),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT);let L=N&&P.length<8?r.createQuery():null;if(L&&N&&r.beginQuery(N.TIME_ELAPSED_EXT,L),r.drawArrays(r.TRIANGLES,0,3),L&&N&&(r.endQuery(N.TIME_ELAPSED_EXT),P.push(L)),t&&I.hawking>.02&&performance.now()>=A){let t=e.width*e.height*4;k.length!==t&&(k=new Uint8Array(t)),r.readPixels(0,0,e.width,e.height,r.RGBA,r.UNSIGNED_BYTE,k);let n=e.width/2,i=e.height/2,a=Math.min(e.width,e.height)*.09,o=Math.min(e.width,e.height)*.49,s=new Uint16Array(48),c=0;for(let t=0;t<e.height;t+=2)for(let r=0;r<e.width;r+=2){let l=r+.5-n,u=t+.5-i,d=Math.hypot(l,u);if(d<a||d>o)continue;let f=(t*e.width+r)*4,p=k[f+3]??0,m=((k[f]??0)+(k[f+1]??0)+(k[f+2]??0))/3;if(p<18||m<28)continue;c+=1;let h=Math.atan2(u,l)+Math.PI,g=Math.min(47,Math.floor(h/(Math.PI*2)*48));s[g]=(s[g]??0)+1}let l=Array.from(s).filter(e=>e>=3).length;j=Math.max(j,c),M=Math.max(M,l),e.dataset.radiationInkPixels=String(j),e.dataset.radiationCoveredSectors=String(M),e.dataset.radiationProbe=`sampled`,A=performance.now()+120}},destroy(){for(let e of P)r.deleteQuery(e);r.deleteProgram(i),r.getExtension(`WEBGL_lose_context`)?.loseContext()}}}function BL(e){let t=document.createElement(`canvas`),n=Math.round(dL*Math.min(2,Math.max(1,window.devicePixelRatio||1)));t.width=n,t.height=n;let r=t.getContext(`webgl2`,{alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!0});if(!r)throw Error(`WebGL 2 is required for black-hole refraction.`);let i=RL(r,FL);return r.useProgram(i),r.uniform2f(r.getUniformLocation(i,`uResolution`),n,n),r.uniform1f(r.getUniformLocation(i,`uByte`),e),r.viewport(0,0,n,n),r.drawArrays(r.TRIANGLES,0,3),r.deleteProgram(i),t}function VL(){let e=Math.min(2,Math.max(1,window.devicePixelRatio||1)),t=new Map,n=0;return document.querySelectorAll(bL).forEach(r=>{let i=r.getBoundingClientRect();if(i.width<=0||i.height<=0||i.right<=0||i.bottom<=0||i.left>=window.innerWidth||i.top>=window.innerHeight)return;n+=1;let a=r.currentSrc||r.src;if(!a||t.has(a)||!r.complete||r.naturalWidth<=0||r.naturalHeight<=0)return;let o=document.createElement(`canvas`);o.width=Math.max(1,Math.round(i.width*e)),o.height=Math.max(1,Math.round(i.height*e));let s=o.getContext(`2d`);if(s)try{s.drawImage(r,0,0,o.width,o.height),t.set(a,o.toDataURL(`image/png`))}catch{}}),{sources:t,visibleCount:n}}async function HL(){let t=window;if(t.__FARMING_E2E__&&(t.__farmingBlackHoleCaptureFailures??0)>0)throw t.__farmingBlackHoleCaptureFailures=Math.max(0,(t.__farmingBlackHoleCaptureFailures??0)-1),Error(`Synthetic initial black-hole snapshot failure.`);let n=window.innerWidth,r=window.innerHeight,i=Math.min(2,Math.max(1,window.devicePixelRatio||1)),a=performance.now(),{default:o}=await s(async()=>{let{default:t}=await import(`./html2canvas-DsczWxBa.js`).then(t=>e(t.default));return{default:t}},__vite__mapDeps([19,1])),c=Array.from(document.styleSheets).flatMap(e=>{if(!e.href)return[];try{let t=Array.from(e.cssRules).map(e=>e.cssText).join(`
695
+ `);return t.includes(`body.code-mode[data-appearance=`)&&t.includes(`color-scheme: dark`)?[{href:e.href,cssText:t,media:e.ownerNode?.media??``}]:[]}catch{return[]}}),l=getComputedStyle(document.body).backgroundColor||`#101418`,u=Yy(),d=VL(),f=0,p=0,m=0,h=``;try{let e=await o(document.body,{allowTaint:!1,backgroundColor:l,foreignObjectRendering:!1,height:r,ignoreElements:e=>e.closest(yL)!==null||e.tagName===`SCRIPT`||e.tagName===`NOSCRIPT`||e.tagName===`VIDEO`||e.tagName===`BROWSER-MCP-CONTAINER`,imageTimeout:500,logging:!1,onclone:e=>{let t=e.body;t.className=document.body.className,t.dataset.appearance=document.body.dataset.appearance??`light`,c.forEach(t=>{let n=Array.from(e.querySelectorAll(`link[rel="stylesheet"]`)).find(e=>e.href===t.href);if(!n)return;let r=e.createElement(`style`);r.dataset.farmingAppearanceSnapshot=``,r.media=t.media,r.textContent=t.cssText,n.replaceWith(r)}),h=getComputedStyle(t).backgroundColor;let i=Array.from(e.querySelectorAll(yL));f=i.length,i.forEach(e=>e.remove()),p=e.querySelectorAll(yL).length,t.style.width=`${n}px`,t.style.height=`${r}px`,t.style.margin=`0`,t.style.overflow=`hidden`,e.querySelectorAll(bL).forEach(e=>{let t=e.currentSrc||e.src,n=d.sources.get(t);n&&(e.removeAttribute(`srcset`),e.src=n,m+=1)}),e.querySelectorAll(`[data-pet-xterm-snapshot]`).forEach(e=>{e.style.visibility=`visible`})},removeContainer:!0,scale:i,scrollX:0,scrollY:0,useCORS:!0,width:n,windowHeight:r,windowWidth:n,x:0,y:0});e.dataset.captureMs=String(Math.round(performance.now()-a)),e.dataset.excludedPetElements=String(f),e.dataset.remainingPetElements=String(p),e.dataset.visibleFileIcons=String(d.visibleCount),e.dataset.rasterizedFileIcons=String(m),e.dataset.clonedBodyBackground=h,e.dataset.appearanceStylesheets=String(c.length);let t=e.getContext(`2d`,{willReadFrequently:!0});if(t){let n=t.getImageData(0,0,1,1).data;e.dataset.cornerLuminance=String(Math.round(.2126*(n[0]??0)+.7152*(n[1]??0)+.0722*(n[2]??0)))}return e}finally{u()}}function UL(e,t,n){let r=e.getContext(`webgl2`,{alpha:!1,antialias:!1,premultipliedAlpha:!1,powerPreference:`high-performance`});if(!r)throw Error(`WebGL 2 is required for black-hole refraction.`);let i=RL(r,IL),a=r.getUniformLocation(i,`uResolution`),o=r.getUniformLocation(i,`uCenter`),s=r.getUniformLocation(i,`uScale`),c=r.getUniformLocation(i,`uOpacity`),l=r.getUniformLocation(i,`uPixelRatio`),u=[],d=(e,t)=>{let n=r.createTexture();if(!n)throw Error(`Unable to create the black-hole scene texture.`);return u.push(n),r.activeTexture(r.TEXTURE0+e),r.bindTexture(r.TEXTURE_2D,n),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!0),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t),n};r.useProgram(i);let f=d(0,t);d(1,t),d(2,n),t.getContext(`webgl2`)?.getExtension(`WEBGL_lose_context`)?.loseContext(),n.getContext(`webgl2`)?.getExtension(`WEBGL_lose_context`)?.loseContext(),r.uniform1i(r.getUniformLocation(i,`uScene`),0),r.uniform1i(r.getUniformLocation(i,`uHigh`),1),r.uniform1i(r.getUniformLocation(i,`uLow`),2);let p=0,m=(e,t,n)=>{r.activeTexture(r.TEXTURE0+e),r.bindTexture(r.TEXTURE_2D,t),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,n)};return{setScene(t){p+=1,e.dataset.sceneGeneration=String(p);let n=Math.min(2,Math.max(1,window.devicePixelRatio||1));e.width=Math.round(window.innerWidth*n),e.height=Math.round(window.innerHeight*n),e.style.width=`${window.innerWidth}px`,e.style.height=`${window.innerHeight}px`,m(0,f,t),e.dataset.captureMs=t instanceof HTMLCanvasElement?t.dataset.captureMs:``,e.dataset.excludedPetElements=t instanceof HTMLCanvasElement?t.dataset.excludedPetElements??``:``,e.dataset.remainingPetElements=t instanceof HTMLCanvasElement?t.dataset.remainingPetElements??``:``,e.dataset.visibleFileIcons=t instanceof HTMLCanvasElement?t.dataset.visibleFileIcons??``:``,e.dataset.rasterizedFileIcons=t instanceof HTMLCanvasElement?t.dataset.rasterizedFileIcons??``:``,e.dataset.cornerLuminance=t instanceof HTMLCanvasElement?t.dataset.cornerLuminance??``:``,e.dataset.clonedBodyBackground=t instanceof HTMLCanvasElement?t.dataset.clonedBodyBackground??``:``,e.dataset.appearanceStylesheets=t instanceof HTMLCanvasElement?t.dataset.appearanceStylesheets??``:``,e.style.opacity=`1`},draw(t){if(!e.width||!e.height)return;let n=e.width/window.innerWidth;r.viewport(0,0,e.width,e.height),r.useProgram(i),r.uniform2f(a,e.width,e.height),r.uniform2f(o,t.centerX*n,(window.innerHeight-t.centerY)*n),r.uniform1f(s,t.scale*t.mass*n),r.uniform1f(c,t.lensOpacity),r.uniform1f(l,n),r.drawArrays(r.TRIANGLES,0,3)},destroy(){u.forEach(e=>r.deleteTexture(e)),r.deleteProgram(i),r.getExtension(`WEBGL_lose_context`)?.loseContext()}}}function WL(e,t,n){return Math.min(n,Math.max(t,e))}function GL(e){let t=WL(e,0,1);return t*t*t*(t*(t*6-15)+10)}function KL(e){let t=e();if(!t)return{x:28,y:window.innerHeight-28};let n=t.getBoundingClientRect();return{x:n.left+n.width*.72,y:n.top+n.height*.5}}function qL(e,t,n){return e+(t-e)*n}function JL(e){let t=window.innerWidth/window.innerHeight;return qL(Math.sqrt(EL*t/Math.PI),Math.sqrt(DL*t/Math.PI),e)*(OL/.08)*window.innerHeight/fL}var YL=[{phase:`zen`,temperature:7e3,inclination:1.45,roll:.15,innerRadius:3.5,outerRadius:7,diskOpacity:.4,doppler:.5,beam:2,gain:.5,contrast:.3,wind:3,speed:1.5,exposure:.7,starField:0,size:.9,motion:.16,lens:.86,diskRate:.42},{phase:`m87`,temperature:3800,inclination:.55,roll:-.3,innerRadius:2.2,outerRadius:6,diskOpacity:.45,doppler:.9,beam:3.5,gain:1.6,contrast:.4,wind:3,speed:2.5,exposure:1.1,starField:0,size:.93,motion:.24,lens:.92,diskRate:.58},{phase:`ember`,temperature:6500,inclination:.3,roll:0,innerRadius:3,outerRadius:10,diskOpacity:.5,doppler:.8,beam:2.5,gain:1,contrast:1.1,wind:7,speed:5,exposure:1,starField:0,size:.96,motion:.38,lens:.9,diskRate:.82},{phase:`gargantua`,temperature:4500,inclination:1.52,roll:.1,innerRadius:2.2,outerRadius:7,diskOpacity:.85,doppler:.35,beam:2,gain:1.4,contrast:.5,wind:7,speed:5,exposure:1.2,starField:0,size:.98,motion:.44,lens:.93,diskRate:.88},{phase:`inferno`,temperature:5500,inclination:1.5,roll:.35,innerRadius:1.8,outerRadius:8,diskOpacity:.9,doppler:.6,beam:2.5,gain:2.2,contrast:1.6,wind:7,speed:5,exposure:1.4,starField:0,size:1,motion:.72,lens:1,diskRate:1.2},{phase:`quasar`,temperature:15e3,inclination:1.3,roll:.35,innerRadius:3,outerRadius:9,diskOpacity:.35,doppler:1,beam:4,gain:1.2,contrast:1.3,wind:8,speed:5,exposure:.8,starField:0,size:.98,motion:.78,lens:1,diskRate:1.3},{phase:`blazar`,temperature:18e3,inclination:1.05,roll:.55,innerRadius:3,outerRadius:10,diskOpacity:.3,doppler:1,beam:5,gain:1,contrast:1.5,wind:9,speed:6,exposure:.75,starField:0,size:.96,motion:.84,lens:1,diskRate:1.38},{phase:`cooling`,temperature:5500,inclination:1.5,roll:.35,innerRadius:1.8,outerRadius:8,diskOpacity:.9,doppler:.6,beam:2.5,gain:2.2,contrast:1.6,wind:7,speed:5,exposure:1.4,starField:0,size:.94,motion:.32,lens:.9,diskRate:.68}];function XL(e,t,n,r){return{phase:r,temperature:qL(e.temperature,t.temperature,n),inclination:qL(e.inclination,t.inclination,n),roll:qL(e.roll,t.roll,n),innerRadius:qL(e.innerRadius,t.innerRadius,n),outerRadius:qL(e.outerRadius,t.outerRadius,n),diskOpacity:qL(e.diskOpacity,t.diskOpacity,n),doppler:qL(e.doppler,t.doppler,n),beam:qL(e.beam,t.beam,n),gain:qL(e.gain,t.gain,n),contrast:qL(e.contrast,t.contrast,n),wind:qL(e.wind,t.wind,n),speed:qL(e.speed,t.speed,n),exposure:qL(e.exposure,t.exposure,n),starField:qL(e.starField,t.starField,n),size:qL(e.size,t.size,n),motion:qL(e.motion,t.motion,n),lens:qL(e.lens,t.lens,n),diskRate:qL(e.diskRate,t.diskRate,n)}}function ZL(e,t){let n=YL[0],r=YL[1],i=YL[2],a=YL[3],o=YL[4],s=YL[5],c=YL[6],l=YL[7],u=$L(e,t,20)>=0?[n,r]:[r,n],d=$L(e,t,21)>=0?[i,a]:[a,i],f=$L(e,t,22)>=0?[s,c]:[c,s];return[...u,...d,o,...f,l]}function QL(e,t,n){let r=ZL(n,0),i=WL(e/CL,0,1);if(i<1){let e=GL(i),n=r[0];return XL(t,n,e,`birth`)}let a=e-CL,o=Math.floor(a/wL),s=(a-o*wL)/wL,c=o===0?r:ZL(n,o),l=ZL(n,o+1),u=s*c.length,d=Math.floor(u),f=c[d],p=d===c.length-1?l[0]:c[d+1],m=GL(u-d),h=s*Math.PI*2,g=.7*Math.sin(h)**3+.3*Math.sin(h*2)**3,_=.65*Math.sin(h)**3+.35*Math.sin(h*2)**3,v=XL(f,p,m,m<.5?f.phase:p.phase);return v.size=Math.min(1,v.size*(1+_*.01)),v.motion=WL(v.motion+_*.025,0,1),v.lens=WL(v.lens+g*.012,0,1),v.diskRate*=1+_*.025,v}function $L(e,t,n){let r=(t|0)^e^Math.imul(n+1,2654435769);return r=Math.imul(r^r>>>16,569420461),r=Math.imul(r^r>>>15,1935289751),((r^r>>>15)>>>0)/2147483647.5-1}function eR(e,t,n){let r=Math.floor(t),i=GL(t-r);return qL($L(e,r,n),$L(e,r+1,n),i)}function tR(e,t,n,r){return{x:.72*eR(e,t*n,r)+.28*eR(e,t*n*2.13+11.7,r+1),y:.72*eR(e,t*n*.91+7.3,r+2)+.28*eR(e,t*n*1.87+19.1,r+3)}}function nR(e){if(e<=0)return{progress:0,mass:1,diskFeed:1,hawking:0,burst:0,body:1,lens:1};let t=WL((e-.16)/.76,0,1);return{progress:e,mass:Math.max(.035,(1-t)**(1/3)),diskFeed:1-GL(e/.32),hawking:GL((e-.12)/.78),burst:WL((e-.9)/.1,0,1),body:1-GL((e-.955)/.035),lens:1-GL((e-.82)/.12)}}function rR(e,t,n,r){let i=WL(e/CL,0,1),a=window.innerWidth,o=window.innerHeight,s=a/o,c=JL(i)*t.size,l=fL*c/o,u=KL(r),d={x:u.x/a,y:u.y/o},f=Math.min(l*qL(1.45,.9,i),.5*(1-kL-.03)),p=f/s,m={x:Math.min(p,.5),y:f},h={x:Math.max(.5,1-p),y:Math.max(f,1-(kL+.03+f))},g={x:WL(d.x,m.x,h.x),y:WL(d.y,m.y,h.y)},_=qL(.06,1,i),v={x:qL(g.x,m.x,_),y:m.y},y={x:h.x,y:qL(g.y,h.y,_)},b={x:Math.max((y.x-v.x)*.5,0),y:Math.max((y.y-v.y)*.5,0)},x=(.01+.03*i)*qL(.65,1.15,t.motion),S={x:Math.min(x,Math.max(b.x*.35,.006)),y:Math.min(x,Math.max(b.y*.35,.006))},C={x:Math.max(b.x-S.x,0),y:Math.max(b.y-S.y,0)},w=tR(n,e,AL,0),T=tR(n,e,jL,4),E={x:qL(w.x,T.x,t.motion),y:qL(w.y,T.y,t.motion)},D=tR(n,e,.11,8),O={x:(v.x+y.x)*.5+E.x*C.x+S.x*D.x,y:(v.y+y.y)*.5+E.y*C.y+S.y*D.y},k=GL(i),A=GL(WL(e/(CL*.55),0,1));return{centerX:qL(d.x,O.x,k)*a,centerY:qL(d.y,O.y,k)*o,scale:c,mass:1,bodyOpacity:A,lensOpacity:A*t.lens}}function iR({canvas:e,compositor:t,homeElement:n,onError:r,onReady:i}){let a,o;try{a=zL(e),o=UL(t,BL(0),BL(1))}catch(e){return r(e instanceof Error?e.message:String(e)),{setActive(){},beginExit(e){e()},destroy(){}}}let s=!0,c=!1,l=!1,u=null,d=15,f=!0,p=null,m=0,h=0,g=18.5,_=!1,v=null,y=0,b=window,x=performance.now(),S=crypto.getRandomValues(new Uint32Array(1))[0]??0,C=b.__farmingBlackHoleEvolutionSeed,w=b.__FARMING_E2E__&&Number.isInteger(C)?Math.trunc(C)>>>0:S,T=ZL(w,0),E=T[0],D=$L(S,0,12),O={...E,phase:`birth`,size:.72+D*.04,motion:.06,lens:E.lens*(.69+D*.07),diskRate:E.diskRate*(.55+D*.07)};e.dataset.introSeconds=String(CL),e.dataset.cycleSeconds=String(wL),e.dataset.cycleOrder=T.map(e=>e.phase).join(`,`),e.dataset.nextCycleOrder=ZL(w,1).map(e=>e.phase).join(`,`),e.dataset.birthPreset=E.phase;let k=()=>{m&&cancelAnimationFrame(m),m=0},A=()=>{k();let e=p;p=null,e?.()},j=()=>{c||!s||document.hidden||m||(m=requestAnimationFrame(F))},M=()=>{v!==null&&(window.clearTimeout(v),v=null)},N=()=>{c||l||_||!s||document.hidden||(M(),_=!0,t.dataset.refreshState=`initial-capturing`,HL().then(e=>{c||(o.setScene(e),l=!0,y=0,t.dataset.refreshState=`idle`,delete t.dataset.refreshError,i(),j())}).catch(e=>{if(c)return;y+=1;let n=e instanceof Error?e.message:String(e);t.dataset.refreshState=`initial-retry-wait`,t.dataset.refreshError=n,r(n);let i=Math.min(vL,_L*2**Math.min(y-1,4));v=window.setTimeout(()=>{v=null,N()},i)}).finally(()=>{_=!1}))},P=t=>{let n=Math.min(2,Math.max(1,window.devicePixelRatio||1)),r=e=>Math.round(e*n)/n,i=r(uL*t.scale);e.style.left=`${r(t.centerX-i/2)}px`,e.style.top=`${r(t.centerY-i/2)}px`,e.style.opacity=String(t.bodyOpacity),a.resize(i)};function F(r){if(m=0,c||!s||document.hidden)return;let i=b.__FARMING_E2E__?b.__farmingBlackHoleElapsedSeconds:void 0,p=Number.isFinite(i)?Number(i):(r-x)/1e3,_=QL(p,O,w);e.dataset.macroPhase=_.phase,e.dataset.macroSize=_.size.toFixed(4),e.dataset.macroTemperature=_.temperature.toFixed(1),e.dataset.macroInclination=_.inclination.toFixed(4),e.dataset.macroOuterRadius=_.outerRadius.toFixed(3);let v=nR(0),y=rR(p,_,S,n);if(u!==null){let e=WL((r-u)/(d*1e3),0,1);t.dataset.exitProgress=e.toFixed(4),v=nR(e),t.dataset.evaporationPhase=e<.2?`disk-quench`:e<.82?`blue-shift`:e<.9?`photon-collapse`:`final-release`,t.dataset.hawking=v.hawking.toFixed(4),t.dataset.finalBurst=v.burst.toFixed(4);let i=(u-x)/1e3+.45*(1-Math.exp(-(r-u)/450)),a=QL(i,O,w);y=rR(i,a,S,n);let o=KL(n),s=f?GL((e-.8)/.14):0;if(y={...y,centerX:qL(y.centerX,o.x,s),centerY:qL(y.centerY,o.y,s),mass:v.mass,bodyOpacity:v.body,lensOpacity:v.lens*a.lens},e>=1){A();return}}if(h){let e=qL(_.diskRate,.08,GL(v.progress/.3));g+=Math.min(.1,(r-h)/1e3)*e}h=r,P(y),l&&o.draw(y),a.draw(g,y.bodyOpacity,_,v),j()}N();let ee=()=>{document.hidden?(k(),h=0):s&&(N(),j())};return document.addEventListener(`visibilitychange`,ee),{setActive(e){s=e,s?(N(),j()):(k(),h=0)},beginExit(e,t=15,n=!0,r=0){u!==null||c||(d=Math.max(.3,t),u=performance.now()-WL(r,0,d)*1e3,f=n,p=e,j())},destroy(){c=!0,k(),M(),document.removeEventListener(`visibilitychange`,ee),t.style.opacity=`0`,o.destroy(),a.destroy()}}}var aR={0:[`a`,`b`,`c`,`d`,`e`,`f`],1:[`b`,`c`],2:[`a`,`b`,`d`,`e`,`g`],3:[`a`,`b`,`c`,`d`,`g`],4:[`b`,`c`,`f`,`g`],5:[`a`,`c`,`d`,`f`,`g`],6:[`a`,`c`,`d`,`e`,`f`,`g`],7:[`a`,`b`,`c`],8:[`a`,`b`,`c`,`d`,`e`,`f`,`g`],9:[`a`,`b`,`c`,`d`,`f`,`g`]};function oR(e,t){let n=Math.max(0,Math.ceil((e-t)/1e3)),r=Math.floor(n/60),i=n%60;return`${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`}function sR({value:e}){return(0,K.jsx)(`time`,{className:`code-pet-seven-segment-time`,"aria-label":e,dateTime:`PT${e.replace(`:`,`M`)}S`,children:(0,K.jsx)(`span`,{className:`code-pet-seven-segment-digits`,"aria-hidden":`true`,children:Array.from(e).map((e,t)=>{if(e===`:`)return(0,K.jsxs)(`span`,{className:`code-pet-seven-segment-colon`,children:[(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{})]},`colon-${t}`);let n=aR[e]??[];return(0,K.jsx)(`span`,{className:`code-pet-seven-segment-digit`,children:[`a`,`b`,`c`,`d`,`e`,`f`,`g`].map(e=>(0,K.jsx)(`i`,{className:`segment segment-${e}${n.includes(e)?` lit`:``}`},e))},`${e}-${t}`)})})})}function cR(){let e=document.createElement(`canvas`);e.width=520,e.height=88;let t=e.getContext(`2d`);if(!t)return null;let n=t.createImageData(520,88);for(let e=0;e<88;e+=1)for(let t=0;t<520;t+=1){let r=t-(t<44?44:t>476?476:t),i=e-44,a=Math.sqrt(r*r+i*i),o=44-a,s=Math.max(0,Math.min(1,o/11)),c=s*s*(3-2*s),l=Math.max(1,a),u=r/l,d=i/l,f=(1-c)*(o>=0),p=(e*520+t)*4;n.data[p]=Math.round(128+u*f*56),n.data[p+1]=Math.round(128+d*f*56),n.data[p+2]=128,n.data[p+3]=255}return t.putImageData(n,0,0),e.toDataURL(`image/png`)}function lR({statusLabel:e,endLabel:t,errorLabel:n,restUntil:r,active:i,onEnd:a}){let[o,s]=(0,G.useState)(Date.now),[c,l]=(0,G.useState)(null),[u,d]=(0,G.useState)(!1),f=(0,G.useRef)(null),p=(0,G.useRef)(null),m=(0,G.useRef)(null),h=(0,G.useRef)(null),g=(0,G.useRef)(!1),_=`code-pet-status-glass-${(0,G.useId)().replace(/:/g,``)}`;(0,G.useEffect)(()=>{if(!i)return;s(Date.now());let e=window.setInterval(()=>{document.visibilityState!==`hidden`&&s(Date.now())},1e3);return()=>window.clearInterval(e)},[i,r]),(0,G.useEffect)(()=>{let e=f.current,t=p.current;if(!e||!t)return;let n=iR({canvas:e,compositor:t,homeElement:()=>document.querySelector(`.code-product-mark`)??document.querySelector(`.code-product-pet-anchor`),onError:e=>l(e),onReady:()=>l(null)});return h.current=n,n.setActive(i),()=>{n.destroy(),h.current=null}},[]),(0,G.useEffect)(()=>{h.current?.setActive(i)},[i]),(0,G.useEffect)(()=>{let e=cR();e&&m.current?.setAttribute(`href`,e)},[]);let v=(e=TL,t=!1,n=0)=>{g.current||(g.current=!0,d(!0),h.current?.beginExit(a,e,t,n))};if((0,G.useEffect)(()=>{if(!i)return;let e=r-15*1e3,t=window.setTimeout(()=>v(15,!0,Math.max(0,(Date.now()-e)/1e3)),Math.max(0,e-Date.now()));return()=>window.clearTimeout(t)},[i,r]),(0,G.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.preventDefault(),v())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)}),typeof document>`u`)return null;let y=oR(r,o),b={"--code-pet-status-glass-filter":`url(#${_})`};return(0,nE.createPortal)((0,K.jsxs)(`section`,{className:`code-pet-black-hole-rest${u?` exiting`:``}`,"data-pet-ui":!0,"data-testid":`pet-rest-scene`,"data-pet-appearance":`black-hole`,role:`dialog`,"aria-modal":`false`,"aria-label":e,children:[(0,K.jsx)(`svg`,{className:`code-pet-black-hole-filters`,"aria-hidden":`true`,children:(0,K.jsx)(`defs`,{children:(0,K.jsxs)(`filter`,{id:_,x:`0%`,y:`0%`,width:`100%`,height:`100%`,primitiveUnits:`objectBoundingBox`,colorInterpolationFilters:`sRGB`,children:[(0,K.jsx)(`feImage`,{ref:m,x:`0`,y:`0`,width:`1`,height:`1`,result:`edge-map`,preserveAspectRatio:`none`}),(0,K.jsx)(`feDisplacementMap`,{in:`SourceGraphic`,in2:`edge-map`,scale:`0.016`,xChannelSelector:`R`,yChannelSelector:`G`})]})})}),(0,K.jsx)(`canvas`,{ref:p,className:`code-pet-black-hole-compositor`,"aria-hidden":`true`}),(0,K.jsx)(`canvas`,{ref:f,className:`code-pet-black-hole-canvas`,"aria-hidden":`true`}),(0,K.jsxs)(`div`,{className:`code-pet-black-hole-status`,style:b,children:[(0,K.jsxs)(`span`,{className:`code-pet-black-hole-status-label`,children:[c?n:e,c?null:(0,K.jsx)(`i`,{"aria-hidden":`true`,children:`·`})]}),(0,K.jsx)(sR,{value:y}),(0,K.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>v(),children:t}),c?(0,K.jsx)(`span`,{className:`code-pet-black-hole-error`,title:c,"aria-hidden":`true`}):null]})]}),document.body)}function uR(e,t){let n=Math.max(0,Math.ceil((e-t)/1e3)),r=Math.floor(n/60),i=n%60;return`${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`}function dR({title:e,body:t,endLabel:n,restUntil:r,active:i,onEnd:a}){let[o,s]=(0,G.useState)(Date.now),c=(0,G.useRef)(null),l=`code-pet-glass-rest-${(0,G.useId)().replace(/:/g,``)}`;return(0,G.useEffect)(()=>{if(!i)return;s(Date.now());let e=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(e)},[i,r]),(0,G.useEffect)(()=>{let e=document.getElementById(`root`),t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=e?.inert??!1,r=e?.getAttribute(`aria-hidden`)??null;e&&(e.inert=!0,e.setAttribute(`aria-hidden`,`true`));let i=window.requestAnimationFrame(()=>{c.current?.focus({preventScroll:!0})}),o=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopImmediatePropagation(),a())};return window.addEventListener(`keydown`,o,!0),()=>{window.cancelAnimationFrame(i),window.removeEventListener(`keydown`,o,!0),e&&(e.inert=n,r===null?e.removeAttribute(`aria-hidden`):e.setAttribute(`aria-hidden`,r)),t?.isConnected&&t.focus({preventScroll:!0})}},[a]),typeof document>`u`?null:(0,nE.createPortal)((0,K.jsx)(`section`,{className:`code-pet-glass-rest-overlay`,"data-pet-ui":!0,"data-testid":`pet-rest-scene`,"data-pet-appearance":`glass`,role:`dialog`,"aria-modal":`true`,"aria-label":e,"aria-describedby":l,children:(0,K.jsxs)(`div`,{className:`code-pet-glass-rest-content`,children:[(0,K.jsx)(`time`,{className:`code-pet-glass-rest-time`,children:uR(r,o)}),(0,K.jsx)(`strong`,{children:e}),(0,K.jsx)(`p`,{id:l,children:t}),(0,K.jsx)(`div`,{className:`code-pet-glass-rest-actions`,children:(0,K.jsx)(`button`,{ref:c,type:`button`,onClick:a,children:n})})]})}),document.body)}function fR({title:e,body:t,closeLabel:n,testId:r,actions:i,announcement:a,error:o,children:s,onClose:c}){return(0,K.jsxs)(`section`,{className:`code-pet-bubble`,"data-pet-ui":!0,"data-testid":r,role:`dialog`,"aria-modal":`false`,"aria-label":e,children:[a?(0,K.jsx)(`span`,{className:`code-visually-hidden`,role:`status`,"aria-live":`polite`,children:a}):null,(0,K.jsx)(`button`,{type:`button`,className:`code-pet-close`,"aria-label":n,onClick:c,children:`×`}),(0,K.jsx)(`div`,{className:`code-pet-bubble-heading`,children:(0,K.jsx)(`strong`,{children:e})}),(0,K.jsx)(`p`,{children:t}),o?(0,K.jsx)(`small`,{className:`code-pet-error`,role:`alert`,children:o}):null,s,i.length>0&&(0,K.jsx)(`div`,{className:`code-pet-actions`,children:i.map(e=>(0,K.jsx)(`button`,{type:`button`,className:e.primary?`primary`:void 0,onClick:e.onClick,children:e.label},e.label))})]})}var pR={appearance:`system`,codeContentFontSize:14,composerFollowUpBehavior:`queue`,language:`en`};function mR(e){return e===`system`||e===`light`||e===`dark`?e:pR.appearance}function hR(e){return e===`zh`||e===`en`?e:pR.language}function gR(e){return e===`steer`?`steer`:`queue`}function _R(e){return e===`system`?typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:e}function vR(e){return _R(e)===`dark`?`black-hole`:`glass`}function yR(e){let[t,n]=(0,G.useState)(()=>vR(e));return(0,G.useEffect)(()=>{let t=()=>n(vR(e));if(t(),e!==`system`)return;let r=window.matchMedia(`(prefers-color-scheme: dark)`);return r.addEventListener(`change`,t),()=>r.removeEventListener(`change`,t)},[e]),t}var bR=1e3;function xR(e){let t=RI(e);return t!==null&&t>0?t:null}function SR(e){return e.target instanceof Element&&!!e.target.closest(`[data-pet-ui]`)}function CR(e){return![`Shift`,`Control`,`Alt`,`Meta`,`CapsLock`].includes(e.key)}function wR(e){let t=xR(e);return t===null?null:cL(t)??XI(t)}function TR(e,t=!1){let[n,r]=(0,G.useState)(()=>wR(e)),[i,a]=(0,G.useState)(()=>typeof document>`u`||document.visibilityState!==`hidden`),[o,s]=(0,G.useState)(!1),c=(0,G.useRef)(n),l=(0,G.useRef)(t),u=(0,G.useRef)(t),d=(0,G.useRef)(null),f=(0,G.useRef)(null),p=(0,G.useRef)(!1);l.current=t;let m=(0,G.useCallback)(e=>{p.current!==e&&(p.current=e,s(e))},[]),h=(0,G.useCallback)((e,t=!0)=>{let n=lL(e);t&&m(!n)},[m]),g=(0,G.useCallback)((e,t=!0,n=!0)=>{c.current=e,h(e,n),t&&r(e)},[h]),_=(0,G.useCallback)(()=>{f.current!==null&&(window.clearTimeout(f.current),f.current=null)},[]),v=(0,G.useCallback)(()=>{let e=d.current;d.current=null;let t=c.current;if(e===null||t===null||l.current)return t;let n=iL(t);return t.phase!==`due`&&(n===null||e<n)?t:rL(t,{type:`interaction`,now:e})},[]),y=(0,G.useCallback)((e=!0,t=!0)=>{_();let n=c.current,r=v();return r!==n&&g(r,e,t),r},[_,g,v]);(0,G.useEffect)(()=>{let t=xR(e);_();let n=v();if(t===null){n===null?h(null,!1):g(null);return}if(n===null){g(XI(t));return}if(n.intervalSeconds!==t){g(eL(n,t,Date.now()));return}h(n)},[_,g,e,h,v]),(0,G.useEffect)(()=>{let e=u.current;if(u.current=t,e===t)return;_(),d.current=null;let n=c.current;!n||n.phase===`resting`||g(rL(n,{type:t?`background`:`foreground`,now:Date.now()}))},[_,g,t]),(0,G.useEffect)(()=>{if(n===null)return;let e=e=>{if(SR(e)||e instanceof KeyboardEvent&&!CR(e)||l.current)return;let t=Date.now(),n=c.current;if(!n)return;let r=iL(n);n.phase!==`due`&&(r===null||t<r)||(d.current=Math.max(d.current??0,t),f.current===null&&(f.current=window.setTimeout(()=>{f.current=null;let e=c.current,t=v();t!==e&&g(t)},bR)))};return window.addEventListener(`pointerdown`,e,!0),window.addEventListener(`keydown`,e,!0),window.addEventListener(`input`,e,!0),()=>{window.removeEventListener(`pointerdown`,e,!0),window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`input`,e,!0)}},[g,n!==null,v]),(0,G.useEffect)(()=>{let e=()=>{if(document.visibilityState===`hidden`){let e=y();e&&e.phase!==`resting`&&g(rL(e,{type:`background`,now:Date.now()})),a(!1);return}a(!0);let e=v();e&&!l.current&&g(rL(e,{type:`foreground`,now:Date.now()}))};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[g,y,v]),(0,G.useEffect)(()=>{!i||t||!n||n.phase!==`armed`&&n.backgroundedAt===null||g(rL(n,{type:`foreground`,now:Date.now()}))},[g,t,i,n]),(0,G.useEffect)(()=>{if(!i||!n||t&&n.phase!==`resting`)return;let e=iL(n);if(e===null)return;let r=window.setTimeout(()=>{_();let e=v();e&&(e.phase===`resting`||!l.current)&&g(rL(e,{type:`deadline`,now:Date.now()}))},Math.max(0,e-Date.now()));return()=>window.clearTimeout(r)},[_,g,t,i,n,v]),(0,G.useEffect)(()=>()=>{_();let e=v(),t=e&&e.phase!==`resting`?rL(e,{type:`background`,now:Date.now()}):e;c.current=t,h(t,!1)},[_,h,v]);let b=(0,G.useCallback)(e=>{_(),d.current=null;let t=c.current;t&&g(rL(t,{type:e,now:Date.now()}))},[_,g]);return{state:n,pageVisible:i,persistenceFailed:o,dismiss:(0,G.useCallback)(()=>b(`dismiss`),[b]),snooze:(0,G.useCallback)(()=>b(`snooze`),[b])}}var ER=`data-farming-pet-owner`,DR=`farming:pet-owner-change`,OR=30;function kR(){try{let e=JSON.parse(window.sessionStorage.getItem(`farmingPetRestReminderInvitationRuntime`)??`null`);if(e?.version===1&&typeof e.foregroundMs==`number`&&Number.isFinite(e.foregroundMs)&&e.foregroundMs>=0&&(e.foregroundStartedAt===null||typeof e.foregroundStartedAt==`number`&&Number.isFinite(e.foregroundStartedAt)))return{version:1,foregroundMs:e.foregroundMs,foregroundStartedAt:e.foregroundStartedAt}}catch{}return{version:1,foregroundMs:0,foregroundStartedAt:null}}function AR(e){let[t,n]=(0,G.useState)(!1);return(0,G.useEffect)(()=>{if(!e){n(!1);return}let t=AI(window.location.search,!!window.__FARMING_E2E__),r=kR(),i=null,a=()=>{try{window.sessionStorage.setItem(TI,JSON.stringify(r))}catch{}},o=e=>r.foregroundMs+(r.foregroundStartedAt===null?0:Math.max(0,e-r.foregroundStartedAt)),s=()=>{i!==null&&window.clearTimeout(i),i=null;let e=Date.now(),c=o(e);if(c>=t){r={version:1,foregroundMs:t,foregroundStartedAt:null},a(),n(!0);return}document.visibilityState!==`hidden`&&(r.foregroundStartedAt===null&&(r={...r,foregroundStartedAt:e},a()),i=window.setTimeout(s,t-c))},c=()=>{let e=Date.now();if(document.visibilityState===`hidden`){r={version:1,foregroundMs:Math.min(t,o(e)),foregroundStartedAt:null},a(),i!==null&&window.clearTimeout(i),i=null;return}s()};return s(),document.addEventListener(`visibilitychange`,c),()=>{document.removeEventListener(`visibilitychange`,c),i!==null&&window.clearTimeout(i),r.foregroundStartedAt!==null&&(r={version:1,foregroundMs:Math.min(t,o(Date.now())),foregroundStartedAt:null},a())}},[e]),t}function jR(e){let[t]=(0,G.useState)(()=>`pet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`),[n,r]=(0,G.useState)(!1);return(0,G.useLayoutEffect)(()=>{let e=()=>{r(document.documentElement.getAttribute(ER)===t)};return window.addEventListener(DR,e),document.documentElement.setAttribute(ER,t),e(),window.dispatchEvent(new Event(DR)),()=>{window.removeEventListener(DR,e),document.documentElement.getAttribute(ER)===t&&(document.documentElement.removeAttribute(ER),window.dispatchEvent(new Event(DR)))}},[t]),n?(0,K.jsx)(PR,{...e}):null}function MR(e,t){if(t<60)return e===`zh`?`${t} 秒`:`${t} sec`;let n=t/60;if(n%60==0){let t=n/60;return e===`zh`?`${t} 小时`:`${t} hr`}return e===`zh`?`${n} 分钟`:`${n} min`}function NR(e){let t=e===`zh`,n=MR(e,EI);return{startupTitle:t?`需要长时使用休息提醒吗?`:`Need a reminder during long Farming sessions?`,startupBody:t?`连续操作 Farming ${n}后提醒休息。之后可随时在设置的“Farming Pet”中调整或关闭。`:`Get a break reminder after ${n} of continuous Farming activity. You can adjust or turn it off anytime under “Farming Pet” in Settings.`,tryReminder:t?`试用一下`:`Try it`,disable:t?`不使用提醒`:`Don’t use reminders`,appearanceTitle:t?`选择休息提醒的样式`:`Choose a reminder style`,appearanceBody:t?`它只会在需要提醒休息时出现。之后可在设置的“Farming Pet”中更改。`:`It appears only when it is time for a break. You can change it later under “Farming Pet” in Settings.`,softGlow:t?`柔光`:`Soft glow`,softGlowHint:t?`温和的磨砂提示`:`A quiet frosted reminder`,defaultAppearance:t?`默认`:`Default`,blackHole:t?`黑洞`:`Black hole`,blackHoleHint:t?`更醒目的动态提示`:`A more noticeable animated reminder`,previewAppearance:e=>{let n=e===`black-hole`?t?`黑洞`:`black hole`:t?`柔光`:`soft glow`;return t?`预览${n}效果`:`Preview ${n}`},previewTitle:e=>e===`black-hole`?t?`黑洞预览`:`Black hole preview`:t?`柔光预览`:`Soft glow preview`,previewBody:t?`这是休息开始时看到的效果。`:`This is the scene shown when a break starts.`,endPreview:t?`结束预览`:`End preview`,dueTitle:t?`休息提醒`:`Break reminder`,dueAnnouncement:e=>{let n=PI(e),r=jI(e);return t?`休息提醒已出现。暂停操作 ${n} 秒后,开始 ${r} 分钟休息。`:`Break reminder shown. Pause for ${n} sec to start a ${r} min break.`},dueBody:(n,r)=>{let i=jI(n);return t?(0,K.jsxs)(K.Fragment,{children:[`已连续操作 Farming `,MR(e,n),`。`,(0,K.jsx)(`br`,{}),`暂停操作 `,(0,K.jsxs)(`strong`,{className:`code-pet-countdown`,children:[r,` 秒`]}),`后,开始 `,i,` 分钟休息。`]}):(0,K.jsxs)(K.Fragment,{children:[`Used Farming continuously for `,MR(e,n),`.`,(0,K.jsx)(`br`,{}),`Pause `,(0,K.jsxs)(`strong`,{className:`code-pet-countdown`,children:[r,` sec`]}),` for a `,i,` min break.`]})},cancelBreak:t?`取消`:`Cancel`,snooze:t?`10 分钟后`:`In 10 min`,restingTitle:t?`休息一下`:`Take a break`,restingBody:t?`让眼睛和注意力暂停片刻。`:`Pause for a moment and rest your eyes and attention.`,restingStatus:t?`休息中`:`Resting`,blackHoleError:t?`黑洞显示失败`:`Black hole unavailable`,restStartedAnnouncement:e=>{let n=jI(e);return t?`${n} 分钟休息已经开始。可随时选择结束休息。`:`Your ${n}-minute break has started. You can end it at any time.`},endBreak:t?`结束休息`:`End break`,settingsSaveFailed:t?`无法保存 Pet 设置,请重试。`:`Could not save Pet settings. Try again.`,runtimeSaveTitle:t?`Pet 计时无法保存`:`Pet timer cannot be saved`,runtimeSaveBody:t?`本次提醒仍可使用,但刷新页面后计时会重新开始。`:`The reminder still works, but its timer will restart after a page reload.`,acknowledge:t?`知道了`:`Got it`,closeStartup:t?`关闭`:`Close`,closeAppearance:e=>{let n=e===`black-hole`?t?`黑洞`:`Black hole`:t?`柔光`:`Soft glow`;return t?`关闭并使用${n}`:`Close and use ${n}`},closeDue:t?`取消本次休息`:`Cancel this break`}}function PR({language:e,appearancePreference:t,restReminderEntryBlocked:n=!1}){let r=(0,G.useMemo)(()=>NR(e),[e]),i=yR(t),[a,o]=(0,G.useState)(BI),[s,c]=(0,G.useState)(!1),[l,u]=(0,G.useState)(()=>VI(void 0,i)),[d,f]=(0,G.useState)(null),p=(0,G.useRef)(null),[m,h]=(0,G.useState)(!1),[g,_]=(0,G.useState)(null),[v,y]=(0,G.useState)(``),[b,x]=(0,G.useState)(!1),[S,C]=(0,G.useState)(Date.now),w=AR(s&&a===null),{state:T,pageVisible:E,persistenceFailed:D,dismiss:O,snooze:k}=TR(a,n);(0,G.useEffect)(()=>{let e=!1;return JI(i).then(t=>{e||(o(t),c(!0))}),()=>{e=!0}},[i]),(0,G.useEffect)(()=>{let e=(e,t,n=!1)=>{o(RI(e)),c(!0),u(t??VI(void 0,i)),_(null),n&&y(``)},t=t=>{let n=t.detail;e(n?.intervalSeconds,n?.appearance,!0)},n=t=>{YI(t.key)&&e(BI(),VI(void 0,i))};return window.addEventListener(SI,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(SI,t),window.removeEventListener(`storage`,n)}},[i]),(0,G.useEffect)(()=>{u(VI(void 0,i))},[i]),(0,G.useEffect)(()=>{let e=e=>{let t=e.detail,n=t?.appearance;n!==`glass`&&n!==`black-hole`||(p.current=typeof t?.onEnd==`function`?t.onEnd:null,f({appearance:n,restUntil:Date.now()+OR*1e3}))};return window.addEventListener(CI,e),()=>window.removeEventListener(CI,e)},[]);let A=(0,G.useCallback)(()=>{f(null);let e=p.current;p.current=null,e?.()},[]);(0,G.useEffect)(()=>()=>{let e=p.current;p.current=null,e?.()},[]),(0,G.useEffect)(()=>{if(!E||T?.phase!==`due`)return;C(Date.now());let e=window.setInterval(()=>C(Date.now()),1e3);return()=>window.clearInterval(e)},[E,T?.phase,T?.restStartsAt]),(0,G.useEffect)(()=>{if(!d)return;let e=window.setTimeout(A,Math.max(0,d.restUntil-Date.now()));return()=>window.clearTimeout(e)},[d,A]);let j=(0,G.useCallback)(async()=>{await qI(3e3,i)?(y(``),_(`appearance`)):y(r.settingsSaveFailed)},[r.settingsSaveFailed,i]),M=(0,G.useCallback)(async()=>{await qI(0,i)?y(``):y(r.settingsSaveFailed)},[r.settingsSaveFailed,i]),N=(0,G.useCallback)(e=>{if(!WI(e)){y(r.settingsSaveFailed);return}y(``),u(e),_(null)},[r.settingsSaveFailed]),P=(0,G.useMemo)(()=>{if(!s||n&&T?.phase!==`resting`)return null;let e=bI(a,g);return!w&&e?.option===`invitation`||m&&e?.option===`invitation`?null:e||(T?.phase===`due`&&T.restStartsAt!==null?{kind:`capability`,capability:`rest-reminder`,phase:`due`,restStartsAt:T.restStartsAt}:T?.phase===`resting`&&T.restUntil!==null?{kind:`capability`,capability:`rest-reminder`,phase:`resting`,restUntil:T.restUntil}:null)},[a,w,T,n,g,s,m]);if(d)return d.appearance===`black-hole`?(0,K.jsx)(lR,{statusLabel:r.previewTitle(`black-hole`),errorLabel:r.blackHoleError,endLabel:r.endPreview,restUntil:d.restUntil,active:E,onEnd:A}):(0,K.jsx)(dR,{title:r.previewTitle(`glass`),body:r.previewBody,endLabel:r.endPreview,restUntil:d.restUntil,active:E,onEnd:A});if(!P)return!D||b?null:(0,K.jsx)(fR,{title:r.runtimeSaveTitle,body:r.runtimeSaveBody,closeLabel:r.acknowledge,testId:`pet-runtime-save-warning`,onClose:()=>x(!0),actions:[{label:r.acknowledge,onClick:()=>x(!0)}]});if(P.kind===`capability`&&P.capability===`rest-reminder`&&P.phase===`resting`)return l===`black-hole`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{className:`code-visually-hidden`,role:`status`,"aria-live":`polite`,children:r.restStartedAnnouncement(T?.intervalSeconds??3e3)}),(0,K.jsx)(lR,{statusLabel:r.restingStatus,errorLabel:r.blackHoleError,endLabel:r.endBreak,restUntil:P.restUntil,active:E,onEnd:O})]}):(0,K.jsx)(dR,{title:r.restingTitle,body:r.restingBody,endLabel:r.endBreak,restUntil:P.restUntil,active:E,onEnd:O});if(P.kind===`capability`&&P.capability===`rest-reminder`&&P.phase===`due`){let e=Math.max(0,Math.ceil((P.restStartsAt-S)/1e3));return(0,K.jsx)(fR,{title:r.dueTitle,body:r.dueBody(T?.intervalSeconds??3e3,e),closeLabel:r.closeDue,testId:`pet-rest-reminder`,announcement:r.dueAnnouncement(T?.intervalSeconds??3e3),error:v||void 0,onClose:O,actions:[{label:r.cancelBreak,onClick:O},...T?.snoozeUsed?[]:[{label:r.snooze,onClick:k}]]})}return P.kind===`notification`&&P.notification===`rest-reminder-setup`&&P.option===`appearance`?(0,K.jsx)(fR,{title:r.appearanceTitle,body:r.appearanceBody,closeLabel:r.closeAppearance(l),testId:`pet-appearance-choice`,error:v||void 0,onClose:()=>N(l),actions:[],children:(0,K.jsx)(`div`,{className:`code-pet-appearance-options`,role:`group`,"aria-label":r.appearanceTitle,children:[`glass`,`black-hole`].map(e=>(0,K.jsxs)(`div`,{className:`code-pet-appearance-option`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-pet-appearance-select${l===e?` selected`:``}`,"aria-pressed":l===e,onClick:()=>N(e),children:[(0,K.jsx)(`span`,{className:`code-pet-appearance-icon ${e}`,"aria-hidden":`true`}),(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`strong`,{children:e===`glass`?r.softGlow:r.blackHole}),(0,K.jsx)(`small`,{children:e===`glass`?r.softGlowHint:r.blackHoleHint})]}),i===e&&(0,K.jsx)(`em`,{children:r.defaultAppearance})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-pet-appearance-preview`,"aria-label":r.previewAppearance(e),title:r.previewAppearance(e),onClick:()=>FI(e),children:(0,K.jsx)(Me,{})})]},e))})}):(0,K.jsx)(fR,{title:r.startupTitle,body:r.startupBody,closeLabel:r.closeStartup,testId:`pet-rest-invitation`,error:v||void 0,onClose:()=>h(!0),actions:[{label:r.tryReminder,primary:!0,onClick:j},{label:r.disable,onClick:M}]})}var FR=5,IR=5;function LR(){return typeof window>`u`?!1:navigator.standalone===!0||window.matchMedia(`(display-mode: standalone)`).matches}function RR(e){let t=e?.trim().toLowerCase()||``;if(t===`claude-code`)return`claude`;if([`codex`,`claude`,`opencode`,`qoder`,`qwen`,`bash`,`zsh`].includes(t))return t}function zR(e){return RR(e.providerSessionProvider)||RR(e.command.trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e))?.split(`/`).pop())}function BR(){return(0,K.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,K.jsx)(`circle`,{cx:`4`,cy:`3`,r:`1.5`}),(0,K.jsx)(`circle`,{cx:`4`,cy:`13`,r:`1.5`}),(0,K.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,K.jsx)(`path`,{d:`M4 4.5v7M5.5 8h2.25A4.25 4.25 0 0 0 12 3.75`})]})}function VR(e){let t=e.trim().replace(/^v/i,``);if(!t)return``;let n=/^(\d+\.\d+\.\d+)-(\d+)-g[0-9a-f]+(?:-dirty)?$/i.exec(t);if(n)return`${n[1]}-${n[2]}`;let r=/^(\d+\.\d+\.\d+)-dirty$/i.exec(t);return r?`${r[1]}-1`:t.replace(/-dirty$/i,``)}var HR=(0,G.lazy)(()=>s(()=>import(`./ProjectFilesSection-BDT2_r0o.js`).then(e=>({default:e.ProjectFilesSection})),__vite__mapDeps([20,1,5,6,7,21,22,23,16,24,17])));function UR({sidebarCollapsed:e,emptyHomeActionRequest:t,activeView:n,searchOpen:i,displayedProjects:a,collapsedProjectIds:o,normalizedSearch:s,hasProjectListItems:c,hasDisplayedProjectListItems:l,activeTerminalId:u,selectedSearchAgentId:d,selectedSearchSessionHandle:f,claimedAgentSessionKeyByAgentId:p,agentShortcutKeys:m,keyboardShortcutsEnabled:h,now:g,mainAgent:_,usageSummary:v,instanceName:y,language:b,appearancePreference:x,restReminderEntryBlocked:S,shareTarget:C,agentLaunchOptions:w,agentCreationWorkspace:T,openWorkspaceFile:E,openWorkspaceFiles:D,fileRevealRequest:O,fileSearchFocusRequest:k,projectListRef:A,canLoadMoreAgentSessions:j,onLoadMoreAgentSessions:M,onNewAgent:N,onStartAgent:P,onToggleSidebar:F,onOpenSearch:ee,onOpenWorkspaceView:I,onOpenMainAgent:L,onRestartMainAgent:te,onProjectListKeyDown:R,onToggleProject:ne,onToggleProjectSessions:re,onMountProject:z,onOpenProjectMenu:ie,onOpenAgent:ae,onUpdateAgentFlags:B,onReorderAgent:oe,onOpenAgentMenu:V,onResumeAgentSession:se,onOpenAgentSessionMenu:ce,onOpenProjectFile:le,onSelectOpenWorkspaceFile:ue,onCloseOpenWorkspaceFile:de,onMoveWorkspaceEntries:fe,onDeleteWorkspaceEntries:pe,onRefreshProjectOpenFiles:me,onOpenOptionsMenu:he,onRenameInstance:ge,copy:H}){let[_e,ve]=(0,G.useState)(null),[ye,be]=(0,G.useState)(null),xe=(0,G.useRef)(null),Se=(0,G.useRef)(!1),U=(0,G.useRef)(new Map),[we,Te]=(0,G.useState)(!0),[De,Ae]=(0,G.useState)(!1),[je,Me]=(0,G.useState)(!1),[Ne,Pe]=(0,G.useState)(!1),Fe=(0,G.useRef)(null),Le=(0,G.useRef)(null),Re=(0,G.useCallback)(()=>Me(!1),[]),[ze,Ve]=(0,G.useState)(!1),[He,Ue]=(0,G.useState)(!1),[We,Ge]=(0,G.useState)(LR),[Ke,qe]=(0,G.useState)(!1),[Je,Ye]=(0,G.useState)(null),Xe=(0,G.useRef)(0),Ze=(0,G.useCallback)(e=>{j&&e.scrollHeight-e.scrollTop-e.clientHeight<=240&&M()},[j,M]),Qe=(0,G.useCallback)(()=>{xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)},[]),$e=(0,G.useCallback)(()=>{Qe(),ve(null),be(null)},[Qe]),et=(0,G.useCallback)(()=>{Se.current=!1,$e()},[$e]),tt=(0,G.useCallback)((e,t,n=!1)=>{Qe();let i=e.currentTarget,a=Se.current?0:n?450:1500;xe.current=window.setTimeout(()=>{if(xe.current=null,!i.matches(`:hover`))return;let e=i.getBoundingClientRect(),n=e.right+10,a=Math.min(320,window.innerWidth-n-12);if(a<200)return;let o=Math.max(8,Math.min(e.top-4,window.innerHeight-152)),s=t.workspaceRootId?U.current.get(t.workspaceRootId):void 0,c=s&&s.expiresAt>Date.now()?s.branch:``;Se.current=!0,be(null),ve({...t,x:n,y:o,width:a,branch:c}),!(!t.workspaceRootId||c)&&fetch(r(`/api/files/branch?rootId=${encodeURIComponent(t.workspaceRootId)}`)).then(e=>e.ok?e.json():null).then(e=>{let n=typeof e?.branch==`string`?e.branch.trim():``;U.current.set(t.workspaceRootId,{branch:n,expiresAt:Date.now()+3e4}),ve(e=>e?.key===t.key?{...e,branch:n}:e)}).catch(()=>{U.current.set(t.workspaceRootId,{branch:``,expiresAt:Date.now()+3e4})})},a)},[Qe]),nt=(0,G.useCallback)((e,t)=>{Qe();let n=e.currentTarget,r=Se.current?0:1500;xe.current=window.setTimeout(()=>{if(xe.current=null,!n.matches(`:hover`))return;let e=n.getBoundingClientRect(),r=e.right+10,i=Math.min(320,window.innerWidth-r-12);if(i<200)return;let a=Math.max(8,Math.min(e.top-4,window.innerHeight-188));Se.current=!0,ve(null),be({...t,x:r,y:a,width:i})},r)},[Qe]);(0,G.useEffect)(()=>()=>Qe(),[Qe]),(0,G.useEffect)(()=>{Ue(!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen));let e=()=>{Ve(!!document.fullscreenElement)};return document.addEventListener(`fullscreenchange`,e),e(),()=>{document.removeEventListener(`fullscreenchange`,e)}},[]),(0,G.useEffect)(()=>{let e=window.matchMedia(`(display-mode: standalone)`),t=()=>{let e=LR();Ge(e),e&&qe(!1)},n=e=>{e.preventDefault(),Ye(e)};return e.addEventListener(`change`,t),window.addEventListener(`beforeinstallprompt`,n),t(),()=>{e.removeEventListener(`change`,t),window.removeEventListener(`beforeinstallprompt`,n)}},[]);let W=(0,G.useCallback)(()=>{if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}document.documentElement.requestFullscreen({navigationUI:`hide`}).catch(()=>{})},[]);(0,G.useEffect)(()=>{if(!(!t||Xe.current===t.nonce)&&(Xe.current=t.nonce,t.kind===`focus`)){if(We){W();return}qe(!0)}},[t,We,W]);let rt=(0,G.useCallback)(()=>{let e=Je;e&&e.prompt().then(()=>e.userChoice).then(e=>{Ye(null),e.outcome===`accepted`&&qe(!1)}).catch(()=>Ye(null))},[Je]),it=(0,G.useCallback)(()=>{qe(!1),W()},[W]),at=window.isSecureContext?H.appModeInstallUnavailableBrowser:H.appModeInstallUnavailableInsecure,ot=a.flatMap(e=>[...e.agents.filter(e=>e.pinned).map(e=>({kind:`agent`,agent:e})),...e.agentSessions.filter(e=>e.pinned).map(e=>({kind:`agent-session`,session:e}))]).sort((e,t)=>e.kind===`agent`&&t.kind===`agent`?(e.agent.pinnedOrder??0)-(t.agent.pinnedOrder??0)||(e.agent.startedAt??0)-(t.agent.startedAt??0):e.kind===t.kind?e.kind===`agent-session`&&t.kind===`agent-session`?PA(t.session)-PA(e.session):0:e.kind===`agent`?-1:1),st=a.filter(e=>e.agents.some(e=>!e.pinned||!e.isMain)||e.agentSessions.some(e=>!e.pinned)||(e.hiddenAgentSessionCount??0)>0||e.hasOpenFile||!!e.workspace),ct=a.flatMap(e=>[...e.agents.filter(e=>!e.isMain).map(t=>({agent:t,projectName:e.name}))]),lt=VR(`2.2.32`),ut=lt?`v${lt}`:``,ft=e;return(0,K.jsxs)(`aside`,{className:`code-sidebar ${e?`collapsed`:``}`,"data-testid":`code-sidebar`,onMouseLeave:et,onPointerDownCapture:$e,onContextMenuCapture:$e,children:[(0,K.jsx)(`div`,{className:`code-nav`,children:(0,K.jsxs)(`div`,{className:`code-nav-top-row`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-nav-item primary`,"data-testid":`code-new-agent`,onClick:e=>N(T,void 0,e.currentTarget),children:[(0,K.jsx)(`span`,{className:`code-nav-icon`,children:(0,K.jsx)(Ee,{})}),(0,K.jsx)(`span`,{children:H.newAgent}),h&&(0,K.jsx)(`kbd`,{children:`N`})]}),(0,K.jsx)(bF,{copy:H,sidebarCollapsed:e,shareTarget:C,openRequest:t?.kind===`share`?t.nonce:0}),!We&&!e&&(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-focus-toggle ${ze?`active`:``}`,"data-testid":`code-sidebar-focus-toggle`,"aria-label":H.appModeOpen,title:H.appModeOpen,"aria-haspopup":`dialog`,"aria-expanded":Ke,onClick:()=>qe(!0),children:(0,K.jsx)(`span`,{className:`code-sidebar-focus-icon`,children:(0,K.jsx)(Ce,{})})}),!e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-search-toggle ${n===`search`||i?`active`:``}`,"data-testid":`code-nav-search`,"aria-label":H.search,title:H.search,"aria-pressed":n===`search`||i,onClick:ee,children:(0,K.jsx)(`span`,{className:`code-sidebar-search-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Oe,{})})}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-history-toggle ${n===`history`?`active`:``}`,"data-testid":`code-nav-history`,"aria-label":H.history,title:H.history,"aria-pressed":n===`history`,onClick:()=>I(`history`),children:(0,K.jsx)(`span`,{className:`code-sidebar-history-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Ie,{})})}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-plugins-toggle ${n===`plugins`?`active`:``}`,"data-testid":`code-nav-plugins`,"aria-label":H.plugins,title:H.plugins,"aria-pressed":n===`plugins`,onClick:()=>I(`plugins`),children:(0,K.jsx)(`span`,{className:`code-sidebar-plugins-icon`,"aria-hidden":`true`,children:(0,K.jsx)(ht,{})})})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-toggle`,"data-testid":`code-sidebar-toggle`,"aria-label":e?H.expandSidebar:H.collapseSidebar,title:e?H.expandSidebar:H.collapseSidebar,onClick:F,children:(0,K.jsx)(`span`,{className:`code-sidebar-toggle-icon ${e?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:e?(0,K.jsx)(mt,{}):(0,K.jsx)(dt,{})})})]})}),e&&ct.length>0&&(0,K.jsx)(WR,{items:ct,activeTerminalId:u,now:g,onOpenAgent:ae,onShowPreview:tt,onHidePreview:$e,copy:H}),(0,K.jsxs)(`div`,{className:`code-project-list`,"data-testid":`code-project-list`,ref:A,tabIndex:0,onKeyDown:R,onScroll:e=>Ze(e.currentTarget),"aria-label":H.projectsAndAgents,children:[!c&&(0,K.jsx)(`div`,{className:`code-empty-project`,children:H.noAgentsYet}),c&&!l&&(0,K.jsx)(`div`,{className:`code-empty-project`,"data-testid":`code-empty-search`,children:H.noMatchingProjectsOrAgents}),ot.length>0&&(0,K.jsx)(JR,{items:ot,collapsed:De,compressed:ft,activeTerminalId:u,selectedSearchAgentId:d,selectedSearchSessionHandle:f,claimedAgentSessionKeyByAgentId:p,agentShortcutKeys:m,keyboardShortcutsEnabled:h,now:g,onOpenAgent:ae,onUpdateAgentFlags:B,onReorderAgent:oe,onOpenAgentMenu:V,onResumeAgentSession:se,onOpenAgentSessionMenu:ce,onShowAgentPreview:tt,onHideAgentPreview:$e,onToggleCollapsed:()=>Ae(e=>!e),copy:H}),st.map(e=>(0,K.jsx)(QR,{project:e,collapsed:o.has(e.id)&&!s,forceAgentsExpanded:!!s,compactAgents:ft,activeTerminalId:u,selectedSearchAgentId:d,selectedSearchSessionHandle:f,claimedAgentSessionKeyByAgentId:p,agentShortcutKeys:m,keyboardShortcutsEnabled:h,now:g,openWorkspaceFile:E,openWorkspaceFiles:D,agentLaunchOptions:w,fileRevealRequest:O,fileSearchFocusRequest:k,onToggleProject:ne,onToggleProjectSessions:re,onMountProject:z,onNewAgent:N,onStartAgent:P,onOpenProjectMenu:ie,onShowProjectPreview:nt,onOpenAgent:ae,onUpdateAgentFlags:B,onReorderAgent:oe,onOpenAgentMenu:V,onResumeAgentSession:se,onOpenAgentSessionMenu:ce,onShowAgentPreview:tt,onHideAgentPreview:$e,onOpenProjectFile:le,onSelectOpenWorkspaceFile:ue,onCloseOpenWorkspaceFile:de,onMoveWorkspaceEntries:fe,onDeleteWorkspaceEntries:pe,onRefreshProjectOpenFiles:me,copy:H},e.id))]}),(0,K.jsxs)(`div`,{className:`code-sidebar-footer`,children:[(0,K.jsxs)(`div`,{className:`code-product-pet-anchor`,children:[!e&&(0,K.jsxs)(`button`,{ref:Le,type:`button`,className:`code-instance-name`,"data-testid":`code-instance-name-edit`,"aria-label":H.renameInstance,title:y,onClick:()=>Pe(!0),children:[(0,K.jsx)(`span`,{className:`code-instance-name-copy`,children:y}),(0,K.jsx)(ke,{})]}),(0,K.jsx)(jR,{language:b,appearancePreference:x,restReminderEntryBlocked:S||je||Ne||Ke}),(0,K.jsxs)(`div`,{className:`code-product-row`,children:[(0,K.jsxs)(`button`,{ref:Fe,type:`button`,className:`code-product-mark`,"data-testid":`code-product-mark`,title:`Farming Code`,"aria-label":`Farming Code`,onClick:()=>Me(!0),children:[(0,K.jsx)(`img`,{className:`code-product-logo`,src:r(`/farming-2/app-icon-v2-180.png`),alt:``,"aria-hidden":`true`}),(0,K.jsxs)(`span`,{className:`code-product-mark-copy`,children:[(0,K.jsxs)(`span`,{className:`code-product-mark-main-slot`,children:[(0,K.jsx)(`span`,{className:`code-product-mark-main code-product-mark-main-full`,children:`Farming Code`}),(0,K.jsx)(`span`,{className:`code-product-mark-main code-product-mark-main-short`,"aria-hidden":`true`,children:`Farming`})]}),ut&&(0,K.jsx)(`span`,{className:`code-product-mark-badge`,children:ut})]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-options`,"data-testid":`code-sidebar-options`,"aria-label":H.openSettings,title:H.openSettings,onClick:he,children:(0,K.jsx)(Be,{})})]})]}),!e&&(0,K.jsx)(vI,{collapsed:we,mainAgent:_,now:g,usageSummary:v,onToggleCollapsed:()=>Te(e=>!e),onOpenMainAgent:L,onRestartMainAgent:te})]}),_e&&(0,K.jsx)(az,{preview:_e,now:g}),ye&&(0,K.jsx)(iz,{preview:ye,copy:H}),je&&(0,K.jsx)(GP,{copy:H,version:ut,onClose:Re,returnFocusRef:Fe}),Ne&&(0,K.jsx)(qP,{copy:H,instanceName:y,onClose:()=>Pe(!1),onSave:ge,returnFocusRef:Le}),Ke&&(0,K.jsx)(UP,{canInstall:!!Je,canFullscreen:He,fullscreenActive:ze,installUnavailableReason:at,copy:H,onClose:()=>qe(!1),onInstall:rt,onToggleFullscreen:it})]})}function WR({items:e,activeTerminalId:t,now:n,onOpenAgent:r,onShowPreview:i,onHidePreview:a,copy:o}){return(0,K.jsx)(`div`,{className:`code-agent-rail`,"data-testid":`code-agent-rail`,"aria-label":o.projectsAndAgents,children:e.map((e,o)=>(0,K.jsx)(GR,{item:e,index:o,activeTerminalId:t,now:n,onOpenAgent:r,onShowPreview:i,onHidePreview:a},FM({kind:`agent`,agent:e.agent})))})}function GR({item:e,index:t,activeTerminalId:n,now:r,onOpenAgent:i,onShowPreview:a,onHidePreview:o}){let s=KM({kind:`agent`,agent:e.agent},r),c=e.agent.id===n,l=[s.title,s.commandTitle,e.projectName].filter(Boolean).join(` · `);return(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-rail-button ${c?`active`:``} ${s.unread?`unread`:``}`,"data-testid":`code-agent-rail-item`,"data-agent-id":e.agent.id,"aria-label":l,onClick:()=>{i(e.agent.id)},onMouseEnter:t=>a(t,nz(e.agent,s,e.projectName),!0),onMouseLeave:o,children:[(0,K.jsx)(`span`,{className:`code-agent-rail-label`,children:t+1}),s.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-agent-rail-status ${s.lifecycleStatus} ${s.turnActive?`turn-active`:``}`,"aria-hidden":`true`}),s.unread&&(0,K.jsx)(`span`,{className:`code-agent-rail-unread`,"aria-hidden":`true`})]})}function KR({agents:e,activeTerminalId:t,selectedSearchAgentId:n,claimedAgentSessionKeyByAgentId:r,now:i,onOpenAgent:a,onOpenAgentMenu:o,onShowPreview:s,onHidePreview:c}){return(0,K.jsx)(`div`,{className:`code-project-agent-strip`,"data-testid":`code-project-agent-strip`,"aria-label":`Project agents`,children:e.map((e,l)=>{let u=KM({kind:`agent`,agent:e},i),d=e.id===t,f=e.id===n,p=u.rowTitle||u.title;return(0,K.jsxs)(`button`,{type:`button`,className:`code-project-agent-compact ${d?`active`:``} ${f?`search-selected`:``} ${u.unread?`unread`:``}`,"data-testid":`code-project-agent-compact`,"data-agent-id":e.id,"aria-label":p,onClick:()=>a(e.id),onMouseEnter:t=>s(t,nz(e,u),!0),onMouseLeave:c,onContextMenu:t=>o(t,e.id),onKeyDown:t=>{o(t,e.id),!t.defaultPrevented&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),a(e.id))},children:[(0,K.jsx)(`span`,{className:`code-project-agent-compact-label`,children:l+1}),u.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-status ${u.lifecycleStatus} ${u.turnActive?`turn-active`:``}`,"aria-hidden":`true`}),u.unread&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-unread`,"aria-hidden":`true`})]},FM({kind:`agent`,agent:e,claimedSessionKey:r.get(e.id)}))})})}function qR({items:e,activeTerminalId:t,selectedSearchAgentId:n,selectedSearchSessionHandle:r,claimedAgentSessionKeyByAgentId:i,now:a,onOpenAgent:o,onOpenAgentMenu:s,onResumeAgentSession:c,onOpenAgentSessionMenu:l,onShowPreview:u,onHidePreview:d}){return(0,K.jsx)(`div`,{className:`code-project-agent-strip code-pinned-agent-strip`,"data-testid":`code-pinned-agent-strip`,"aria-label":`Pinned agents`,children:e.map((e,f)=>{let p=e.kind===`agent`?KM({kind:`agent`,agent:e.agent},a):KM({kind:`history`,session:e.session,fallbackTitle:e.session.providerName||e.session.provider||`Agent`},a),m=e.kind===`agent`?e.agent:null,h=e.kind===`agent`?null:e.session,g=h?OA(h):null,_=m?m.id===t:!1,v=m?m.id===n:g===r,y=p.rowTitle||p.title;return(0,K.jsxs)(`button`,{type:`button`,className:`code-project-agent-compact ${_?`active`:``} ${v?`search-selected`:``} ${p.unread?`unread`:``}`,"data-testid":`code-pinned-agent-compact`,"data-agent-id":m?.id,"data-session-id":g??void 0,"aria-label":y,onClick:()=>{if(m){o(m.id);return}h&&c(h.provider,h.id,h.providerHomeId)},onMouseEnter:e=>u(e,m?nz(m,p):rz(h,p),!0),onMouseLeave:d,onContextMenu:e=>{if(m){s(e,m.id);return}h&&l(e,h.provider,OA(h))},onKeyDown:e=>{m?s(e,m.id):h&&l(e,h.provider,OA(h)),!e.defaultPrevented&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),m?o(m.id):h&&c(h.provider,h.id,h.providerHomeId))},children:[(0,K.jsx)(`span`,{className:`code-project-agent-compact-label`,children:f+1}),p.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-status ${p.lifecycleStatus} ${p.turnActive?`turn-active`:``}`,"aria-hidden":`true`}),p.unread&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-unread`,"aria-hidden":`true`})]},e.kind===`agent`?FM({kind:`agent`,agent:e.agent,claimedSessionKey:i.get(e.agent.id)}):FM({kind:`history`,session:e.session}))})})}function JR({items:e,collapsed:t,compressed:n,activeTerminalId:r,selectedSearchAgentId:i,selectedSearchSessionHandle:a,claimedAgentSessionKeyByAgentId:o,agentShortcutKeys:s,keyboardShortcutsEnabled:c,now:l,onOpenAgent:u,onUpdateAgentFlags:d,onReorderAgent:f,onOpenAgentMenu:p,onResumeAgentSession:m,onOpenAgentSessionMenu:h,onShowAgentPreview:g,onHideAgentPreview:_,onToggleCollapsed:v,copy:y}){let{agentDrag:b,beginAgentDrag:x,dropAgent:S,finishAgentDrag:C,updateAgentDropTarget:w}=DF(e.flatMap(e=>e.kind===`agent`?[e.agent]:[]),f,_);return(0,K.jsxs)(`section`,{className:`code-pinned-section ${t?`collapsed`:``}`,"data-testid":`code-pinned-section`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-pinned-title`,"data-testid":`code-pinned-title`,"aria-expanded":!t,onClick:v,children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${t?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:t?(0,K.jsx)(mt,{}):(0,K.jsx)(Ge,{})}),(0,K.jsx)(`span`,{children:y.pinned})]}),!t&&(0,K.jsx)(`div`,{className:`code-agent-list code-pinned-list`,children:n?(0,K.jsx)(qR,{items:e,activeTerminalId:r,selectedSearchAgentId:i,selectedSearchSessionHandle:a,claimedAgentSessionKeyByAgentId:o,now:l,onOpenAgent:u,onOpenAgentMenu:p,onResumeAgentSession:m,onOpenAgentSessionMenu:h,onShowPreview:g,onHidePreview:_}):e.map(e=>{if(e.kind===`agent`){let t=e.agent;return(0,K.jsx)(pz,{agent:t,shortcutHint:c?s.get(t.id):void 0,active:t.id===r,searchSelected:t.id===i,now:l,onOpenAgent:u,onUpdateAgentFlags:d,reorderable:!0,dragging:b?.agentId===t.id,dropPosition:b?.targetAgentId===t.id?b.position:void 0,onAgentDragStart:x,onAgentDragEnd:C,onAgentDragOver:w,onAgentDrop:S,onOpenAgentMenu:p,onShowPreview:g,onHidePreview:_,copy:y},FM({kind:`agent`,agent:t,claimedSessionKey:o.get(t.id)}))}return(0,K.jsx)(pz,{session:e.session,searchSelected:OA(e.session)===a,now:l,onResume:m,onOpenSessionMenu:h,onShowPreview:g,onHidePreview:_,copy:y},FM({kind:`history`,session:e.session}))})})]})}function YR(e,t){return e.branch?e.branch:e.detached?`${t.worktreeDetached}@${e.head.slice(0,7)}`:e.bare?`bare`:e.head.slice(0,7)}function XR({agentId:e,anchorRef:t,copy:n,fallback:r,point:i,onClose:a,onMountProject:o}){let s=(0,G.useRef)(null),c=(0,G.useRef)(null),[l,u]=(0,G.useState)(r),[d,f]=(0,G.useState)(!1),[p,m]=(0,G.useState)(``),g=(0,G.useCallback)(()=>{c.current?.abort();let t=new AbortController;c.current=t,f(!0),m(``),pe(e,{signal:t.signal}).then(e=>{t.signal.aborted||u(e)}).catch(e=>{t.signal.aborted||e?.name===`AbortError`||m(n.worktreeLoadFailed)}).finally(()=>{t.signal.aborted||f(!1)})},[e,n.worktreeLoadFailed]);return(0,G.useEffect)(()=>(g(),()=>c.current?.abort()),[g]),h(!0,s,t,a),(0,K.jsxs)(`div`,{ref:s,className:`code-worktree-popover`,"data-testid":`code-project-worktree-menu`,role:`dialog`,"aria-label":n.worktrees,style:{left:i.x,top:i.y},children:[(0,K.jsxs)(`div`,{className:`code-worktree-popover-header`,children:[(0,K.jsx)(`span`,{children:n.worktrees}),(0,K.jsx)(`span`,{className:`code-worktree-popover-count`,children:l.items.length}),(0,K.jsx)(`button`,{type:`button`,className:d?`loading`:``,disabled:d,onClick:g,children:n.refresh})]}),p&&(0,K.jsx)(`div`,{className:`code-worktree-popover-status error`,children:p}),!p&&!l.isGitRepo&&(0,K.jsx)(`div`,{className:`code-worktree-popover-status`,children:n.gitHistoryNotRepository}),(0,K.jsx)(`div`,{className:`code-worktree-list`,children:l.items.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-worktree-row ${e.current?`current`:``}`,"data-current":e.current?`true`:void 0,"data-main":e.main?`true`:void 0,title:e.workspace,onClick:()=>{o(e.workspace),a()},children:[(0,K.jsx)(`span`,{className:`code-worktree-row-marker`,"aria-hidden":`true`}),(0,K.jsxs)(`span`,{className:`code-worktree-row-content`,children:[(0,K.jsxs)(`span`,{className:`code-worktree-row-heading`,children:[(0,K.jsx)(`strong`,{children:YR(e,n)}),(0,K.jsxs)(`span`,{className:`code-worktree-row-badges`,children:[e.current&&(0,K.jsx)(`span`,{children:n.worktreeCurrent}),e.main&&(0,K.jsx)(`span`,{children:n.worktreeMain}),e.locked&&(0,K.jsx)(`span`,{title:e.lockReason,children:n.worktreeLocked}),e.prunable&&(0,K.jsx)(`span`,{title:e.pruneReason,children:n.worktreePrunable})]}),e.head&&(0,K.jsx)(`code`,{children:e.head.slice(0,7)})]}),(0,K.jsx)(`span`,{className:`code-worktree-row-path`,children:e.workspace})]})]},e.workspace))})]})}function ZR(e){return e?.workspace?{isGitRepo:!0,commonDir:e.commonDir,currentWorkspace:e.workspace,mainWorkspace:e.mainWorkspace,items:Array.isArray(e.worktrees)?e.worktrees:[]}:null}function QR({project:e,collapsed:t,forceAgentsExpanded:n,compactAgents:r,activeTerminalId:i,selectedSearchAgentId:a,selectedSearchSessionHandle:o,claimedAgentSessionKeyByAgentId:s,agentShortcutKeys:c,keyboardShortcutsEnabled:l,now:u,openWorkspaceFile:d,openWorkspaceFiles:f,agentLaunchOptions:p,fileRevealRequest:m,fileSearchFocusRequest:g,onToggleProject:_,onToggleProjectSessions:v,onMountProject:y,onNewAgent:S,onStartAgent:C,onOpenProjectMenu:w,onShowProjectPreview:T,onOpenAgent:E,onUpdateAgentFlags:D,onReorderAgent:O,onOpenAgentMenu:k,onResumeAgentSession:A,onOpenAgentSessionMenu:j,onShowAgentPreview:M,onHideAgentPreview:N,onOpenProjectFile:P,onSelectOpenWorkspaceFile:F,onCloseOpenWorkspaceFile:ee,onMoveWorkspaceEntries:I,onDeleteWorkspaceEntries:L,onRefreshProjectOpenFiles:te,copy:R}){let ne=(0,G.useRef)(null),re=(0,G.useRef)(null),z=(0,G.useRef)(null),ie=(0,G.useRef)(null),ae=(0,G.useRef)(null),B=(0,G.useRef)(null),[oe,V]=(0,G.useState)(null),se=(0,G.useCallback)(()=>V(null),[]),[ce,le]=(0,G.useState)(null),[ue,fe]=(0,G.useState)(()=>ZR(e.gitWorktree)),[me,he]=(0,G.useState)(!1),[ge,H]=(0,G.useState)(!1),[_e,ye]=(0,G.useState)(!1),[be,xe]=(0,G.useState)(()=>xF(null,e.agents)),Se=xF((i&&e.agents.some(e=>!e.isMain&&e.id===i)?i:null)??be,e.agents),U=e.agents.find(e=>!e.isMain&&e.id===Se)??null,Ce=e.workspace?Ar(e.workspace):``,we=e.id!==`__farming_main_agent__`&&!!Ce,Te=Ce===Dt,Ee=new Set([Ce,...e.agents.filter(e=>!e.isMain).map(e=>e.id),...U&&!U.isMain?[U.id]:[]]),De=t=>t.workspaceRoot===e.workspace||Ee.has(t.agentId),Oe=d&&De(d)?d:null,ke=f.filter(De),je=new Set(ke.filter(e=>e.dirty).map(e=>e.file.path)),Me=new Set(ke.filter(e=>e.externalChanged).map(e=>e.file.path)),Ne=e.agents.filter(e=>!e.pinned),Pe=e.agentSessions.filter(e=>!e.pinned),Fe=Ne.length>0||Pe.length>0||(e.hiddenAgentSessionCount??0)>0,Ie=_e&&de()&&Ne.length>1,Le=(r||Ie)&&Ne.length>0,Re=Le||me?Ne:ez(Ne,IR,[i,a]),ze=Math.max(0,Ne.length-Re.length),Be=ge&&!n;(0,G.useEffect)(()=>{be!==Se&&xe(Se)},[Se,be]),(0,G.useEffect)(()=>{let t=ZR(e.gitWorktree);t&&fe(t)},[e.gitWorktree]),(0,G.useEffect)(()=>{if(!Ce||Te)return;let e=new AbortController;return pe(Ce,{signal:e.signal}).then(fe).catch(()=>{}),()=>e.abort()},[Ce,Te]);let Ve=(0,G.useCallback)(e=>!U?.id||e?.sourceAgentId?e:{...e,sourceAgentId:U.id},[U?.id]),He=(0,G.useCallback)((e,t,n)=>{P(e,t,Ve(n))},[P,Ve]),Ue=(0,G.useCallback)((e,t,n)=>F(e,t,Ve(n)),[F,Ve]),Ke=(0,G.useCallback)(e=>{ye(!e)},[]),{agentDrag:qe,beginAgentDrag:Je,dropAgent:Ye,dropAgentAtEnd:Xe,droppingAtEnd:Ze,finishAgentDrag:$e,updateAgentDropTarget:et,updateAgentEndDropTarget:tt}=DF(Ne,O,N);(0,G.useEffect)(()=>{Ne.length<=IR&&me&&he(!1)},[me,Ne.length]),(0,G.useLayoutEffect)(()=>{let e=ne.current;if(!e)return;let t=()=>{let t=re.current;e.style.setProperty(`--code-project-sticky-height`,t?`${Math.ceil(t.getBoundingClientRect().height)}px`:``);let n=z.current;e.style.setProperty(`--code-agents-sticky-height`,n?`${Math.ceil(n.getBoundingClientRect().height)}px`:`0px`)};t();let n=re.current,r=z.current,i=typeof ResizeObserver<`u`?new ResizeObserver(t):null;return n&&i?.observe(n),r&&i?.observe(r),window.addEventListener(`resize`,t),()=>{i?.disconnect(),window.removeEventListener(`resize`,t)}},[t,e.id,Fe]),h(oe!==null,ae,ie,se);let nt=t=>{if(t.preventDefault(),t.stopPropagation(),p.length===0){S(e.workspace,void 0,t.currentTarget);return}let n=t.currentTarget.getBoundingClientRect(),r=Math.min(260,p.length*34+12);V(de()?nF(n,r,void 0,194):tF(n,r,void 0,194))},W=(t,n)=>{V(null),C(t,e.workspace,n?{agentRuntimeMode:n}:void 0)},rt=ue?.items.find(e=>e.current),it=ue?.isGitRepo&&rt&&rt?rt.branch||`detached@${rt.head.slice(0,7)}`:``,at=ue?.items.length||0,ot=e.agents.filter(e=>!e.isMain&&e.archived!==!0),st=ot.length+e.agentSessions.filter(e=>e.archived!==!0).length+(e.hiddenAgentSessionCount??0);return(0,K.jsxs)(`section`,{ref:ne,className:`code-project-group`,"data-testid":`code-project-group`,children:[(0,K.jsxs)(`div`,{ref:re,className:`code-project-row`,onMouseEnter:t=>T(t,{key:`project:${e.id}`,name:e.name,workspace:e.workspace,agentCount:st,unreadCount:ot.filter(e=>rn(e).unread===!0).length+e.agentSessions.filter(e=>e.archived!==!0&&e.unread===!0).length,runningCount:ot.filter(e=>KM({kind:`agent`,agent:rn(e)},u).turnActive).length,branch:it,worktreeCount:at,pinned:e.pinned===!0}),onMouseLeave:N,children:[(0,K.jsxs)(`span`,{className:`code-project-title-content`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-project-title`,"data-testid":`code-project-title`,"data-project-id":e.id,"aria-expanded":!t,onClick:()=>_(e.id),onContextMenu:t=>w(t,e.id),onKeyDown:t=>w(t,e.id),children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${t?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:t?(0,K.jsx)(mt,{}):(0,K.jsx)(Ge,{})}),(0,K.jsx)(`span`,{className:`code-project-title-name`,children:e.name})]}),it&&ue&&(0,K.jsxs)(`button`,{ref:B,type:`button`,className:`code-project-worktree`,"data-testid":`code-project-worktree`,"aria-label":`${it} · ${at} ${R.worktrees}`,"aria-haspopup":`dialog`,"aria-expanded":ce?!0:void 0,onClick:e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getBoundingClientRect(),n=Math.min(440,Math.max(320,window.innerWidth-24)),r=Math.min(420,Math.max(132,(ue?.items.length||2)*58+54));le(de()?nF(t,r,void 0,n):tF(t,r,void 0,n))},children:[(0,K.jsx)(`span`,{className:`code-project-worktree-icon`,"aria-hidden":`true`,children:(0,K.jsx)(BR,{})}),(0,K.jsx)(`span`,{className:`code-project-worktree-name`,children:it}),at>1&&(0,K.jsx)(`span`,{className:`code-project-worktree-count`,"aria-hidden":`true`,children:at})]})]}),(0,K.jsxs)(`span`,{className:`code-project-title-actions`,"aria-hidden":!1,children:[Fe&&!n&&(0,K.jsx)(`button`,{type:`button`,className:`code-project-title-action`,"data-testid":`code-project-agent-visibility`,"data-collapsed":Be?`true`:`false`,"aria-expanded":!Be,"aria-label":Be?R.showAgents:R.hideAgents,title:Be?R.showAgents:R.hideAgents,onClick:()=>H(e=>!e),children:Be?(0,K.jsx)(Ae,{}):(0,K.jsx)(We,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-project-title-action`,"data-testid":`code-project-actions`,"aria-label":R.openOptions,title:R.openOptions,onClick:t=>w(t,e.id),children:(0,K.jsx)(tz,{})}),!Te&&(0,K.jsx)(`button`,{ref:ie,type:`button`,className:`code-project-title-action`,"data-testid":`code-project-new-agent`,"aria-label":R.newAgent,title:R.newAgent,"aria-haspopup":`menu`,"aria-expanded":oe?!0:void 0,onClick:nt,children:(0,K.jsx)($R,{})})]}),oe&&typeof document<`u`&&(0,nE.createPortal)((0,K.jsx)(`div`,{ref:ae,className:`code-context-menu code-project-launch-menu`,"data-testid":`code-project-new-agent-menu`,role:`menu`,style:{left:oe.x,top:oe.y},children:p.map(e=>{let t=e.command||e.name,n=b(e.name),r=e.capabilities?.supportsChat===!0;return(0,K.jsxs)(`div`,{className:`code-project-launch-option ${r?`has-chat`:``}`,role:`none`,children:[(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`code-project-agent-launch`,"data-testid":`code-project-agent-launch-${e.name}`,onClick:()=>W(t),children:[(0,K.jsx)(x,{name:e.name}),(0,K.jsx)(`span`,{children:n})]}),r&&(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,className:`code-project-agent-launch-chat`,"data-testid":`code-project-agent-launch-chat-${e.name}`,"aria-label":`${n} · ${R.transcriptView}`,title:R.transcriptView,onClick:()=>W(t,`chat`),children:(0,K.jsx)(Qe,{})})]},e.name)})}),document.body),ce&&ue&&typeof document<`u`&&(0,nE.createPortal)((0,K.jsx)(XR,{agentId:Ce,anchorRef:B,copy:R,fallback:ue,point:ce,onClose:()=>le(null),onMountProject:y}),document.body)]}),!t&&(0,K.jsxs)(`div`,{className:`code-project-expanded`,children:[Fe&&(0,K.jsx)(`div`,{ref:z,className:`code-agents-section`,"data-testid":`code-agents-section`,"data-project-id":e.id,children:(0,K.jsxs)(`div`,{className:`code-agent-list`,children:[!Be&&(0,K.jsxs)(K.Fragment,{children:[Le?(0,K.jsx)(KR,{agents:Ne,activeTerminalId:i,selectedSearchAgentId:a,claimedAgentSessionKeyByAgentId:s,now:u,onOpenAgent:E,onOpenAgentMenu:k,onShowPreview:M,onHidePreview:N}):Re.map(e=>(0,K.jsx)(pz,{agent:e,shortcutHint:l?c.get(e.id):void 0,active:e.id===i,searchSelected:e.id===a,now:u,onOpenAgent:E,onUpdateAgentFlags:D,reorderable:!0,dragging:qe?.agentId===e.id,dropPosition:qe?.targetAgentId===e.id?qe.position:void 0,onAgentDragStart:Je,onAgentDragEnd:$e,onAgentDragOver:et,onAgentDrop:Ye,onOpenAgentMenu:k,onShowPreview:M,onHidePreview:N,copy:R},FM({kind:`agent`,agent:e,claimedSessionKey:s.get(e.id)}))),Pe.map(e=>(0,K.jsx)(pz,{session:e,searchSelected:OA(e)===o,now:u,onResume:A,onOpenSessionMenu:j,onShowPreview:M,onHidePreview:N,copy:R},FM({kind:`history`,session:e}))),(e.hiddenAgentSessionCount??0)>0&&(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-session-show-more`,onClick:()=>v(e.id),children:[(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:R.showMore})}),(0,K.jsx)(`span`,{className:`code-agent-row-trailing`,children:(0,K.jsx)(`span`,{className:`code-agent-age`,children:e.hiddenAgentSessionCount})})]}),e.agentSessionsExpanded&&e.agentSessions.length>FR&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-session-show-less`,onClick:()=>v(e.id),children:(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:R.showLess})})})]}),!n&&!Be&&!Le&&Ne.length>IR&&(0,K.jsxs)(`div`,{className:`code-agent-list-controls`,"data-testid":`code-agent-list-controls`,children:[ze>0&&(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-row code-session-show-more ${Ze?`drop-after`:``}`,"data-testid":`code-agent-show-more`,onClick:()=>he(!0),onDragOver:tt,onDrop:Xe,children:[(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:R.showMore})}),(0,K.jsx)(`span`,{className:`code-agent-row-trailing`,children:(0,K.jsx)(`span`,{className:`code-agent-age`,children:ze})})]}),me&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-agent-show-less`,onClick:()=>he(!1),children:(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:R.showLess})})})]})]})}),we&&(0,K.jsx)(G.Suspense,{fallback:null,children:(0,K.jsx)(HR,{projectId:e.id,projectWorkspace:e.workspace,agentId:Ce,agentLaunchOptions:p,activeFilePath:Oe?.file.path,activeFileRevealInTree:Oe?.revealInTree,openFiles:ke.map(e=>({agentId:e.agentId,workspaceRoot:e.workspaceRoot,key:ve(e),path:e.file.path,dirty:e.dirty,externalChanged:e.externalChanged})),revealRequest:m&&Ee.has(m.agentId)?m:void 0,focusSearchRequest:g&&Ee.has(g.agentId)?g:void 0,editorDirtyFilePaths:je,editorExternalChangedFilePaths:Me,onOpenFile:He,onSelectOpenFile:Ue,onCloseOpenFile:ee,onNewAgent:S,onStartAgent:C,onMoveEntries:I,onDeleteEntries:L,onRefreshOpenFiles:te,onFilesCollapsedChange:Ke,readOnly:Te,copy:R})})]})]})}function $R(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M7.5 3C7.77614 3 8 3.22386 8 3.5V7H11.5C11.7761 7 12 7.22386 12 7.5C12 7.77614 11.7761 8 11.5 8H8V11.5C8 11.7761 7.77614 12 7.5 12C7.22386 12 7 11.7761 7 11.5V8H3.5C3.22386 8 3 7.77614 3 7.5C3 7.22386 3.22386 7 3.5 7H7V3.5C7 3.22386 7.22386 3 7.5 3Z`})})}function ez(e,t,n){if(e.length<=t)return e;let r=e.slice(0,t),i=new Set(r.map(e=>e.id)),a=new Set(n.filter(e=>!!e));for(let n of e)if(!(!a.has(n.id)||i.has(n.id))){if(r.length>=t&&r.length>0){let e=r[r.length-1];i.delete(e.id),r[r.length-1]=n}else r.push(n);i.add(n.id)}return r}function tz(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M4 8C4 8.55228 3.55228 9 3 9C2.44772 9 2 8.55228 2 8C2 7.44772 2.44772 7 3 7C3.55228 7 4 7.44772 4 8ZM9 8C9 8.55228 8.55228 9 8 9C7.44772 9 7 8.55228 7 8C7 7.44772 7.44772 7 8 7C8.55228 7 9 7.44772 9 8ZM13 9C13.5523 9 14 8.55228 14 8C14 7.44772 13.5523 7 13 7C12.4477 7 12 7.44772 12 8C12 8.55228 12.4477 9 13 9Z`})})}function nz(e,t,n){return{key:`agent:${e.id}`,title:t.title,project:n||xA(e.projectWorkspace||e.cwd),lastActive:e.lastActivity||e.startedAt||0,provider:zR(e),workspaceRootId:e.workspaceRootId}}function rz(e,t){return{key:`session:${OA(e)}`,title:t.title,project:NA(e),lastActive:PA(e),provider:RR(e.provider)}}function iz({preview:e,copy:t}){let n=e.branch?e.worktreeCount>1?`${e.branch} · ${e.worktreeCount} ${t.worktrees}`:e.branch:``;return(0,K.jsxs)(`div`,{className:`code-project-hover-preview`,"data-testid":`code-project-hover-preview`,style:{left:e.x,top:e.y,width:e.width},"aria-hidden":`true`,children:[(0,K.jsxs)(`div`,{className:`code-project-hover-preview-header`,children:[(0,K.jsx)(`span`,{className:`code-project-hover-preview-icon`,children:(0,K.jsx)(oz,{})}),(0,K.jsx)(`strong`,{children:e.name}),e.pinned&&(0,K.jsx)(`span`,{className:`code-project-hover-preview-pin`,children:(0,K.jsx)(lz,{})})]}),(0,K.jsxs)(`div`,{className:`code-project-hover-preview-line`,children:[(0,K.jsx)(`span`,{className:`code-project-hover-preview-icon`,children:(0,K.jsx)(sz,{})}),(0,K.jsx)(`span`,{children:t.projectAgentsSummary(e.agentCount,e.unreadCount,e.runningCount)})]}),(0,K.jsxs)(`div`,{className:`code-project-hover-preview-line`,children:[(0,K.jsx)(`span`,{className:`code-project-hover-preview-icon`,children:(0,K.jsx)(oz,{})}),(0,K.jsx)(`span`,{className:`code-project-hover-preview-workspace`,children:er(e.workspace)})]}),n&&(0,K.jsxs)(`div`,{className:`code-project-hover-preview-line`,children:[(0,K.jsx)(`span`,{className:`code-project-hover-preview-icon`,children:(0,K.jsx)(cz,{})}),(0,K.jsx)(`span`,{children:n})]})]})}function az({preview:e,now:t}){let n=(0,G.useRef)(null),[r,i]=(0,G.useState)(!1),a=N(e.lastActive,t);(0,G.useLayoutEffect)(()=>{let e=n.current;i(!!(e&&e.scrollWidth>e.clientWidth+1))},[a,e.key,e.title,e.width]);let o=e.x+e.width+10,s=Math.min(360,window.innerWidth-o-12);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`code-agent-hover-preview`,"data-testid":`code-agent-hover-preview`,style:{left:e.x,top:e.y,width:e.width},"aria-hidden":`true`,children:[(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-header`,children:[(0,K.jsx)(`strong`,{ref:n,children:e.title}),(0,K.jsx)(`span`,{children:a})]}),(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-line`,children:[(0,K.jsx)(`span`,{className:`code-agent-hover-preview-icon`,children:(0,K.jsx)(oz,{})}),(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-project`,children:[(0,K.jsx)(`span`,{className:`code-agent-hover-preview-project-name`,children:e.project}),e.provider&&(0,K.jsx)(x,{name:e.provider,variant:`color`,className:`code-agent-hover-preview-provider-icon`})]})]}),(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-line`,children:[(0,K.jsx)(`span`,{className:`code-agent-hover-preview-icon`,children:(0,K.jsx)(cz,{})}),(0,K.jsx)(`span`,{children:e.branch||`—`})]})]}),r&&s>=180&&(0,K.jsx)(`div`,{className:`code-agent-hover-title-card`,"data-testid":`code-agent-hover-title-card`,style:{left:o,top:e.y,width:s},"aria-hidden":`true`,children:e.title})]})}function oz(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M1.5 3.75C1.5 2.784 2.284 2 3.25 2h3.104c.464 0 .91.184 1.237.513l.841.842c.14.14.33.22.528.22h3.79c.966 0 1.75.784 1.75 1.75v6.925c0 .966-.784 1.75-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75V3.75Zm1.75-.75a.75.75 0 0 0-.75.75v8.5c0 .414.336.75.75.75h9.5a.75.75 0 0 0 .75-.75V5.325a.75.75 0 0 0-.75-.75H8.96a1.75 1.75 0 0 1-1.235-.512l-.841-.842A.75.75 0 0 0 6.354 3H3.25Z`})})}function sz(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M8 1.5C4.41 1.5 1.5 4.08 1.5 7.25c0 1.34.53 2.58 1.43 3.56l-.7 2.46a.75.75 0 0 0 .93.92l2.68-.8c.68.22 1.4.36 2.16.36 3.59 0 6.5-2.58 6.5-5.75S11.59 1.5 8 1.5Zm0 1c3.09 0 5.5 2.18 5.5 4.75S11.09 12 8 12c-.72 0-1.41-.13-2.04-.36a.5.5 0 0 0-.32-.01l-2.21.66.57-2a.5.5 0 0 0-.13-.5A4.5 4.5 0 0 1 2.5 7.25C2.5 4.68 4.91 2.5 8 2.5Z`})})}function cz(){return(0,K.jsx)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M21 8.25C21 6.1815 19.3185 4.5 17.25 4.5C15.1815 4.5 13.5 6.1815 13.5 8.25C13.5 10.023 14.739 11.5035 16.395 11.892C16.116 12.819 15.2655 13.5 14.25 13.5H9.75C8.9025 13.5 8.1285 13.7925 7.5 14.268V7.4235C9.21 7.0755 10.5 5.5605 10.5 3.75C10.5 1.6815 8.8185 0 6.75 0C4.6815 0 3 1.6815 3 3.75C3 5.562 4.29 7.0755 6 7.4235V16.575C4.29 16.923 3 18.438 3 20.2485C3 22.317 4.6815 23.9985 6.75 23.9985C8.8185 23.9985 10.5 22.317 10.5 20.2485C10.5 18.4755 9.261 16.995 7.605 16.6065C7.884 15.6795 8.7345 14.9985 9.75 14.9985H14.25C16.0845 14.9985 17.61 13.6725 17.931 11.9295C19.674 11.607 21 10.0845 21 8.25ZM4.5 3.75C4.5 2.5095 5.5095 1.5 6.75 1.5C7.9905 1.5 9 2.5095 9 3.75C9 4.9905 7.9905 6 6.75 6C5.5095 6 4.5 4.9905 4.5 3.75ZM9 20.25C9 21.4905 7.9905 22.5 6.75 22.5C5.5095 22.5 4.5 21.4905 4.5 20.25C4.5 19.0095 5.5095 18 6.75 18C7.9905 18 9 19.0095 9 20.25ZM17.25 10.5C16.0095 10.5 15 9.4905 15 8.25C15 7.0095 16.0095 6 17.25 6C18.4905 6 19.5 7.0095 19.5 8.25C19.5 9.4905 18.4905 10.5 17.25 10.5Z`})})}function lz(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M10.0589 2.44511C9.34701 1.73063 8.14697 1.90829 7.67261 2.79839L5.6526 6.58878L2.8419 7.52568C2.6775 7.58048 2.5532 7.71649 2.51339 7.88514C2.47357 8.0538 2.52392 8.23104 2.64646 8.35357L4.79291 10.5L2.14645 13.1465L2 14L2.85356 13.8536L5.50002 11.2071L7.64646 13.3536C7.76899 13.4761 7.94623 13.5265 8.11489 13.4866C8.28354 13.4468 8.41955 13.3225 8.47435 13.1581L9.41143 10.3469L13.1897 8.32423C14.0759 7.84982 14.2538 6.6551 13.5443 5.94305L10.0589 2.44511ZM8.55511 3.2687C8.71323 2.972 9.11324 2.91278 9.35055 3.15094L12.836 6.64889C13.0725 6.88624 13.0131 7.28448 12.7178 7.44262L8.76403 9.55921C8.65137 9.61952 8.56608 9.72068 8.52567 9.84191L7.7815 12.0744L3.92562 8.21853L6.15812 7.47436C6.27966 7.43385 6.38101 7.34823 6.44126 7.23518L8.55511 3.2687Z`})})}function uz(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,xmlns:`http://www.w3.org/2000/svg`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M9.56016 10.2673L14.1464 14.8536C14.3417 15.0488 14.6583 15.0488 14.8536 14.8536C15.0488 14.6583 15.0488 14.3417 14.8536 14.1464L1.85355 1.14645C1.65829 0.951184 1.34171 0.951184 1.14645 1.14645C0.951184 1.34171 0.951184 1.65829 1.14645 1.85355L5.73223 6.43934L5.6526 6.58876L2.8419 7.52566C2.6775 7.58046 2.5532 7.71648 2.51339 7.88513C2.47357 8.05378 2.52392 8.23102 2.64646 8.35356L4.79291 10.5L2.14645 13.1465L2 14L2.85356 13.8536L5.50002 11.2071L7.64646 13.3536C7.76899 13.4761 7.94623 13.5264 8.11489 13.4866C8.28354 13.4468 8.41955 13.3225 8.47435 13.1581L9.41143 10.3469L9.56016 10.2673ZM8.82138 9.52849L8.76403 9.5592C8.65137 9.61951 8.56608 9.72066 8.52567 9.84189L7.7815 12.0744L3.92562 8.21851L6.15812 7.47435C6.27966 7.43383 6.38101 7.34822 6.44126 7.23516L6.47143 7.17854L8.82138 9.52849ZM12.7178 7.4426L10.6636 8.54227L11.4024 9.28105L13.1897 8.32422C14.0759 7.84981 14.2538 6.65509 13.5443 5.94304L10.0589 2.44509C9.34701 1.73062 8.14697 1.90828 7.67261 2.79838L6.71556 4.59421L7.45476 5.33341L8.55511 3.26869C8.71323 2.97199 9.11324 2.91277 9.35055 3.15093L12.836 6.64888C13.0725 6.88623 13.0131 7.28446 12.7178 7.4426Z`})})}function dz(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M6.5 8C6.22386 8 6 8.22386 6 8.5C6 8.77614 6.22386 9 6.5 9H9.5C9.77614 9 10 8.77614 10 8.5C10 8.22386 9.77614 8 9.5 8H6.5ZM1 3.5C1 2.67157 1.67157 2 2.5 2H13.5C14.3284 2 15 2.67157 15 3.5V4.5C15 5.15311 14.5826 5.70873 14 5.91465V11.5C14 12.8807 12.8807 14 11.5 14H4.5C3.11929 14 2 12.8807 2 11.5V5.91465C1.4174 5.70873 1 5.15311 1 4.5V3.5ZM2.5 3C2.22386 3 2 3.22386 2 3.5V4.5C2 4.77614 2.22386 5 2.5 5H13.5C13.7761 5 14 4.77614 14 4.5V3.5C14 3.22386 13.7761 3 13.5 3H2.5ZM3 6V11.5C3 12.3284 3.67157 13 4.5 13H11.5C12.3284 13 13 12.3284 13 11.5V6H3Z`})})}function fz(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M12.854 14.8542L14.854 12.8542C15.049 12.6592 15.049 12.3422 14.854 12.1472L12.854 10.1472C12.659 9.95223 12.342 9.95223 12.147 10.1472C11.952 10.3422 11.952 10.6592 12.147 10.8542L13.293 12.0002H8.5C8.225 12.0002 8 11.7752 8 11.5002V5.50023C8 5.22523 8.225 5.00023 8.5 5.00023H13.293L12.147 6.14623C12.049 6.24423 12.001 6.37223 12.001 6.50023C12.001 6.62823 12.05 6.75623 12.147 6.85423C12.342 7.04923 12.659 7.04923 12.854 6.85423L14.854 4.85423C15.049 4.65923 15.049 4.34223 14.854 4.14723L12.854 2.14723C12.659 1.95223 12.342 1.95223 12.147 2.14723C11.952 2.34223 11.952 2.65923 12.147 2.85423L13.293 4.00023H8.5C7.673 4.00023 7 4.67323 7 5.50023V8.00023H1.5C1.224 8.00023 1 8.22423 1 8.50023C1 8.77623 1.224 9.00023 1.5 9.00023H7V11.5002C7 12.3272 7.673 13.0002 8.5 13.0002H13.293L12.147 14.1462C12.049 14.2442 12.001 14.3722 12.001 14.5002C12.001 14.6282 12.05 14.7562 12.147 14.8542C12.342 15.0492 12.659 15.0492 12.854 14.8542Z`})})}function pz({agent:e,session:t,shortcutHint:n,active:r=!1,searchSelected:i,now:a,onOpenAgent:o,onUpdateAgentFlags:s,reorderable:c=!1,dragging:l=!1,dropPosition:u,onAgentDragStart:d,onAgentDragEnd:f,onAgentDragOver:p,onAgentDrop:m,onOpenAgentMenu:h,onResume:g,onOpenSessionMenu:_,onShowPreview:v,onHidePreview:y,copy:b}){let S=(0,G.useRef)(!1),C=on(e),w=C?{kind:`agent`,agent:C}:t?{kind:`history`,session:t,fallbackTitle:b.sessionFallbackTitle(t.providerName)}:null;if(!w)return null;let T=KM(w,a),E=T.requiresResume,D=C?.id??``,O=t?.provider??``,k=t?.id??``,A=E?`code-active-session-row`:`code-agent-row`,j=C?zR(C):RR(t?.provider),M=()=>{if(E){y?.(),O&&k&&g?.(O,k,t?.providerHomeId);return}D&&o?.(D)};return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{tabIndex:0,className:`code-agent-row ${j?`has-provider`:``} ${E?`requires-resume`:``} ${r?`active`:``} ${i?`search-selected`:``} ${T.pinned?`pinned`:``} ${T.unread?`unread`:``} ${l?`dragging`:``} ${u?`drop-${u}`:``}`,draggable:c||void 0,"data-testid":A,"data-agent-id":C?.id,"data-activity-level":C?.activityLevel,"data-provider":t?.provider,"data-session-id":t?OA(t):void 0,"aria-label":T.rowTitle||T.title,onDragStart:e=>{!D||!c||(S.current=!0,d?.(e,D))},onDragEnd:()=>{f?.(),window.setTimeout(()=>{S.current=!1},0)},onDragOver:e=>D&&p?.(e,D),onDrop:e=>D&&m?.(e,D),onClick:e=>{if(S.current){e.preventDefault(),e.stopPropagation();return}M()},onMouseEnter:e=>{C?v?.(e,nz(C,T)):t&&v?.(e,rz(t,T))},onMouseLeave:y,onContextMenu:e=>{if(E){y?.(),O&&t&&_?.(e,O,OA(t));return}D&&h?.(e,D)},onKeyDown:e=>{E?O&&t&&_?.(e,O,OA(t)):D&&h?.(e,D),!e.defaultPrevented&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),M())},children:[j&&(0,K.jsx)(`span`,{className:`code-agent-row-provider-icon`,"aria-hidden":`true`,children:(0,K.jsx)(x,{name:j,variant:`color`})}),(0,K.jsxs)(`span`,{className:`code-agent-row-copy ${T.detailLabel?`has-details`:``}`,children:[(0,K.jsx)(`span`,{className:`code-agent-name`,children:T.title}),T.detailLabel&&(0,K.jsx)(`span`,{className:`code-agent-meta`,"data-testid":`code-agent-row-detail`,title:T.detailLabel,children:T.detailLabel})]}),(0,K.jsxs)(`span`,{className:`code-agent-row-trailing`,children:[T.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-agent-dot ${T.lifecycleStatus} ${T.turnActive?`turn-active`:``}`,title:T.commandTitle||T.lifecycleStatus}),T.forkedToNewWorktree&&(0,K.jsx)(`span`,{className:`code-agent-fork-new-worktree`,"data-testid":`code-agent-new-worktree-fork`,title:b.newWorktreeFork,"aria-label":b.newWorktreeFork,role:`img`,children:(0,K.jsx)(fz,{})}),T.scheduled&&(0,K.jsx)(`span`,{className:`code-agent-schedule-clock`,"data-testid":`code-agent-schedule-clock`,title:T.scheduleTitle,"aria-label":T.scheduleTitle||b.scheduledTask}),T.unread&&(0,K.jsx)(`span`,{className:`code-agent-unread`,title:b.unread}),T.ageVisible&&(0,K.jsx)(`span`,{className:`code-agent-age code-agent-relative-age`,"data-testid":`code-agent-row-age`,title:T.ageTitle,children:T.ageLabel}),e&&(0,K.jsxs)(`span`,{className:`code-agent-row-actions`,"aria-hidden":!1,children:[C&&(0,K.jsx)(`span`,{className:`code-agent-resource-action-slot`,"data-testid":`code-agent-resource-action-slot`,"data-agent-id":C.id}),(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row-action pin ${T.pinned?`active`:``}`,"data-testid":`code-agent-row-pin`,"aria-label":T.pinned?b.unpinAgent:b.pinAgent,title:T.pinned?b.unpinAgent:b.pinAgent,onClick:e=>{e.preventDefault(),e.stopPropagation(),C&&s?.(C,{pinned:!T.pinned})},children:T.pinned?(0,K.jsx)(uz,{}):(0,K.jsx)(lz,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row-action archive`,"data-testid":`code-agent-row-archive`,"aria-label":b.archiveAgent,title:b.archiveAgent,onClick:e=>{e.preventDefault(),e.stopPropagation(),C&&s?.(C,{archived:!0})},children:(0,K.jsx)(dz,{})})]}),(e||t)&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row-more`,"data-testid":`code-agent-row-more`,"aria-label":b.openOptions,title:b.openOptions,onClick:e=>{if(e.preventDefault(),e.stopPropagation(),E){y?.(),O&&t&&_?.(e,O,OA(t));return}D&&h?.(e,D)},children:(0,K.jsx)(tz,{})}),n&&(0,K.jsx)(`kbd`,{children:n})]})]}),C&&(0,K.jsx)(`div`,{className:`code-agent-resource-slot`,"data-testid":`code-agent-resource-slot`,"data-agent-id":C.id})]})}var mz=class{generation=0;begin(){let e=++this.generation;return{generation:e,isCurrent:()=>this.generation===e}}invalidate(){this.generation+=1}},hz=`farming.code.browserSectionsCollapsed.v1`,gz=`farming.code.agentResourcesExpanded.v1`;function _z(){try{let e=JSON.parse(localStorage.getItem(hz)||`[]`);return new Set(Array.isArray(e)?e.filter(e=>typeof e==`string`):[])}catch{return new Set}}function vz(e){try{localStorage.setItem(hz,JSON.stringify([...e]))}catch{}}function yz(){try{let e=JSON.parse(localStorage.getItem(gz)||`[]`);return new Set(Array.isArray(e)?e.filter(e=>typeof e==`string`):[])}catch{return new Set}}function bz(e){try{localStorage.setItem(gz,JSON.stringify([...e]))}catch{}}function xz(e){let t=e===`zh`;return{browsers:t?`浏览器`:`Browsers`,newBrowser:t?`新建标签页`:`New Tab`,createBrowser:t?`新建标签页`:`Create tab`,browserName:t?`标签页名称`:`Tab name`,renameBrowser:t?`重命名标签页`:`Rename Tab`,startBrowser:t?`启动标签页`:`Start Tab`,stopBrowser:t?`停止标签页`:`Stop Tab`,deleteBrowser:t?`关闭标签页`:`Close Tab`,failed:t?`标签页失败`:`Tab failed`,starting:t?`启动中…`:`Starting…`,stopping:t?`停止中…`:`Stopping…`,stopped:t?`已停止`:`Stopped`,renameFailed:t?`标签页重命名失败`:`Failed to rename tab`,transitionFailed:t?`标签页状态切换失败`:`Tab transition failed`,deleteFailed:t?`标签页关闭失败`:`Failed to close tab`,createFailed:t?`标签页创建失败`:`Failed to create tab`,showResources:t?`显示 Agent 资源`:`Show Agent resources`,hideResources:t?`隐藏 Agent 资源`:`Hide Agent resources`}}function Sz(){return(0,K.jsx)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M4.5 2.6a.75.75 0 0 1 1.15-.63l7 4.9a.75.75 0 0 1 0 1.23l-7 4.9A.75.75 0 0 1 4.5 12.4V2.6Z`})})}function Cz(e,t){return e.status===`running`?e.url.replace(/^https?:\/\//,``)||`about:blank`:e.status===`failed`?t.stopped:e.status===`starting`?t.starting:e.status===`stopping`?t.stopping:t.stopped}function wz({resource:e,active:t,controller:n,copy:r,onOpen:i}){let[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(e.name),l=e.status===`starting`||e.status===`stopping`,u=async()=>{let t=s.trim();if(o(!1),!t||t===e.name){c(e.name);return}await n.rename(e.id,t).catch(t=>{c(e.name),window.alert(t instanceof Error?t.message:r.renameFailed)})};return(0,K.jsxs)(`div`,{className:`farming-browser-row ${t?`active`:``} ${e.status===`running`?`running`:``}`,"data-testid":`farming-browser-row`,"data-browser-id":e.id,role:`button`,tabIndex:0,onClick:()=>i(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),i(e))},children:[(0,K.jsx)(`span`,{className:`farming-browser-resource-icon ${e.status}`,"aria-hidden":`true`,children:(0,K.jsx)(at,{})}),(0,K.jsxs)(`span`,{className:`farming-browser-row-copy`,children:[a?(0,K.jsx)(`input`,{autoFocus:!0,value:s,"aria-label":r.browserName,onClick:e=>e.stopPropagation(),onChange:e=>c(e.currentTarget.value),onBlur:()=>void u(),onKeyDown:t=>{t.stopPropagation(),t.key===`Enter`&&u(),t.key===`Escape`&&(c(e.name),o(!1))}}):(0,K.jsx)(`span`,{className:`farming-browser-row-name`,children:e.name}),(0,K.jsx)(`span`,{className:`farming-browser-row-detail`,title:e.status===`running`?e.url:void 0,children:Cz(e,r)})]}),(0,K.jsxs)(`span`,{className:`farming-browser-row-actions`,children:[(0,K.jsx)(`button`,{type:`button`,title:r.renameBrowser,"aria-label":r.renameBrowser,onClick:e=>{e.stopPropagation(),o(!0)},children:(0,K.jsx)(ke,{})}),(0,K.jsx)(`button`,{type:`button`,disabled:l,title:e.status===`running`?r.stopBrowser:r.startBrowser,"aria-label":e.status===`running`?r.stopBrowser:r.startBrowser,onClick:t=>{t.stopPropagation(),(e.status===`running`?n.stop(e.id):n.start(e.id)).catch(e=>window.alert(e instanceof Error?e.message:r.transitionFailed))},children:e.status===`running`?(0,K.jsx)(je,{}):(0,K.jsx)(Sz,{})}),(0,K.jsx)(`button`,{type:`button`,title:r.deleteBrowser,"aria-label":r.deleteBrowser,onClick:t=>{t.stopPropagation(),n.remove(e.id).catch(e=>{window.alert(e instanceof Error?e.message:r.deleteFailed)})},children:(0,K.jsx)(pt,{})})]})]})}function Tz({workspace:e,ownerAgentId:t,resources:n,activeBrowserId:r,controller:i,copy:a,collapsed:o,onToggle:s,onOpen:c}){let l=async()=>{try{let n=await i.create(e,{agentId:t});c(await i.start(n.id))}catch(e){window.alert(e instanceof Error?e.message:a.createFailed)}};return(0,K.jsxs)(`section`,{className:`farming-browser-section`,"data-testid":`farming-browser-section`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsxs)(`button`,{type:`button`,className:`farming-browser-section-toggle`,"aria-expanded":!o,onClick:s,children:[(0,K.jsx)(`span`,{className:`farming-browser-section-chevron`,"aria-hidden":`true`,children:o?(0,K.jsx)(mt,{}):(0,K.jsx)(Ge,{})}),(0,K.jsx)(`span`,{children:a.browsers}),n.length>0&&(0,K.jsx)(`small`,{children:n.length})]}),(0,K.jsx)(`button`,{type:`button`,className:`farming-browser-new`,title:a.newBrowser,"aria-label":a.newBrowser,onClick:()=>void l(),children:(0,K.jsx)(Le,{})})]}),!o&&(0,K.jsxs)(`div`,{className:`farming-browser-list`,children:[n.map(e=>(0,K.jsx)(wz,{resource:e,active:e.id===r,controller:i,copy:a,onOpen:c},e.id)),n.length===0&&(0,K.jsxs)(`button`,{type:`button`,className:`farming-browser-empty`,onClick:()=>void l(),children:[(0,K.jsx)(Le,{}),(0,K.jsx)(`span`,{children:a.createBrowser})]})]})]})}function Ez({expanded:e,copy:t,onToggle:n}){return(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row-action farming-agent-resources-toggle`,"data-testid":`code-agent-resources-toggle`,"aria-expanded":e,"aria-label":e?t.hideResources:t.showResources,title:e?t.hideResources:t.showResources,onClick:e=>{e.preventDefault(),e.stopPropagation(),n()},children:e?(0,K.jsx)(We,{}):(0,K.jsx)(Ae,{})})}function Dz(e){let t=document.querySelectorAll(`[data-testid="code-project-title"]`);for(let n of t)if(n.dataset.projectId===e)return n.closest(`[data-testid="code-project-group"]`)?.querySelector(`.code-project-expanded`)??null;return null}function Oz(e,t){return document.querySelector(`[data-testid="${t}"][data-agent-id="${CSS.escape(e)}"]`)}function kz({projects:e,collapsedProjectIds:t,activeBrowserId:n,controller:r,language:i,onOpen:a,additionalAgentResourceIds:o=new Set,renderAdditionalAgentResources:s,forceAvailable:c=!1}){let l=xz(i),u=r.loading===!1&&r.capability?.available===!0,d=c||u,[f,p]=(0,G.useState)(new Map),[m,h]=(0,G.useState)(_z),[g,_]=(0,G.useState)(yz),v=(0,G.useCallback)(()=>{let n=new Map;for(let r of e){if(t.has(r.id))continue;let e=Dz(r.id);e&&n.set(r.id,e);for(let e of r.agents){let t=Oz(e.id,`code-agent-resource-action-slot`),r=Oz(e.id,`code-agent-resource-slot`);t&&n.set(`agent-action:${e.id}`,t),r&&n.set(`agent-content:${e.id}`,r)}}p(e=>e.size===n.size&&[...n].every(([t,n])=>e.get(t)===n)?e:n)},[t,e]);(0,G.useLayoutEffect)(()=>{if(d){v();return}p(e=>e.size===0?e:new Map)},[d,v]),(0,G.useEffect)(()=>{if(!d)return;let e=new MutationObserver(v);return e.observe(document.body,{childList:!0,subtree:!0}),()=>e.disconnect()},[d,v]);let y=e=>{h(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),vz(n),n})},b=e=>{_(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),bz(n),n})};return d?(0,K.jsxs)(K.Fragment,{children:[e.map(e=>{if(!u)return null;let t=f.get(e.id);if(!t||!e.workspace)return null;let i=(r.byWorkspace.get(e.workspace)??[]).filter(e=>e.ownerType===`project`);return i.length===0?null:(0,nE.createPortal)((0,K.jsx)(Tz,{workspace:e.workspace,resources:i,activeBrowserId:n,controller:r,copy:l,collapsed:m.has(e.id),onToggle:()=>y(e.id),onOpen:a}),t,`browser-section:${e.id}`)}),e.flatMap(e=>e.agents.flatMap(t=>{let i=r.byAgentId.get(t.id)??[],c=o.has(t.id);if(!u&&!c)return[];let d=f.get(`agent-action:${t.id}`),p=f.get(`agent-content:${t.id}`),h=g.has(t.id),_=[];return d&&_.push((0,nE.createPortal)((0,K.jsx)(Ez,{expanded:h,copy:l,onToggle:()=>b(t.id)}),d,`browser-agent-toggle:${t.id}`)),p&&h&&_.push((0,nE.createPortal)((0,K.jsxs)(K.Fragment,{children:[s?.({agentId:t.id,workspace:e.workspace,expanded:h}),u&&(0,K.jsx)(Tz,{workspace:e.workspace,ownerAgentId:t.id,resources:i,activeBrowserId:n,controller:r,copy:l,collapsed:m.has(`agent:${t.id}`),onToggle:()=>y(`agent:${t.id}`),onOpen:a})]}),p,`browser-agent-section:${t.id}`)),_}))]}):null}async function Az(e,t){let n=await fetch(r(e),{...t,headers:{Accept:`application/json`,...t?.body?{"Content-Type":`application/json`}:{},...t?.headers}}),i=await n.json().catch(()=>({}));if(!n.ok)throw Error(i.error||`Browser request failed (${n.status})`);return i}function jz(e){let{collection:t,onDeletion:n,onResource:r}=e,[i,a]=(0,G.useState)(null),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(!0),[u,d]=(0,G.useState)(0),f=(0,G.useCallback)(e=>{r(e)},[r]);(0,G.useEffect)(()=>{let e=!0;return l(!0),s(``),Az(`/api/browsers/capability`).then(t=>{e&&(a(t),l(!1))}).catch(()=>{e&&(a(null),s(`Failed to check Browser availability`),l(!1))}),()=>{e=!1}},[u]);let p=(0,G.useCallback)(async(e,t={})=>{let n=await Az(`/api/browsers`,{method:`POST`,body:JSON.stringify({rootId:Ar(e),agentId:t.agentId,name:t.name,url:t.url})});return f(n),n},[f]),m=(0,G.useCallback)(async(e,t)=>{let n=await Az(`/api/browsers/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify({name:t})});return f(n),n},[f]),h=(0,G.useCallback)(async(e,t)=>{let n=await Az(`/api/browsers/${encodeURIComponent(e)}/${t}`,{method:`POST`});return f(n),n},[f]),g=(0,G.useCallback)(e=>h(e,`start`),[h]),_=(0,G.useCallback)(e=>h(e,`stop`),[h]),v=(0,G.useCallback)(async e=>{n(await Az(`/api/browsers/${encodeURIComponent(e)}`,{method:`DELETE`}))},[n]),y=(0,G.useCallback)(()=>{a(null),s(``),l(!0),d(e=>e+1)},[]),b=i?.available===!1?[]:t?.resources??[];return{resources:b,byWorkspace:(0,G.useMemo)(()=>{let e=new Map;for(let t of b){let n=e.get(t.workspace)??[];n.push(t),e.set(t.workspace,n)}return e},[b]),byAgentId:(0,G.useMemo)(()=>{let e=new Map;for(let t of b){if(t.ownerType!==`agent`||!t.ownerAgentId)continue;let n=e.get(t.ownerAgentId)??[];n.push(t),e.set(t.ownerAgentId,n)}return e},[b]),capability:i,capabilityError:o,loading:c,collectionLoading:t===null,create:p,rename:m,start:g,stop:_,remove:v,mergeResource:f,refreshCapability:y}}function Mz(e){let t=e===`zh`;return{title:t?`桌面`:`Desktops`,create:t?`创建隔离桌面`:`Create Isolated Desktop`,createFailed:t?`隔离桌面创建失败`:`Failed to create Isolated Desktop`,start:t?`启动桌面`:`Start Desktop`,stop:t?`停止桌面`:`Stop Desktop`,remove:t?`删除桌面`:`Delete Desktop`,removeConfirm:e=>t?`删除“${e}”及其隔离环境?此操作无法撤销。`:`Delete “${e}” and its isolated environment? This cannot be undone.`,rename:t?`重命名桌面`:`Rename Desktop`,more:t?`更多`:`More`,name:t?`桌面名称`:`Desktop name`,stopped:t?`已停止`:`Stopped`,starting:t?`启动中…`:`Starting…`,stopping:t?`停止中…`:`Stopping…`,removing:t?`删除中…`:`Deleting…`,failed:t?`启动失败`:`Failed`,humanControl:t?`由你控制`:`Human control`,agentControl:t?`由 Agent 控制`:`Agent control`,browserInUse:e=>t?`${e} 个浏览器正在使用`:`${e} browser${e===1?``:`s`} in use`,stopBrowsersFirst:t?`请先停止正在使用此桌面的浏览器`:`Stop the Browsers using this Desktop first`,renameFailed:t?`桌面重命名失败`:`Desktop rename failed`,transitionFailed:t?`桌面状态切换失败`:`Desktop transition failed`,deleteFailed:t?`桌面删除失败`:`Desktop deletion failed`}}function Nz(){return(0,K.jsx)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M4.5 2.6a.75.75 0 0 1 1.15-.63l7 4.9a.75.75 0 0 1 0 1.23l-7 4.9A.75.75 0 0 1 4.5 12.4V2.6Z`})})}function Pz(){return(0,K.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:[(0,K.jsx)(`circle`,{cx:`3`,cy:`8`,r:`1.1`}),(0,K.jsx)(`circle`,{cx:`8`,cy:`8`,r:`1.1`}),(0,K.jsx)(`circle`,{cx:`13`,cy:`8`,r:`1.1`})]})}function Fz({workspace:e,agentId:t,resource:n,active:r,controller:i,language:a,collapsed:o,isolatedBrowserCount:s,onToggle:c,onOpen:l}){let u=Mz(a),[d,f]=(0,G.useState)(!1),[p,m]=(0,G.useState)(n?.name||`Desktop`),[h,g]=(0,G.useState)(!1),[_,v]=(0,G.useState)(null),[y,b]=(0,G.useState)(``),x=(0,G.useRef)(null),S=(0,G.useRef)(null);(0,G.useEffect)(()=>{if(!h)return;let e=e=>{e.target instanceof Node&&(x.current?.contains(e.target)||S.current?.contains(e.target))||g(!1)},t=e=>{e.key===`Escape`&&(e.preventDefault(),g(!1),x.current?.focus())};return window.addEventListener(`pointerdown`,e,!0),window.addEventListener(`keydown`,t,!0),()=>{window.removeEventListener(`pointerdown`,e,!0),window.removeEventListener(`keydown`,t,!0)}},[h]);let C=async()=>{try{let n=await i.create(e,t);l(await i.start(n.id))}catch(e){window.alert(e instanceof Error?e.message:u.createFailed)}},w=async e=>{if(!(!n||_)){v(e),b(``);try{e===`remove`?await i.remove(n.id):e===`start`?await i.start(n.id):await i.stop(n.id)}catch(t){b(t instanceof Error?t.message:e===`remove`?u.deleteFailed:u.transitionFailed)}finally{v(null)}}},T=async()=>{if(!n)return;let e=p.trim();if(f(!1),!e||e===n.name){m(n.name);return}b(``);try{await i.rename(n.id,e)}catch(e){m(n.name),b(e instanceof Error?e.message:u.renameFailed)}},E=n?.controlOwner===`human`?u.humanControl:u.agentControl,D=y||(n?.status===`failed`?n.error||u.failed:n?.status===`starting`?u.starting:n?.status===`stopping`?u.stopping:n?.status===`running`?[E,s>0?u.browserInUse(s):``].filter(Boolean).join(` · `):u.stopped),O=_!==null||n?.status===`starting`||n?.status===`stopping`,k=n?.status===`running`&&s>0;return(0,K.jsxs)(`section`,{className:`farming-computer-section`,"data-testid":`farming-computer-section`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsxs)(`button`,{type:`button`,className:`farming-computer-section-toggle`,"aria-expanded":!o,onClick:c,children:[(0,K.jsx)(`span`,{"aria-hidden":`true`,children:o?(0,K.jsx)(mt,{}):(0,K.jsx)(Ge,{})}),(0,K.jsx)(`span`,{children:u.title}),n&&(0,K.jsx)(`small`,{children:`1`})]}),!n&&(0,K.jsx)(`button`,{type:`button`,title:u.create,"aria-label":u.create,onClick:()=>void C(),children:(0,K.jsx)(Le,{})})]}),!o&&(n?(0,K.jsxs)(`div`,{className:`farming-computer-row ${r?`active`:``}`,"data-testid":`farming-computer-row`,role:`button`,tabIndex:0,onClick:()=>l(n),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&l(n)},children:[(0,K.jsx)(`span`,{className:`farming-computer-resource-icon ${n.status}`,"aria-hidden":`true`,children:(0,K.jsx)(ze,{})}),(0,K.jsxs)(`span`,{className:`farming-computer-copy`,children:[d?(0,K.jsx)(`input`,{autoFocus:!0,value:p,"aria-label":u.name,onClick:e=>e.stopPropagation(),onChange:e=>m(e.currentTarget.value),onBlur:()=>void T(),onKeyDown:e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),T()):e.key===`Escape`&&(m(n.name),f(!1))}}):(0,K.jsx)(`span`,{className:`farming-computer-name`,children:n.name}),(0,K.jsx)(`span`,{className:`farming-computer-detail ${y?`error`:``}`,title:y||n.error,children:_===`remove`?u.removing:_===`stop`?u.stopping:_===`start`?u.starting:D})]}),(0,K.jsxs)(`span`,{className:`farming-computer-actions`,children:[(0,K.jsx)(`span`,{title:k?u.stopBrowsersFirst:void 0,children:(0,K.jsx)(`button`,{type:`button`,title:k?void 0:n.status===`running`?u.stop:u.start,"aria-label":n.status===`running`?u.stop:u.start,disabled:O||k,onClick:e=>{e.stopPropagation(),w(n.status===`running`?`stop`:`start`)},children:n.status===`running`?(0,K.jsx)(je,{}):(0,K.jsx)(Nz,{})})}),(0,K.jsxs)(`span`,{className:`farming-computer-more-wrap`,children:[(0,K.jsx)(`button`,{ref:x,type:`button`,title:u.more,"aria-label":u.more,"aria-haspopup":`menu`,"aria-expanded":h,disabled:O,onClick:e=>{e.stopPropagation(),g(e=>!e)},children:(0,K.jsx)(Pz,{})}),h&&(0,K.jsxs)(`div`,{ref:S,className:`farming-computer-more-menu`,role:`menu`,children:[(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,onClick:e=>{e.stopPropagation(),g(!1),m(n.name),f(!0)},children:u.rename}),(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,className:`danger`,onClick:e=>{e.stopPropagation(),g(!1),window.confirm(u.removeConfirm(n.name))&&w(`remove`)},children:u.remove})]})]})]})]}):(0,K.jsxs)(`button`,{type:`button`,className:`farming-computer-empty`,onClick:()=>void C(),children:[(0,K.jsx)(Le,{}),(0,K.jsx)(`span`,{children:u.create})]}))]})}async function Iz(e,t){let n=await fetch(r(e),{...t,headers:{Accept:`application/json`,...t?.body?{"Content-Type":`application/json`}:{},...t?.headers}}),i=await n.json().catch(()=>({}));if(!n.ok)throw Error(i.error||`Computer request failed (${n.status})`);return i}function Lz(e){let{collection:t,onDeletion:n,onResource:r}=e,[i,a]=(0,G.useState)(null),[o,s]=(0,G.useState)(``),[c,l]=(0,G.useState)(!0),[u,d]=(0,G.useState)(0),f=(0,G.useCallback)(e=>{r(e)},[r]);(0,G.useEffect)(()=>{let e=!0;return l(!0),s(``),Iz(`/api/computers/capability`).then(t=>{e&&(a(t),l(!1))}).catch(()=>{e&&(a(null),s(`Failed to check Computer Use availability`),l(!1))}),()=>{e=!1}},[u]);let p=(0,G.useCallback)(async(e,t,n)=>{let r=await Iz(`/api/computers`,{method:`POST`,body:JSON.stringify({rootId:Ar(e),agentId:t,name:n})});return f(r),r},[f]),m=(0,G.useCallback)(async(e,t)=>{let n=await Iz(`/api/computers/${encodeURIComponent(e)}/${t}`,{method:`POST`});return f(n),n},[f]),h=(0,G.useCallback)(async(e,t)=>{let n=await Iz(`/api/computers/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify({name:t})});return f(n),n},[f]),g=(0,G.useCallback)(async e=>{n(await Iz(`/api/computers/${encodeURIComponent(e)}`,{method:`DELETE`}))},[n]),_=(0,G.useCallback)(async(e,t)=>{let n=await Iz(`/api/computers/${encodeURIComponent(e)}/control`,{method:`POST`,body:JSON.stringify({owner:t})});return f(n),n},[f]),v=(0,G.useCallback)(async()=>{let e=await Iz(`/api/computers/prepare`,{method:`POST`});return a(e),e},[]),y=(0,G.useCallback)(()=>{a(null),s(``),l(!0),d(e=>e+1)},[]),b=(0,G.useMemo)(()=>new Map((t?.resources??[]).map(e=>[e.ownerAgentId,e])),[t?.resources]);return{resources:t?.resources??[],byAgentId:b,capability:i,capabilityError:o,loading:c,collectionLoading:t===null,create:p,start:(0,G.useCallback)(e=>m(e,`start`),[m]),stop:(0,G.useCallback)(e=>m(e,`stop`),[m]),rename:h,remove:g,takeControl:_,prepare:v,mergeResource:f,refreshCapability:y}}var Rz=[3,5,10,15,30,60,180];function zz(e){let t=e/1e3;return Rz.reduce((e,n)=>Math.abs(n-t)<Math.abs(e-t)?n:e)}function Bz(e){let t=Number(e?.receivedBytes),n=Number(e?.totalBytes);return!Number.isFinite(t)||!Number.isFinite(n)||n<=0?null:Math.max(0,Math.min(100,Math.floor(t/n*100)))}function Vz(e,t=Date.now()){let n=Date.parse(String(e?.startedAt||``)),r=e?.completedAt?Date.parse(e.completedAt):e?.preparedAt?Date.parse(e.preparedAt):t;return!Number.isFinite(n)||!Number.isFinite(r)||r<n?null:Math.floor((r-n)/1e3)}function Hz(e){let t=e===`zh`;return{title:t?`设置`:`Settings`,subtitle:t?`管理 Farming 的本地元数据。`:`Manage local Farming metadata.`,close:t?`关闭`:`Close`,back:t?`返回导航`:`Back to navigation`,general:t?`通用`:`General`,appearance:t?`外观`:`Appearance`,system:t?`跟随系统`:`System`,light:t?`浅色`:`Light`,dark:t?`深色`:`Dark`,interface:t?`界面`:`Interface`,interfaceSkin:t?`界面皮肤`:`Interface skin`,contentTextSize:t?`正文字号`:`Content text size`,farmingCode:`Farming Code`,farmingCrt:`Farming CRT`,farmingPet:`Farming Pet`,petAppearance:t?`提醒样式`:`Reminder style`,softGlow:t?`柔光`:`Soft glow`,blackHole:t?`黑洞`:`Black hole`,previewAppearance:e=>{let n=e===`black-hole`?t?`黑洞`:`black hole`:t?`柔光`:`soft glow`;return t?`预览${n}效果`:`Preview ${n}`},breakReminder:t?`休息提醒`:`Break reminder`,breakReminderHint:t?`按本页前台可见时间计时,离开 5 分钟后重置;90 分钟及以上休息 10 分钟。`:`Counts foreground time in this tab; resets after 5 minutes away. Intervals of 90 min or longer use a 10 min break.`,breakReminderValue:e=>{if(!e||e<=0)return t?`关闭`:`Off`;if(e===5)return t?`5 秒(仅用于观察效果)`:`5 sec (preview only)`;let n=e/60;if(n%60==0){let e=n/60;return t?`每 ${e} 小时`:`Every ${e} hr`}return t?`每 ${n} 分钟`:`Every ${n} min`},breakReminderOffMarker:t?`关闭`:`Off`,customBreakReminder:t?`自定义`:`Custom`,customBreakReminderMinutes:t?`自定义提醒间隔(分钟)`:`Custom reminder interval in minutes`,customBreakReminderUnit:t?`分钟`:`min`,language:t?`语言`:`Language`,english:`English`,chinese:`中文`,search:t?`搜索`:`Search`,composer:`Composer`,followUpBehavior:t?`后续消息行为`:`Follow-up behavior`,followUpBehaviorHint:t?`Agent 工作时,新消息默认排队到下一轮,或直接调整当前轮。按 ⌘/Ctrl + Enter 可仅对当前一条反向发送。`:`While an Agent is working, queue messages for the next turn or steer the current turn. Press ⌘/Ctrl + Enter to use the opposite behavior once.`,queue:`Queue`,steer:`Steer`,agentPermissions:t?`Agent 权限`:`Agent Permissions`,dangerousSkipLabel:t?`默认跳过所有 agent 权限检查`:`Skip all agent permission checks by default`,dangerousSkipHint:t?`开启后,新启动的 Codex、Claude、OpenCode、Qoder、Qwen、Aider、GitHub Copilot CLI、Amazon Q 等会使用各自的危险跳过权限 flag。只在可信沙箱中使用。`:`When enabled, new Codex, Claude, OpenCode, Qoder, Qwen, Aider, GitHub Copilot CLI, Amazon Q, and similar agents launch with their provider-specific dangerous skip flags. Use only in trusted sandboxes.`,searchTimeout:t?`搜索超时`:`Search timeout`,searchTimeoutValue:e=>t?e>=60?`${e/60} 分钟`:`${e} 秒`:e>=60?`${e/60} min`:`${e} sec`,updates:t?`更新`:`Updates`,refreshUpdates:t?`刷新`:`Refresh`,updateAction:t?`准备更新`:`Prepare update`,updateToVersion:e=>t?`准备 ${e}`:`Prepare ${e}`,updating:t?`准备中…`:`Preparing…`,restartToUpdate:t?`重启并应用`:`Restart to update`,checkingUpdates:t?`正在检查更新…`:`Checking for updates…`,currentVersion:t?`当前版本`:`Current`,latestVersion:t?`最新版本`:`Latest`,targetVersion:t?`升级版本`:`Target`,updateMethodLabel:e=>({npm:`npm`,"app-bundle":t?`兼容包`:`App bundle`,"source-deploy":t?`源码部署`:`Source deployment`,source:t?`源码检出`:`Source checkout`,"standalone-cli":t?`单文件 CLI`:`Standalone CLI`})[e]||e||`-`,upToDate:t?`已是最新版本`:`Up to date`,updateAvailable:t?`有新版本可用`:`Update available`,updateNotInstallable:t?`当前更新不可安装`:`Update is not installable`,updateDownloading:e=>e===null?t?`正在下载更新包…`:`Downloading update package…`:t?`正在下载更新包 ${e}%`:`Downloading update package ${e}%`,updateExtracting:t?`正在解压更新包…`:`Extracting update package…`,updateInstalling:t?`正在准备更新…`:`Preparing update…`,updateReady:t?`更新已准备好,重启后应用。`:`Update ready. Restart to apply it.`,updateRestarting:t?`新版本已安装,正在重启 Farming。`:`The new version is installed. Restarting Farming.`,updateRollingBack:t?`正在回退到旧版本…`:`Rolling back to the previous version…`,updateSucceeded:t?`更新成功。`:`Update completed.`,updateRolledBack:t?`新版本启动失败,已回退到旧版本。`:`The new version failed to start and Farming rolled back.`,updateElapsed:e=>{let n=Math.floor(e/60),r=e%60;return t?`已用时 ${n>0?`${n} 分 `:``}${r} 秒`:`Elapsed ${n>0?`${n}m `:``}${r}s`},loading:t?`加载中…`:`Loading…`,saving:t?`保存中…`:`Saving…`,saved:t?`已保存`:`Saved`,loadFailed:t?`加载设置失败`:`Failed to load settings`,saveFailed:t?`保存失败`:`Failed to save`}}function Uz({open:e,activeAgentId:t=null,language:n,uiPreferences:i,onClose:a,onPreviewPetAppearance:o,onSyncUiPreferences:s,onUpdateUiPreferences:c}){let l=(0,G.useMemo)(()=>Hz(n),[n]),u=yR(i.appearance),d=(0,G.useRef)(null),f=(0,G.useRef)(null),p=(0,G.useRef)(0),m=(0,G.useRef)(``),h=(0,G.useRef)({open:e,generation:0}),g=(0,G.useRef)(0),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(null),[x,S]=(0,G.useState)(15),[C,w]=(0,G.useState)(null),[T,E]=(0,G.useState)(null),[D,O]=(0,G.useState)(BI),[k,A]=(0,G.useState)(null),[j,M]=(0,G.useState)(()=>VI(void 0,u)),[N,P]=(0,G.useState)(null),[F,ee]=(0,G.useState)(``),[I,L]=(0,G.useState)(!1),[te,R]=(0,G.useState)(``),[ne,re]=(0,G.useState)(!1),[z,ie]=(0,G.useState)(!1),[ae,B]=(0,G.useState)(``),[oe,V]=(0,G.useState)(``);h.current.open!==e&&(h.current={open:e,generation:h.current.generation+1});let se=(0,G.useCallback)(()=>{if(!h.current.open)return;let e=h.current.generation,t=g.current+1;g.current=t,re(!0),V(``),b(null),fetch(r(`/api/settings`)).then(async n=>{if(!n.ok)throw Error(l.loadFailed);let r=await n.json();if(g.current!==t||h.current.generation!==e||!h.current.open)return;v(r.settings?.dangerouslySkipAgentPermissionsByDefault===!0);let i=gR(r.settings?.composerFollowUpBehavior);b(i),s({composerFollowUpBehavior:i}),S(zz(Number(r.settings?.searchTimeoutMs??15e3)))}).catch(()=>{g.current===t&&h.current.generation===e&&h.current.open&&V(l.loadFailed)}).finally(()=>{g.current===t&&h.current.generation===e&&h.current.open&&re(!1)})},[l.loadFailed,s]);(0,G.useEffect)(()=>(h.current.open=e,()=>{h.current={open:!1,generation:h.current.generation+1},g.current+=1,f.current!==null&&window.clearTimeout(f.current)}),[]),(0,G.useEffect)(()=>{e&&(ie(!1),JI(u).then(O),se(),window.requestAnimationFrame(()=>d.current?.focus({preventScroll:!0})))},[u,se,e]),(0,G.useEffect)(()=>{M(VI(void 0,u))},[u,e]),(0,G.useEffect)(()=>{!e||y===null||b(i.composerFollowUpBehavior)},[y,e,i.composerFollowUpBehavior]),(0,G.useEffect)(()=>{let e=e=>{let t=e.detail;O(RI(t?.intervalSeconds)),M(t?.appearance??VI(void 0,u))},t=e=>{YI(e.key)&&(O(BI()),M(VI(void 0,u)))};return window.addEventListener(SI,e),window.addEventListener(`storage`,t),()=>{window.removeEventListener(SI,e),window.removeEventListener(`storage`,t)}},[u]),(0,G.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),a())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[a,e]);let ce=(0,G.useCallback)((e=!0,t=!1)=>{t||(L(!0),R(``)),fetch(r(`/api/update${e?`?force=1`:``}`)).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||l.loadFailed);let n=t?.update??null;P(n);let r=n?.versions??[];ee(e=>{if(n?.state?.phase===`ready-to-restart`){let e=n.state.version,t=r.find(t=>t.version===e);if(t?.assetName)return t.assetName}return e&&r.some(t=>t.assetName===e)?e:r[0]?.assetName||``})}).catch(e=>{t||R(e instanceof Error?e.message:l.loadFailed)}).finally(()=>{t||L(!1)})},[l.loadFailed]),le=(0,G.useCallback)(e=>{S(e),V(``),f.current!==null&&window.clearTimeout(f.current),f.current=window.setTimeout(()=>{fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({searchTimeoutMs:e*1e3})}).then(async t=>{let n=await t.json().catch(()=>null);if(!t.ok)throw Error(n?.error||l.saveFailed);S(zz(Number(n?.settings?.searchTimeoutMs??e*1e3)))}).catch(e=>V(e instanceof Error?e.message:l.saveFailed))},120)},[l.saveFailed]),ue=(0,G.useCallback)(()=>{if(C===null)return;let e=C;w(null),le(e)},[C,le]),de=(0,G.useCallback)(()=>{if(T===null)return;let e=T;E(null),c({codeContentFontSize:e})},[T,c]),fe=(0,G.useCallback)(async e=>{let t=p.current+1;p.current=t;let n=D;return O(e),await qI(e,u)?(p.current===t&&V(``),!0):(p.current===t&&(O(n),V(l.saveFailed)),!1)},[l.saveFailed,u,D]),pe=(0,G.useCallback)(e=>{if(!WI(e)){V(l.saveFailed);return}V(``),M(e)},[l.saveFailed]),me=k??D,he=MI(me),ge=(0,G.useCallback)(e=>{A(NI(e))},[]),H=(0,G.useCallback)(()=>{if(k===null)return;let e=k;A(null),fe(e)},[k,fe]),_e=(0,G.useCallback)(e=>{if(e===``){fe(0);return}let t=Number(e);Number.isInteger(t)&&t>=1&&t<=240&&fe(t*60)},[fe]),ve=(0,G.useCallback)(()=>{let e=N?.state?.phase===`ready-to-restart`,t=N?.versions?.find(e=>e.assetName===F);if(!e&&!t?.available){ce(!0);return}L(!0),R(``),B(``),m.current=e?N?.state?.version||``:t?.version||t?.assetName||``,fetch(r(e?`/api/update/restart`:`/api/update/install`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e?{}:{assetName:F})}).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||l.saveFailed);P(e=>({...e??{},state:t?.update?.state??e?.state}))}).catch(e=>{m.current=``,R(e instanceof Error?e.message:l.saveFailed)}).finally(()=>L(!1))},[l,ce,F,N]);(0,G.useEffect)(()=>{e&&ce(!1)},[e,ce]);let ye=(0,G.useCallback)(e=>{v(e),ie(!0),V(``),B(``),fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({dangerouslySkipAgentPermissionsByDefault:e})}).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||l.saveFailed);v(t?.settings?.dangerouslySkipAgentPermissionsByDefault===!0),B(l.saved)}).catch(t=>{v(!e),V(t instanceof Error?t.message:l.saveFailed)}).finally(()=>ie(!1))},[l.saveFailed,l.saved]),be=(0,G.useCallback)(e=>{b(e),c({composerFollowUpBehavior:e})},[c]),xe=N?.state?.phase||``;if((0,G.useEffect)(()=>{if(!e||![`downloading`,`extracting`,`installing`,`restarting`,`rolling-back`].includes(xe))return;let t=window.setInterval(()=>ce(!1,!0),1500);return()=>window.clearInterval(t)},[e,ce,xe]),(0,G.useEffect)(()=>{!e||xe!==`succeeded`||!m.current||(N?.state?.version||N?.current?.releaseVersion||N?.current?.packageVersion||``)===m.current&&(m.current=``,window.location.reload())},[e,xe,N]),!e)return null;let Se=N?.versions??[],U=Se.find(e=>e.assetName===F),Ce=[`downloading`,`extracting`,`installing`,`restarting`,`rolling-back`].includes(xe),we=xe===`ready-to-restart`,Te=I||Ce,Ee=N?.method||N?.current?.type||``,De=l.updateMethodLabel(Ee),Oe=N?.current?.releaseVersion||N?.current?.packageVersion||N?.state?.previousVersion||`-`,ke=N?.latest?.version||`-`,Ae=we?N?.state?.version||U?.version||N?.selected?.version||ke:U?.version||N?.selected?.version||ke,je=Oe!==`-`&&Ae!==`-`&&Oe!==Ae&&(N?.available===!0||Te||we),Ne=Bz(N?.state),Pe=N?xe===`rolled-back`?l.updateRolledBack:xe===`failed`&&N?.state?.error?N.state.error:xe===`downloading`?l.updateDownloading(Ne):we?l.updateReady:xe===`extracting`?l.updateExtracting:xe===`installing`?l.updateInstalling:xe===`restarting`?l.updateRestarting:xe===`rolling-back`?l.updateRollingBack:N.available?l.updateAvailable:xe===`succeeded`?l.updateSucceeded:N.latest?.blockedReason||l.upToDate:l.checkingUpdates,Fe=Ce||we||[`succeeded`,`failed`,`rolled-back`].includes(xe)?Vz(N?.state):null,Ie=Fe===null?``:l.updateElapsed(Fe),Le=Ce?l.updating:we?l.restartToUpdate:U?.available&&Ae!==`-`?l.updateToVersion(Ae):l.updateAction;return(0,K.jsx)(`div`,{className:`code-settings-panel-overlay`,"data-testid":`code-settings-panel`,"data-pet-snapshot-exclude":!0,onPointerDown:e=>{e.target===e.currentTarget&&a()},children:(0,K.jsxs)(`aside`,{className:`code-settings-panel`,"aria-modal":`true`,role:`dialog`,"aria-labelledby":`code-settings-panel-title`,children:[(0,K.jsxs)(`header`,{className:`code-settings-panel-header`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-settings-panel-back`,onClick:a,"aria-label":l.back,children:(0,K.jsx)(dt,{})}),(0,K.jsx)(`div`,{children:(0,K.jsx)(`h2`,{id:`code-settings-panel-title`,children:l.title})}),(0,K.jsx)(`button`,{ref:d,type:`button`,className:`code-settings-panel-close`,onClick:a,"aria-label":l.close,children:(0,K.jsx)(pt,{})})]}),(0,K.jsxs)(`div`,{className:`code-settings-panel-body`,children:[(0,K.jsx)(`section`,{className:`code-settings-section compact`,children:(0,K.jsxs)(`div`,{className:`code-settings-inline-preferences`,children:[(0,K.jsxs)(`div`,{className:`code-settings-inline-choice`,children:[(0,K.jsx)(Re,{"aria-hidden":`true`}),(0,K.jsxs)(`div`,{className:`code-settings-segmented`,role:`group`,"aria-label":l.appearance,children:[(0,K.jsx)(`button`,{type:`button`,className:i.appearance===`system`?`active`:``,onClick:()=>c({appearance:`system`}),children:l.system}),(0,K.jsx)(`button`,{type:`button`,className:i.appearance===`light`?`active`:``,onClick:()=>c({appearance:`light`}),children:l.light}),(0,K.jsx)(`button`,{type:`button`,className:i.appearance===`dark`?`active`:``,onClick:()=>c({appearance:`dark`}),children:l.dark})]})]}),(0,K.jsx)(`div`,{className:`code-settings-inline-choice code-settings-language-choice`,children:(0,K.jsxs)(`div`,{className:`code-settings-segmented`,role:`group`,"aria-label":l.language,children:[(0,K.jsx)(`button`,{type:`button`,className:i.language===`en`?`active`:``,onClick:()=>c({language:`en`}),children:l.english}),(0,K.jsx)(`button`,{type:`button`,className:i.language===`zh`?`active`:``,onClick:()=>c({language:`zh`}),children:l.chinese})]})})]})}),(0,K.jsxs)(`section`,{className:`code-settings-section code-settings-group`,children:[(0,K.jsx)(`div`,{className:`code-settings-section-heading`,children:(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:l.interface})})}),(0,K.jsxs)(`div`,{className:`code-settings-card`,children:[(0,K.jsxs)(`div`,{className:`code-settings-choice-row code-settings-runtime-row`,children:[(0,K.jsx)(`div`,{className:`code-settings-row-copy`,children:(0,K.jsx)(`strong`,{children:l.interfaceSkin})}),(0,K.jsxs)(`div`,{className:`code-settings-segmented`,role:`group`,"aria-label":l.interfaceSkin,children:[(0,K.jsx)(`button`,{type:`button`,className:`active`,"data-testid":`code-settings-skin-code`,"aria-pressed":`true`,children:l.farmingCode}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-settings-skin-crt`,"aria-pressed":`false`,onClick:()=>window.location.assign(`${r(`/crt/`)}${t?`?agent=${encodeURIComponent(t)}`:``}`),children:l.farmingCrt})]})]}),(0,K.jsxs)(`div`,{className:`code-settings-choice-row code-settings-content-font-size-row`,children:[(0,K.jsx)(`div`,{className:`code-settings-row-copy`,children:(0,K.jsx)(`strong`,{children:l.contentTextSize})}),(0,K.jsx)(`input`,{type:`range`,min:`10`,max:`20`,step:`1`,value:T??i.codeContentFontSize,"aria-label":l.contentTextSize,onChange:e=>E(Number(e.target.value)),onPointerUp:de,onPointerCancel:de,onKeyUp:de,onBlur:de}),(0,K.jsxs)(`output`,{children:[T??i.codeContentFontSize,` px`]})]})]})]}),(0,K.jsxs)(`section`,{className:`code-settings-section code-settings-group`,children:[(0,K.jsx)(`div`,{className:`code-settings-section-heading`,children:(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:l.search})})}),(0,K.jsx)(`div`,{className:`code-settings-card`,children:(0,K.jsxs)(`div`,{className:`code-settings-choice-row code-settings-search-timeout-row`,children:[(0,K.jsx)(`div`,{className:`code-settings-row-copy`,children:(0,K.jsx)(`strong`,{children:l.searchTimeout})}),(0,K.jsx)(`input`,{type:`range`,min:`0`,max:String(Rz.length-1),step:`1`,value:Rz.indexOf(C??x),"aria-label":l.searchTimeout,onChange:e=>w(Rz[Number(e.target.value)]??15),onPointerUp:ue,onPointerCancel:ue,onKeyUp:ue,onBlur:ue}),(0,K.jsx)(`output`,{children:l.searchTimeoutValue(C??x)})]})})]}),(0,K.jsxs)(`section`,{className:`code-settings-section code-settings-group`,children:[(0,K.jsx)(`div`,{className:`code-settings-section-heading`,children:(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:l.farmingPet})})}),(0,K.jsxs)(`div`,{className:`code-settings-card`,children:[(0,K.jsxs)(`div`,{className:`code-settings-choice-row code-settings-pet-appearance-row`,children:[(0,K.jsx)(`div`,{className:`code-settings-row-copy`,children:(0,K.jsx)(`strong`,{children:l.petAppearance})}),(0,K.jsx)(`div`,{className:`code-settings-pet-appearance-options`,role:`group`,"aria-label":l.petAppearance,children:[`glass`,`black-hole`].map(e=>(0,K.jsxs)(`div`,{className:`code-settings-pet-appearance-option`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-settings-pet-appearance-select${j===e?` selected`:``}`,"aria-pressed":j===e,onClick:()=>pe(e),children:[(0,K.jsx)(`span`,{className:`code-pet-appearance-icon ${e}`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:e===`glass`?l.softGlow:l.blackHole})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-settings-pet-appearance-preview`,"aria-label":l.previewAppearance(e),title:l.previewAppearance(e),onClick:()=>o(e),children:(0,K.jsx)(Me,{})})]},e))})]}),(0,K.jsxs)(`div`,{className:`code-settings-choice-row code-settings-pet-rest-row`,children:[(0,K.jsxs)(`div`,{className:`code-settings-row-copy`,children:[(0,K.jsx)(`strong`,{children:l.breakReminder}),(0,K.jsx)(`small`,{children:l.breakReminderHint})]}),(0,K.jsxs)(`div`,{className:`code-settings-pet-rest-control`,children:[(0,K.jsx)(`input`,{type:`range`,min:`0`,max:String(kI.length-1),step:`any`,value:he,"aria-label":l.breakReminder,"aria-valuetext":l.breakReminderValue(me),onChange:e=>ge(Number(e.target.value)),onPointerUp:H,onPointerCancel:H,onKeyUp:H,onBlur:H}),(0,K.jsx)(`span`,{className:`code-settings-pet-rest-off-marker`,children:l.breakReminderOffMarker})]}),(0,K.jsxs)(`div`,{className:`code-settings-pet-rest-value`,children:[(0,K.jsx)(`output`,{children:l.breakReminderValue(me)}),(0,K.jsxs)(`label`,{className:`code-settings-pet-rest-custom`,children:[(0,K.jsx)(`span`,{children:l.customBreakReminder}),(0,K.jsx)(`input`,{type:`number`,min:1,max:240,step:`1`,value:D&&D>=60?D/60:``,placeholder:`1–240`,"aria-label":l.customBreakReminderMinutes,onChange:e=>_e(e.currentTarget.value)}),(0,K.jsx)(`span`,{children:l.customBreakReminderUnit})]})]})]})]})]}),(0,K.jsxs)(`section`,{className:`code-settings-section`,children:[(0,K.jsx)(`div`,{className:`code-settings-section-heading`,children:(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:l.composer})})}),(0,K.jsx)(`div`,{className:`code-settings-card`,children:(0,K.jsxs)(`div`,{className:`code-settings-choice-row`,"data-testid":`code-settings-follow-up-behavior`,children:[(0,K.jsxs)(`div`,{className:`code-settings-row-copy`,children:[(0,K.jsx)(`strong`,{children:l.followUpBehavior}),(0,K.jsx)(`small`,{children:l.followUpBehaviorHint})]}),(0,K.jsx)(`div`,{className:`code-settings-segmented`,role:`group`,"aria-label":l.followUpBehavior,children:[`queue`,`steer`].map(e=>(0,K.jsx)(`button`,{type:`button`,className:y===e?`active`:``,"aria-pressed":y===e,disabled:y===null,onClick:()=>be(e),children:e===`queue`?l.queue:l.steer},e))})]})})]}),(0,K.jsxs)(`section`,{className:`code-settings-section`,children:[(0,K.jsx)(`div`,{className:`code-settings-section-heading`,children:(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:l.updates})})}),(0,K.jsxs)(`div`,{className:`code-settings-update-card ${N?.available?`available`:``}`,"data-testid":`code-settings-update-card`,children:[(0,K.jsxs)(`div`,{className:`code-settings-update-overview`,children:[(0,K.jsxs)(`div`,{className:`code-settings-update-versions`,"aria-label":`${l.currentVersion} ${Oe}; ${l.latestVersion} ${ke}`,children:[(0,K.jsx)(`span`,{children:Oe}),je&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{className:`code-settings-update-arrow`,"aria-hidden":`true`,children:`→`}),(0,K.jsx)(`strong`,{children:Ae})]})]}),(0,K.jsxs)(`div`,{className:`code-settings-update-summary ${N?.available?`available`:``} ${xe?`phase-${xe}`:``}`,role:`status`,"aria-live":`polite`,children:[(0,K.jsxs)(`span`,{className:`code-settings-update-summary-text`,children:[Ee&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{children:De}),(0,K.jsx)(`span`,{"aria-hidden":`true`,children:` · `})]}),(0,K.jsx)(`span`,{children:Pe})]}),Ie&&(0,K.jsx)(`span`,{className:`code-settings-update-elapsed`,"aria-hidden":`true`,children:Ie})]})]}),(0,K.jsxs)(`div`,{className:`code-settings-update-actions`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-settings-update-refresh`,onClick:()=>ce(!0),disabled:Te,"aria-label":l.refreshUpdates,title:l.refreshUpdates,children:`↻`}),(!N||Ee===`npm`)&&(0,K.jsx)(`button`,{type:`button`,className:`primary`,"data-testid":`code-settings-update-action`,onClick:ve,disabled:Te||!we&&!U?.available,children:Le})]}),Se.length>1&&(0,K.jsx)(gt,{className:`code-settings-update-version`,ariaLabel:l.targetVersion,value:F,disabled:Te||we||Se.length===0,options:Se.map(e=>({value:e.assetName||``,label:`${e.version||e.assetName||`-`}${e.assetName&&e.assetName!==e.version?` · ${e.assetName}`:``}`})),onChange:ee}),te&&(0,K.jsx)(`div`,{className:`code-settings-error`,role:`alert`,children:te})]})]}),(0,K.jsxs)(`section`,{className:`code-settings-section`,children:[(0,K.jsxs)(`div`,{className:`code-settings-section-heading`,children:[(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:l.agentPermissions})}),(ne||z||ae)&&(0,K.jsx)(`span`,{className:`code-settings-status`,children:ne?l.loading:z?l.saving:ae})]}),(0,K.jsxs)(`div`,{className:`code-settings-choice-row dangerous`,children:[(0,K.jsx)(`span`,{children:l.dangerousSkipLabel}),(0,K.jsx)(`button`,{type:`button`,className:`code-settings-permission-toggle ${_?`active`:``}`,role:`checkbox`,"aria-label":l.dangerousSkipLabel,"aria-pressed":_,disabled:z,onClick:()=>ye(!_),children:(0,K.jsx)(Ze,{})})]}),oe&&(0,K.jsx)(`div`,{className:`code-settings-error`,role:`alert`,children:oe})]})]})]})})}var Wz=`\r`;function Gz(e){return[{type:`paste`,text:e},Wz]}var Kz={newAgent:`New Agent`,search:`Search`,history:`History`,codex:`Farming Code`,expandSidebar:`Expand sidebar`,collapseSidebar:`Collapse sidebar`,enterFocusMode:`Enter focus mode`,exitFocusMode:`Exit focus mode`,appModeOpen:`App mode and fullscreen`,appModeTitle:`Use Farming without browser controls`,appModeDescription:`Use a clean app window where the browser supports it, or fullscreen temporarily.`,appModeRecommended:`Recommended`,appModeInstallTitle:`Install Farming 2`,appModeInstallDescription:`Opens as its own window without tabs, the address bar, or browser extensions.`,appModeInstallAction:`Install Farming 2`,appModeInstallStepOne:`Open Chrome’s ⋮ menu, then choose “Cast, save and share”.`,appModeInstallStepTwo:`Choose “Install page as app”, then open Farming 2 from its app icon.`,appModeInstallUnavailableTitle:`Browser app installation is unavailable`,appModeInstallUnavailableInsecure:`This deployment uses an insecure HTTP connection, so the browser cannot install it as an app.`,appModeInstallUnavailableBrowser:`This browser has not provided an app-install prompt for this deployment.`,appModeFullscreenTitle:`Fullscreen for now`,appModeFullscreenDescription:`Hide browser controls for this window. Press Esc to leave fullscreen.`,terminalView:`Terminal`,transcriptView:`Chat`,switchToTerminal:`Switch to Terminal`,switchToChat:`Switch to Chat`,collapseComposer:`Hide input`,restoreComposer:`Show input`,agentTranscriptSyncing:`Syncing chat history...`,agentTranscriptUnavailable:`This session’s Chat history could not be loaded.`,agentTranscriptEmpty:`No conversation yet.`,agentTranscriptWaiting:`Agent is still working...`,agentTranscriptProcess:`Process`,agentTranscriptWorking:`Processing`,agentTranscriptThinking:`Thinking`,agentTranscriptRunning:`Running`,agentTranscriptReading:`Reading`,agentTranscriptSearching:`Searching`,agentTranscriptEditing:`Editing`,agentTranscriptPlanActive:`On plan`,agentTranscriptPlanProgress:(e,t)=>`Plan ${e}/${t}`,agentTranscriptFetching:`Fetching`,agentTranscriptUsingTool:`Using tool`,agentTranscriptActionRunning:e=>`Running: ${e}`,agentTranscriptActionFailed:e=>`Failed: ${e}`,agentTranscriptTerminalStatusUnavailable:`Terminal status could not be synchronized.`,agentTranscriptRetryTerminalStatus:`Retry`,agentTranscriptWorkingFor:e=>`Working for ${e}`,agentTranscriptWorkedFor:e=>`Worked for ${e}`,agentTranscriptCompactingContext:`Compacting context`,agentTranscriptProcessCount:e=>`${e} ${e===1?`event`:`events`}`,agentTranscriptCollaborationInProgress:`In progress`,agentTranscriptCollaborationHeading:`Collaborating agents`,agentTranscriptCollaborationNoFinalState:`Status syncing`,agentTranscriptCollaborationCompleted:`Completed`,agentTranscriptCollaborationInterrupted:`Paused`,agentTranscriptCollaborationFailed:`Failed`,agentTranscriptCollaborationPending:`Preparing`,agentTranscriptCollaborationClosed:`Closed`,agentTranscriptCollaborationActionCompleted:`Action completed`,agentTranscriptCollaborationPauseRequested:`Pause requested`,agentTranscriptCollaborationChildCount:e=>`${e} ${e===1?`child`:`children`}`,agentTranscriptCollaborationRecorded:`Activity`,agentTranscriptCollaborationStarted:`Created`,agentTranscriptCollaborationUpdated:`Message sent`,agentTranscriptCollaborationEarlierActivities:e=>`Show ${e} earlier ${e===1?`activity`:`activities`}`,agentTranscriptCollaborationEarlierEvidence:e=>`Show ${e} earlier ${e===1?`record`:`records`}`,agentTranscriptCopyDetails:`Copy details`,agentTranscriptCopiedDetails:`Copied`,agentTranscriptCopyAnswer:`Copy answer`,agentTranscriptCopiedAnswer:`Copied answer`,agentTranscriptFork:`Fork conversation`,agentTranscriptForkedFromAgent:`Forked from agent`,agentTranscriptReviewChanges:`Review`,agentTranscriptGitDiff:`Git diff`,agentTranscriptGitDiffLastCommit:`Git diff last commit`,agentTranscriptShowChanges:`Show file changes`,agentTranscriptShowMoreChanges:e=>`Show more files · ${e} remaining`,agentTranscriptLoadingChanges:`Loading exact changes…`,agentTranscriptChangesUnavailable:`Some exact file details could not be loaded.`,agentTranscriptTechnicalDetails:`Technical details`,agentTranscriptChangeKept:`Kept`,agentTranscriptChangeReverted:`Reverted`,agentTranscriptShowMoreFiles:e=>`Show ${e} more file${e===1?``:`s`}`,codexGoalTitle:`Goal`,codexGoalEmpty:`No active goal`,codexGoalOpen:`Open goal controls`,codexGoalObjective:`Objective`,codexGoalStatus:`Status`,codexGoalTokenBudget:`Token budget`,codexGoalNoBudget:`No budget`,codexGoalUsage:(e,t)=>`${e.toLocaleString()} tokens · ${Math.round(t/60)}m`,codexGoalStatusLabel:e=>({active:`Active`,paused:`Paused`,blocked:`Blocked`,usageLimited:`Usage limited`,budgetLimited:`Budget limited`,complete:`Complete`})[e]??e,codexGoalEdit:`Edit`,codexGoalStart:`Start`,codexGoalStop:`Stop`,codexGoalDelete:`Delete`,codexGoalSave:`Save goal`,codexGoalClear:`Clear`,codexGoalSaving:`Saving...`,searchProjectsOrAgents:`Search projects or agents`,clearSearch:`Clear search`,projectsAndAgents:`Projects and agents`,noAgentsYet:`No agents yet.`,noMatchingProjectsOrAgents:`No matching projects or agents.`,openNavigation:`Open navigation`,closeNavigation:`Close navigation`,resizeNavigation:`Resize navigation`,openOptions:`Open options`,openSettings:`Settings`,agentActions:`Agent actions`,appearanceSystem:`Appearance: System`,appearanceLight:`Appearance: Light`,appearanceDark:`Appearance: Dark`,languageEnglish:`Language: English`,languageChinese:`Language: 中文`,pinAgent:`Pin Agent`,unpinAgent:`Unpin Agent`,pinProject:`Pin project`,unpinProject:`Unpin project`,revealInFinder:`Reveal in Finder`,revealInFinderFailed:`Failed to reveal project in Finder`,createPermanentWorktree:`Create permanent worktree`,permanentWorktreeCreated:`Permanent worktree created`,permanentWorktreeFailed:`Failed to create permanent worktree`,markAllAsRead:`Mark all as read`,renameAgent:`Rename Agent`,renameProject:`Rename project`,createBrowser:`Create Browser`,createIsolatedDesktop:`Create Isolated Desktop`,archiveAgent:`Archive`,reorderAgentFailed:`Failed to reorder Agent`,markAsRead:`Mark as read`,markAsUnread:`Mark as unread`,copyWorkingDirectory:`Copy working directory`,copiedWorkingDirectory:`Copied working directory`,copyFailed:`Copy failed`,sharePage:`Share current page`,scanToOpenOnPhone:`Scan to open on phone`,copyFullShareLink:`Copy current page link`,copiedShareLink:`Current page link copied`,shareLinkFailed:`Share link unavailable`,sharedLocationUnavailable:e=>`Unable to locate shared path: ${e}`,shareLinkExpired:`Expired`,refreshShareLink:`Refresh`,brandStoryOrigin:`Farming Code began with a simple idea: when several coding agents work at once, people should not have to bounce between terminals, editors, and browser tabs.`,brandStoryPurpose:`It brings conversations, terminals, project files, and progress into one calm workspace, so attention stays on what matters.`,brandGithub:`GitHub`,renameInstance:`Rename instance`,instanceNameTitle:`Rename Farming instance`,instanceNameDescription:`This name appears in the sidebar and browser tab for this Farming machine.`,instanceNamePlaceholder:`Machine name`,instanceNameSaveFailed:`Could not save the instance name.`,mobileShareTitle:`Share page`,mobileForwardTitle:`Send this page`,mobileForwardHint:`Copy the link to send the current view to someone else.`,mobileShareCopyAction:`Copy link`,mobileShareCopied:`Copied`,mobileInstallTitle:`Add to Home Screen`,mobileInstallChromeHint:`Make sure this page is open in your system browser or Chrome.`,mobileInstallShareStep:`Tap Share in the browser toolbar.`,mobileInstallMoreStep:`If it is hidden, tap •••, then Share.`,mobileInstallAddStep:`Choose “Add to Home Screen”.`,mobileInstallOpenStep:`Open Farming from its Home Screen icon next time.`,mobileShareInstalled:`Farming is already open as a Home Screen app.`,forkSameWorktree:`Fork into same worktree`,forkNewWorktree:`Fork into new worktree`,newWorktreeFork:`Forked to new worktree`,scheduledTask:`Scheduled task`,killAgent:`Kill Agent`,killAgentQuestion:`Kill Agent?`,openSession:`Open Session`,pinChat:`Pin chat`,unpinChat:`Unpin chat`,archiveChat:`Archive`,archiveChats:`Archive chats`,archiveProject:`Archive Project`,removeProject:`Remove Project`,deleteWorktree:`Permanently Delete Worktree`,deleteWorktreeQuestion:`Permanently delete worktree?`,deleteWorktreeDescription:`This permanently deletes the worktree and all of its files.`,forceDelete:`Permanently Delete`,cancel:`Cancel`,retry:`Retry`,save:`Save`,stopAgentDescription:e=>`Stop ${e} and close its terminal.`,acknowledgeUnprovenAcpExit:`Confirm Exit and Remove`,acknowledgeUnprovenAcpExitDescription:e=>`Farming cannot prove that ${e}'s legacy ACP process exited during the upgrade. Continue only after verifying it has exited at the operating-system level. This removes Farming metadata and does not stop an unknown process.`,permissionModeLabel:(e,t)=>t,permissionModeDescription:(e,t)=>t,acpModeLabel:(e,t)=>({"read-only":`Read-only`,agent:`Workspace`,"agent-full-access":`Full access`,auto:`Auto`,default:`Manual`,acceptEdits:`Accept edits`,plan:`Plan`,dontAsk:`Don't ask`,bypassPermissions:`Bypass permissions`,build:`Build`})[e]??t,acpModeDescription:(e,t)=>({"read-only":`Read and analyze by default. File writes and commands that need more access require approval. Network access is off.`,agent:`Read and write inside this workspace and run sandboxed commands. Network and out-of-workspace access require approval.`,"agent-full-access":`Access files outside this workspace and use the network without approval prompts. Use only in a trusted environment.`,auto:`Use the model classifier to approve or deny permission requests.`,default:`Prompt before operations that require approval.`,acceptEdits:`Approve file edits automatically; ask about other operations that need permission.`,plan:`Plan and inspect without modifying files.`,dontAsk:`Do not show permission prompts; deny operations that were not already allowed.`,bypassPermissions:`Bypass permission checks. Use only in a trusted environment.`,build:`Run tools according to the permissions configured for this Agent.`})[e]??t,reasoningOptionLabel:(e,t)=>t,serviceTierLabel:(e,t)=>t,serviceTierDescription:(e,t)=>t,messageMode:`Message`,goalMode:`Goal`,planMode:`Plan`,askFollowUpChanges:`Ask for follow-up changes`,shellCommandPlaceholder:`Type a shell command`,describeAgentGoal:`Describe the goal for this agent`,describePlanFirst:`Describe what should be planned first`,openAgentTerminalFirst:`Open an agent terminal first`,queuedMessages:e=>`${e} queued messages`,sendQueuedMessage:`Send next`,steerQueuedMessage:`Steer`,discardQueuedMessage:`Discard queued message`,editQueuedMessage:`Remove from queue and edit`,messageAwaitingAcceptance:`Waiting for Agent`,messageNotAccepted:`Not accepted`,addContext:`Add context`,attachFile:`Attach file`,fileContext:`File context`,acpSignOut:`Sign out`,acpSigningOut:`Signing out…`,acpSignOutDescription:`Sign out of this ACP Agent`,setObjective:`Set objective`,planFirst:`Plan first`,clearComposerMode:`Clear composer mode`,agentPermissionMode:`Agent permission mode`,permissionsPrompt:`Launch permission profile`,permissionProfileSavedForNextLaunch:`Saved for new agents. Running sessions keep the permissions they launched with.`,permissionProfileRestarting:`Switching agent permissions…`,runtimeModeRestarting:`Restarting Agent…`,terminalProfileApplying:`Applying model to Codex Terminal…`,terminalProfileApplied:`Codex Terminal model updated.`,terminalProfileFailed:e=>`Codex Terminal model was not changed: ${e}`,configurationDeferred:`Model change will apply after the current turn finishes.`,permissionDeferred:`Permission change will apply after the current turn finishes.`,sessionSettingsDeferred:`Session setting changes will apply after the current turn finishes.`,agentRestartTimedOut:`Agent restart timed out. The previous Agent remains available; try switching again.`,permissionRestartHint:`The running agent restarts to apply these permissions. If it has no resumable session id yet, a fresh session starts.`,modelAndReasoning:`Model and reasoning`,reasoning:`Reasoning`,speed:`Speed`,startDictation:`Start dictation`,stopDictation:`Stop dictation`,speechUnsupported:`Speech recognition is not supported in this browser`,mobileDictationHint:`Use the microphone key on the iOS keyboard to dictate.`,sendMessage:`Send message`,interruptAgent:`Interrupt agent`,startOrSelectAgent:`Start or select an agent`,startOrSelectAgentDescription:`Projects live on the left. Open any agent terminal without closing the rest of the workspace.`,emptyWorkspaceWelcome:`Welcome to Farming`,emptyWorkspaceWelcomeDescription:`Continue earlier work, or start a new Agent.`,emptyWorkspaceContinue:`Continue earlier work`,emptyWorkspaceContinueDescription:`Resume Codex, Claude, and other Agent sessions from History.`,emptyWorkspaceNewAgentDescription:`Start a new coding task in the current project.`,plugins:`Plugins`,emptyWorkspacePluginsDescription:`Manage capabilities available to Farming and Agents.`,emptyWorkspaceSearchDescription:`Find projects, Agents, and history.`,emptyWorkspaceShareDescription:`Open Farming on your phone or another device.`,emptyWorkspaceFocus:`Focus mode`,emptyWorkspaceFocusDescription:`Hide distractions and focus on the current task.`,emptyWorkspaceCollapseDescription:`Give the workspace more room.`,historySummary:(e,t,n,r)=>`${n+r} history agents`,searchHistory:`Search history`,noHistoryYet:`No history yet`,noHistoryDescription:`Agents moved off the main page will appear here.`,historyAgents:`History Agents`,historyPagination:`History pages`,historyPageStatus:(e,t,n,r)=>`${e} / ${t}${r?`+`:``} · ${n} loaded`,historyProviderSessionTotal:e=>`${e} provider sessions found`,previousPage:`Previous page`,nextPage:`Next page`,agentSessions:`Agent Sessions`,recentWorkspaces:`Recent Workspaces`,agentsSessionsSummary:(e,t)=>`${e} agents · ${t} sessions`,projectAgentsSummary:(e,t,n)=>[`${e} Agent${e===1?``:`s`}`,`${t} unread`,`${n} running`].join(` · `),restore:`Restore`,continueRun:`Continue`,open:`Open`,archived:`Archived`,pinned:`Pinned`,unread:`Unread`,showMore:`Show more`,showLess:`Show less`,showAgents:`Show agents`,hideAgents:`Hide agents`,latest:`Latest`,upgrade:`UPGRADE`,updating:`UPDATING`,retryUpdate:`RETRY`,checkForUpdates:`Check for updates`,updateFailed:`Update failed`,upgradeToVersion:e=>e?`Upgrade to ${e}`:`Upgrade Farming Code`,sessionFallbackTitle:e=>`${e||`Agent`} session`,resumeSessionAria:e=>`Resume ${e}`,resultsCount:e=>`${e} results`,noMatchingAgents:`No matching agents`,searchHint:`Search by Agent title, session title, or project.`,searchEmptyTitle:`Start a search`,searchEmptyDescription:`Type an Agent title, session title, or project name or path.`,agents:`Agents`,files:`Files`,changes:`Changes`,changedFiles:`Changed files`,trackedChanges:`Tracked`,untrackedChanges:`Untracked`,reviewChanges:`Review`,refreshChanges:`Refresh changes`,worktrees:`Worktrees`,showWorktrees:`Show repository worktrees`,worktreeCurrent:`current`,worktreeMain:`main`,worktreeDetached:`detached`,worktreeLocked:`locked`,worktreePrunable:`prunable`,worktreeLoadFailed:`Unable to load repository worktrees`,gitHistory:`History`,gitHistoryEmpty:`No commits yet`,gitHistoryNotRepository:`This project is not a Git repository`,gitHistoryLoadMore:`Load more`,gitHistoryView:`History view`,gitHistoryCurrentScope:`Current`,gitHistoryAllScope:`All`,gitHistoryCurrentBranch:`Current branch`,gitHistoryAllBranches:`All branches`,gitHistoryCommitMessage:`Message`,gitHistoryParent:`Compare with parent`,gitHistoryRootCommit:`Root commit`,gitHistoryReviewCommit:`Review commit`,gitHistoryCommitChanges:e=>`${e} file${e===1?``:`s`} changed`,gitHistoryNoChanges:`No file changes`,gitHistoryChangesTruncated:`More changed files were omitted`,searchOrPathLine:`Search or path:line`,searchFilesOrJump:`Search files or jump to path line`,openEditors:`OPEN EDITORS`,loading:`Loading...`,currentInfoLoadFailed:`Failed to load current information.`,searching:`Searching...`,noMatches:`No matches`,searchIgnoredFolders:`Also search ignored folders`,searchIncomplete:e=>`Search stopped early. Current timeout: ${Math.round(e/1e3)}s.`,terminalSearchPlaceholder:`Find in terminal`,terminalSearchPrevious:`Previous match`,terminalSearchNext:`Next match`,terminalSearchClose:`Close terminal search`,terminalSearchCaseSensitive:`Match case`,terminalSearchWholeWord:`Match whole word`,terminalSearchRegex:`Use regular expression`,terminalSearchNoResults:`No results`,terminalSearchResults:(e,t)=>`${e}/${t}`,terminalRecoveryRequesting:`Loading terminal state…`,terminalRecoveryInstalling:`Terminal state received. Restoring screen…`,terminalRecoveryRetrying:e=>`Terminal state unavailable. Retrying in ${e}s…`,terminalRecoveryElapsed:e=>`Waiting ${e}s`,terminalRecoveryAttempt:e=>`Attempt ${e}`,terminalSessionUnavailable:`Terminal session unavailable`,acpPermissionAllow:`Allow`,acpPermissionTitle:`Agent needs permission`,acpPermissionTool:`Requested tool`,file:`File`,folder:`Folder`,go:`Go`,moreMatchesOmitted:`More matches omitted`,stickyFolderPath:`Sticky folder path`,containsUncommittedChanges:`Contains uncommitted changes`,changedOnDisk:`Changed on disk`,unsavedChanges:`Unsaved changes`,gitStatus:e=>`Git status: ${e}`,renameEntry:e=>`Rename ${e}`,newFile:`New File`,newFolder:`New Folder`,refreshFiles:`Refresh files`,refreshingFiles:`Refreshing files…`,filesRefreshed:`Files refreshed`,filesRefreshFailed:`Files refresh failed`,refresh:`Refresh`,rename:`Rename`,copyRelativePath:`Copy Relative Path`,copyShareUrl:`Copy Share URL`,delete:`Delete`,deleteFolderContents:e=>`Delete folder and all contents: ${e||``}`,deleteFile:e=>`Delete file: ${e||``}`,saveFile:`Save file`,savingFile:`Saving file`,reloadFile:`Reload file`,overwriteChangedFile:`Overwrite changed file`,openFileDiff:`Open File Diff`,openFileDiffFor:e=>`Open diff for ${e}`,closeDiff:`Close diff`,openFilePreview:`Open preview`,showFileSource:`Show source`,enableWordWrap:`Enable word wrap`,disableWordWrap:`Disable word wrap`,openMarkdownPreview:`Open Markdown preview`,showMarkdownSource:`Show Markdown source`,openMarkdownSplitPreview:`Open Markdown preview to side`,closeMarkdownSplitPreview:`Close Markdown side preview`,markdownPreviewFor:e=>`Markdown preview for ${e}`,markdownFrontMatter:`Front matter`,markdownHeadingAnchor:`Link to heading`,mermaidDiagram:`Mermaid diagram`,mermaidDiagramControls:`Mermaid diagram controls`,mermaidRendering:`Rendering diagram...`,mermaidRenderFailed:`Unable to render Mermaid diagram`,mermaidZoomIn:`Zoom in`,mermaidZoomOut:`Zoom out`,mermaidPanMode:`Toggle pan mode`,mermaidEnterFullscreen:`Open fullscreen diagram`,mermaidExitFullscreen:`Close fullscreen diagram`,mermaidResetView:`Reset view`,mermaidCopySource:`Copy Mermaid source`,mermaidCopiedSource:`Copied Mermaid source`,fileDiff:`File Diff`,loadingDiff:`Loading diff...`,noFileDiff:`No file changes.`,diffUnavailable:`Diff content is unavailable for this file.`,binaryDiffUnavailable:`Binary file diff is unavailable.`,diffTooLarge:`Diff is too large to display.`,deletedFileDiffOnly:`This deleted file is only available as a diff.`,showGitBlame:`Show git blame`,hideGitBlame:`Hide git blame`,gitBlameAnnotations:`Git blame annotations`,gitBlameDetails:`Git blame details`,filePath:`File path`,editorFor:e=>`Editor for ${e}`,revealInExplorer:e=>`Reveal ${e} in Explorer`,previewFor:e=>`Preview for ${e}`,author:`Author`,commit:`Commit`,date:`Date`,line:`Line`,unknown:`Unknown`,uncommitted:`Uncommitted`,closeBlameDetails:`Close blame details`,cut:`Cut`,copy:`Copy`,paste:`Paste`,selectAll:`Select All`,annotateWithBlame:`Annotate with Blame`,hideBlame:`Hide Blame`,openLineChangesWithPreviousRevision:`Open Line Changes with Previous Revision`,openLineChangesWithWorkingFile:`Open Line Changes with Working File`,lineChanges:`Line changes`,loadingLineChanges:`Loading line changes...`,noLineChanges:`No line changes for this line.`,closeLineChanges:`Close line changes`,close:`Close`,closeFile:e=>`Close ${e}`,closeOthers:`Close Others`,closeToRight:`Close to the Right`,closeSaved:`Close Saved`,closeAll:`Close All`,saveBeforeCloseTitle:e=>`Save changes to ${e}?`,saveBeforeCloseDescription:`If you do not save, your changes will be lost.`,dontSave:`Don't Save`,loadingBlame:`Loading blame...`,notGitRepository:`Not a git repository.`,noCommittedLines:`No committed lines.`,cursorPosition:(e,t)=>`Ln ${e}, Col ${t}`,startMainAgent:`Start Main Agent`,startNewAgent:`Start New Agent`,loadingAgents:`Loading agents...`,agentListUnavailable:`Agent list unavailable.`,noSupportedAgentsFound:`No supported agents found.`,resumePreviousMainAgent:`Resume previous Main Agent`,codingAgents:`coding agents`,otherAgents:`Shell`,workspace:`Workspace:`,workspacePathPlaceholder:`/path/to/workspace`,chooseWorkspaceDirectory:`Choose workspace folder`,workspaceDirectoryBrowserFailed:`Couldn’t read this directory.`,workspaceDirectoryBrowserHostHint:`Browse folders on the Farming host.`,workspaceDirectoryBrowserGo:`Go to directory`,workspaceDirectoryBrowserParent:`Parent directory`,workspaceDirectoryBrowserEmpty:`No subdirectories.`,workspaceDirectoryBrowserTruncated:`Only the first 500 folders are shown. Enter a more specific path to continue.`,workspaceDirectoryBrowserSelect:`Select this folder`,workspaceMissingTitle:`Create this workspace?`,workspaceMissingDescription:`This directory does not exist yet. Farming can create it and start the Agent there.`,workspaceCreateAndStart:`Create & Start`,workspaceCreating:`Creating...`,workspaceCreateFailedTitle:`Couldn’t create workspace`,workspaceCreateForbiddenDescription:`Farming does not have permission to create this directory. Choose another location or update the parent directory permissions.`,workspaceCreateFailedDescription:`Farming couldn’t create this directory. Check the path and try again.`,returnToWorkspace:`Change Path`,recentWorkspacesLower:`recent workspaces`,start:`Start`,back:`Back`,backToAgent:`Back to Agent`,goBack:`Go Back`,goForward:`Go Forward`,backendConnecting:`Loading...`,backendActionPending:`Still reconnecting. This action was not sent.`,backendConnectionLost:`Farming backend is still unavailable. Retrying...`,backendBusinessRecovering:`Farming backend is restoring business state...`,backendBusinessUnavailable:`Farming backend business state is not responding. Waiting for recovery...`},qz={newAgent:`新建 Agent`,search:`搜索`,history:`历史`,codex:`Farming Code`,expandSidebar:`展开侧边栏`,collapseSidebar:`收起侧边栏`,enterFocusMode:`进入沉浸模式`,exitFocusMode:`退出沉浸模式`,appModeOpen:`应用模式与全屏`,appModeTitle:`隐藏浏览器控制`,appModeDescription:`浏览器支持时可安装为独立应用窗口,也可以临时进入全屏。`,appModeRecommended:`推荐`,appModeInstallTitle:`安装 Farming 2`,appModeInstallDescription:`以后从独立窗口打开,不显示标签栏、地址栏和浏览器扩展。`,appModeInstallAction:`安装 Farming 2`,appModeInstallStepOne:`打开 Chrome 右上角 ⋮,选择“投放、保存和分享”。`,appModeInstallStepTwo:`选择“将网页安装为应用”,以后从 Farming 2 应用图标打开。`,appModeInstallUnavailableTitle:`无法安装为浏览器应用`,appModeInstallUnavailableInsecure:`当前部署使用不安全的 HTTP 连接,浏览器无法将其安装为应用。`,appModeInstallUnavailableBrowser:`当前浏览器没有为此部署提供应用安装入口。`,appModeFullscreenTitle:`暂时全屏`,appModeFullscreenDescription:`只为当前窗口隐藏浏览器控制,按 Esc 即可退出。`,terminalView:`终端`,transcriptView:`对话`,switchToTerminal:`切换到终端`,switchToChat:`切换到对话`,collapseComposer:`收起输入框`,restoreComposer:`唤出输入框`,agentTranscriptSyncing:`正在同步聊天历史...`,agentTranscriptUnavailable:`无法加载此会话的 Chat 历史。`,agentTranscriptEmpty:`还没有对话。`,agentTranscriptWaiting:`Agent 仍在工作...`,agentTranscriptProcess:`执行过程`,agentTranscriptWorking:`处理中`,agentTranscriptThinking:`思考中`,agentTranscriptRunning:`运行命令中`,agentTranscriptReading:`读取文件中`,agentTranscriptSearching:`搜索中`,agentTranscriptEditing:`修改文件中`,agentTranscriptPlanActive:`执行计划中`,agentTranscriptPlanProgress:(e,t)=>`执行计划 ${e}/${t}`,agentTranscriptFetching:`获取信息中`,agentTranscriptUsingTool:`调用工具中`,agentTranscriptActionRunning:e=>`正在执行:${e}`,agentTranscriptActionFailed:e=>`失败:${e}`,agentTranscriptTerminalStatusUnavailable:`终端状态未能同步。`,agentTranscriptRetryTerminalStatus:`重试`,agentTranscriptWorkingFor:e=>`Working for ${e}`,agentTranscriptWorkedFor:e=>`Worked for ${e}`,agentTranscriptCompactingContext:`正在压缩上下文`,agentTranscriptProcessCount:e=>`${e} 个事件`,agentTranscriptCollaborationInProgress:`进行中`,agentTranscriptCollaborationHeading:`协作 Agent`,agentTranscriptCollaborationNoFinalState:`状态同步中`,agentTranscriptCollaborationCompleted:`已完成`,agentTranscriptCollaborationInterrupted:`已暂停`,agentTranscriptCollaborationFailed:`失败`,agentTranscriptCollaborationPending:`准备中`,agentTranscriptCollaborationClosed:`已关闭`,agentTranscriptCollaborationActionCompleted:`动作已完成`,agentTranscriptCollaborationPauseRequested:`已请求暂停`,agentTranscriptCollaborationChildCount:e=>`${e} 个子 Agent`,agentTranscriptCollaborationRecorded:`活动记录`,agentTranscriptCollaborationStarted:`已创建`,agentTranscriptCollaborationUpdated:`已发送消息`,agentTranscriptCollaborationEarlierActivities:e=>`显示更早 ${e} 条活动`,agentTranscriptCollaborationEarlierEvidence:e=>`显示更早 ${e} 条记录`,agentTranscriptCopyDetails:`复制详情`,agentTranscriptCopiedDetails:`已复制`,agentTranscriptCopyAnswer:`复制答复`,agentTranscriptCopiedAnswer:`已复制答复`,agentTranscriptFork:`分叉对话`,agentTranscriptForkedFromAgent:`从 Agent 分叉`,agentTranscriptReviewChanges:`Review`,agentTranscriptGitDiff:`Git diff`,agentTranscriptGitDiffLastCommit:`Git diff last commit`,agentTranscriptShowChanges:`展开文件改动`,agentTranscriptShowMoreChanges:e=>`展开更多文件 · 还剩 ${e} 个`,agentTranscriptLoadingChanges:`正在加载准确改动…`,agentTranscriptChangesUnavailable:`部分准确文件详情无法加载。`,agentTranscriptTechnicalDetails:`技术详情`,agentTranscriptChangeKept:`已保留`,agentTranscriptChangeReverted:`已撤销`,agentTranscriptShowMoreFiles:e=>`显示另外 ${e} 个文件`,codexGoalTitle:`目标`,codexGoalEmpty:`没有活动目标`,codexGoalOpen:`打开目标控制`,codexGoalObjective:`目标内容`,codexGoalStatus:`状态`,codexGoalTokenBudget:`Token 预算`,codexGoalNoBudget:`不限制`,codexGoalUsage:(e,t)=>`${e.toLocaleString()} tokens · ${Math.round(t/60)} 分钟`,codexGoalStatusLabel:e=>({active:`进行中`,paused:`已暂停`,blocked:`已阻塞`,usageLimited:`用量受限`,budgetLimited:`预算受限`,complete:`已完成`})[e]??e,codexGoalEdit:`编辑`,codexGoalStart:`启动`,codexGoalStop:`停止`,codexGoalDelete:`删除`,codexGoalSave:`保存目标`,codexGoalClear:`清除`,codexGoalSaving:`保存中...`,searchProjectsOrAgents:`搜索项目或 Agent`,clearSearch:`清空搜索`,projectsAndAgents:`项目与 Agent`,noAgentsYet:`还没有 Agent。`,noMatchingProjectsOrAgents:`没有匹配的项目或 Agent。`,openNavigation:`打开导航`,closeNavigation:`关闭导航`,resizeNavigation:`调整导航宽度`,openOptions:`打开选项`,openSettings:`设置`,agentActions:`Agent 操作`,appearanceSystem:`外观:跟随系统`,appearanceLight:`外观:浅色`,appearanceDark:`外观:深色`,languageEnglish:`语言:English`,languageChinese:`语言:中文`,pinAgent:`置顶 Agent`,unpinAgent:`取消置顶`,pinProject:`置顶项目`,unpinProject:`取消置顶项目`,revealInFinder:`在访达中显示`,revealInFinderFailed:`无法在访达中显示项目`,createPermanentWorktree:`创建永久 worktree`,permanentWorktreeCreated:`已创建永久 worktree`,permanentWorktreeFailed:`创建永久 worktree 失败`,markAllAsRead:`全部标为已读`,renameAgent:`重命名 Agent`,renameProject:`重命名项目`,createBrowser:`创建浏览器`,createIsolatedDesktop:`创建隔离桌面`,archiveAgent:`归档`,reorderAgentFailed:`调整 Agent 顺序失败`,markAsRead:`标为已读`,markAsUnread:`标为未读`,copyWorkingDirectory:`复制工作目录`,copiedWorkingDirectory:`已复制工作目录`,copyFailed:`复制失败`,sharePage:`分享当前页面`,scanToOpenOnPhone:`手机扫码打开`,copyFullShareLink:`复制当前页面链接`,copiedShareLink:`已复制当前页面链接`,shareLinkFailed:`分享链接不可用`,sharedLocationUnavailable:e=>`无法定位分享路径:${e}`,shareLinkExpired:`已过期`,refreshShareLink:`刷新`,brandStoryOrigin:`Farming Code 从一个简单的问题出发:当多个 Coding Agent 同时工作,人不该在终端、编辑器和浏览器标签页之间反复切换。`,brandStoryPurpose:`它把对话、终端、项目文件与进展放在一个安静的工作空间里,让注意力留在真正重要的事情上。`,brandGithub:`GitHub`,renameInstance:`重命名实例`,instanceNameTitle:`重命名 Farming 实例`,instanceNameDescription:`这个名称会显示在此机器的侧边栏和浏览器页签中。`,instanceNamePlaceholder:`机器名称`,instanceNameSaveFailed:`无法保存实例名称。`,mobileShareTitle:`分享页面`,mobileForwardTitle:`转发当前页面`,mobileForwardHint:`复制链接,发送给其他人。`,mobileShareCopyAction:`复制链接`,mobileShareCopied:`已复制`,mobileInstallTitle:`添加到主屏幕`,mobileInstallChromeHint:`确认已使用系统浏览器或 Chrome 打开当前页面。`,mobileInstallShareStep:`点浏览器工具栏里的“分享”。`,mobileInstallMoreStep:`没看到时,点 •••,再点“分享”。`,mobileInstallAddStep:`选择“添加到主屏幕”。`,mobileInstallOpenStep:`以后从主屏幕的 Farming 图标进入。`,mobileShareInstalled:`Farming 已经作为主屏幕 App 打开。`,forkSameWorktree:`在同一 worktree 分叉`,forkNewWorktree:`分叉到新 worktree`,newWorktreeFork:`已分叉到新 worktree`,scheduledTask:`周期任务`,killAgent:`停止 Agent`,killAgentQuestion:`停止 Agent?`,openSession:`打开会话`,pinChat:`置顶会话`,unpinChat:`取消置顶会话`,archiveChat:`归档`,archiveChats:`归档会话`,archiveProject:`归档项目`,removeProject:`移除项目`,deleteWorktree:`彻底删除 worktree`,deleteWorktreeQuestion:`彻底删除 worktree?`,deleteWorktreeDescription:`这会彻底删除该 worktree 及其中的所有文件。`,forceDelete:`彻底删除`,cancel:`取消`,retry:`重试`,save:`保存`,stopAgentDescription:e=>`停止 ${e} 并关闭它的终端。`,acknowledgeUnprovenAcpExit:`确认已退出并移除`,acknowledgeUnprovenAcpExitDescription:e=>`Farming 无法证明 ${e} 的旧版 ACP 进程在升级时已经退出。请先在操作系统层确认进程已退出;继续操作只会移除 Farming 元数据,不会停止未知进程。`,permissionModeLabel:(e,t)=>({ask:`请求批准`,approve:`自动批准`,full:`完全访问`,custom:`自定义`,default:`默认`,auto:`自动`,acceptEdits:`接受编辑`,dontAsk:`不询问`,plan:`计划`,bypassPermissions:`绕过权限`})[e]??t,permissionModeDescription:(e,t)=>({ask:`新 Codex 会话以 workspace-write 沙箱启动,并对不可信操作询问`,approve:`新 Codex 会话以 workspace-write 沙箱启动,并在 Codex 请求时询问`,full:`新 Codex 会话绕过批准和沙箱;仅用于可信沙箱`,custom:`新 Codex 会话使用 config.toml 中定义的权限`,default:`新 Claude Code 会话使用默认设置`,auto:`新 Claude Code 会话以 auto 权限模式启动`,acceptEdits:`新 Claude Code 会话允许文件编辑,其他高风险操作仍会询问`,dontAsk:`新 Claude Code 会话在支持时尽量避免交互式批准`,plan:`新 Claude Code 会话以计划权限模式启动`,bypassPermissions:`新 Claude Code 会话绕过权限检查;仅用于可信沙箱`})[e]??t,acpModeLabel:(e,t)=>({"read-only":`只读`,agent:`工作区`,"agent-full-access":`完全访问`,auto:`自动`,default:`手动批准`,acceptEdits:`接受编辑`,plan:`计划`,dontAsk:`不询问`,bypassPermissions:`绕过权限`,build:`执行`})[e]??t,acpModeDescription:(e,t)=>({"read-only":`默认只读和分析;写文件或运行需要更高权限的命令时会请求批准,网络默认关闭`,agent:`可在当前工作区内读写文件并运行沙箱命令;使用网络或访问工作区外内容时会请求批准`,"agent-full-access":`可访问工作区外文件并使用网络,且不再请求批准;仅用于可信环境`,auto:`由模型分类器自动批准或拒绝权限请求`,default:`需要权限的操作会先请求批准`,acceptEdits:`自动批准文件编辑;其他需要权限的操作仍会询问`,plan:`只进行规划和检查,不修改文件`,dontAsk:`不弹出权限询问;未经预先允许的操作会直接拒绝`,bypassPermissions:`绕过权限检查;仅用于可信环境`,build:`按照该 Agent 已配置的权限执行工具`})[e]??t,reasoningOptionLabel:(e,t)=>({config:`使用配置`,low:`低`,medium:`中`,high:`高`,xhigh:`超高`,max:`最高`})[e]??t,serviceTierLabel:(e,t)=>({default:`标准`,priority:`快`,flex:`弹性`})[e]??t,serviceTierDescription:(e,t)=>({default:`默认速度`,priority:`1.5 倍速度,用量增加`})[e]??t,messageMode:`消息`,goalMode:`目标`,planMode:`计划`,askFollowUpChanges:`输入后续修改要求`,shellCommandPlaceholder:`输入 Shell 命令`,describeAgentGoal:`描述这个 Agent 的目标`,describePlanFirst:`描述需要先规划的事情`,openAgentTerminalFirst:`先打开一个 Agent 终端`,queuedMessages:e=>`${e} 条排队消息`,sendQueuedMessage:`当前轮后发送`,steerQueuedMessage:`Steer`,discardQueuedMessage:`丢弃排队消息`,editQueuedMessage:`移出队列并编辑`,messageAwaitingAcceptance:`等待 Agent 接收`,messageNotAccepted:`未被接收`,addContext:`添加上下文`,attachFile:`附加文件`,fileContext:`文件上下文`,acpSignOut:`退出登录`,acpSigningOut:`正在退出…`,acpSignOutDescription:`退出当前 ACP Agent 登录`,setObjective:`设置目标`,planFirst:`先做计划`,clearComposerMode:`清除输入模式`,agentPermissionMode:`Agent 权限模式`,permissionsPrompt:`启动权限 profile`,permissionProfileSavedForNextLaunch:`已保存给新 Agent。运行中的会话保留启动时的权限。`,permissionProfileRestarting:`正在切换 Agent 权限…`,runtimeModeRestarting:`正在重启 Agent…`,terminalProfileApplying:`正在应用 Codex Terminal 模型…`,terminalProfileApplied:`Codex Terminal 模型已更新。`,terminalProfileFailed:e=>`Codex Terminal 模型未修改:${e}`,configurationDeferred:`模型调整将在当前任务结束后生效。`,permissionDeferred:`权限调整将在当前任务结束后生效。`,sessionSettingsDeferred:`会话设置调整将在当前任务结束后生效。`,agentRestartTimedOut:`Agent 重启超时。原 Agent 仍然可用,请重新切换。`,permissionRestartHint:`运行中的 Agent 会重启以应用权限;如果还没有可 resume 的 Session ID,则启动一个新会话。`,modelAndReasoning:`模型与推理`,reasoning:`推理`,speed:`速度`,startDictation:`开始语音输入`,stopDictation:`停止语音输入`,speechUnsupported:`当前浏览器不支持语音识别`,mobileDictationHint:`请点 iOS 键盘上的麦克风进行听写。`,sendMessage:`发送消息`,interruptAgent:`中止 Agent`,startOrSelectAgent:`启动或选择一个 Agent`,startOrSelectAgentDescription:`项目在左侧。打开任意 Agent 终端时,不会关闭其他工作区。`,emptyWorkspaceWelcome:`欢迎使用 Farming`,emptyWorkspaceWelcomeDescription:`继续之前的工作,或开始一个新的 Agent。`,emptyWorkspaceContinue:`继续之前的工作`,emptyWorkspaceContinueDescription:`从历史记录恢复 Codex、Claude 等 Agent 会话。`,emptyWorkspaceNewAgentDescription:`在当前项目开始一个新的编码任务。`,plugins:`插件`,emptyWorkspacePluginsDescription:`管理 Farming 和 Agent 可以使用的能力。`,emptyWorkspaceSearchDescription:`查找项目、Agent 和历史。`,emptyWorkspaceShareDescription:`在手机或另一台设备打开。`,emptyWorkspaceFocus:`专注模式`,emptyWorkspaceFocusDescription:`隐藏干扰,专注当前任务。`,emptyWorkspaceCollapseDescription:`给工作区更多空间。`,historySummary:(e,t,n,r)=>`${n+r} 个 History Agents`,searchHistory:`搜索历史记录`,noHistoryYet:`还没有历史记录`,noHistoryDescription:`从主页面移出的 Agent 会出现在这里。`,historyAgents:`History Agents`,historyPagination:`历史记录分页`,historyPageStatus:(e,t,n,r)=>`第 ${e} / ${t}${r?`+`:``} 页 · 已载入 ${n} 条`,historyProviderSessionTotal:e=>`已发现 ${e} 个 Provider 会话`,previousPage:`上一页`,nextPage:`下一页`,agentSessions:`Agent 会话`,recentWorkspaces:`最近工作区`,agentsSessionsSummary:(e,t)=>`${e} 个 Agent · ${t} 个会话`,projectAgentsSummary:(e,t,n)=>[`${e} 个 Agent`,`${t} 个未读`,`${n} 个运行中`].join(` · `),restore:`恢复`,continueRun:`继续`,open:`打开`,archived:`已归档`,pinned:`已置顶`,unread:`未读`,showMore:`显示更多`,showLess:`收起`,showAgents:`展开 Agent`,hideAgents:`隐藏 Agent`,latest:`最新`,upgrade:`升级`,updating:`更新中`,retryUpdate:`重试`,checkForUpdates:`检查更新`,updateFailed:`更新失败`,upgradeToVersion:e=>e?`升级到 ${e}`:`升级 Farming Code`,sessionFallbackTitle:e=>`${e||`Agent`} 会话`,resumeSessionAria:e=>`恢复 ${e}`,resultsCount:e=>`${e} 个结果`,noMatchingAgents:`没有匹配的 Agent`,searchHint:`可按 Agent 标题、会话标题或项目搜索。`,searchEmptyTitle:`开始搜索`,searchEmptyDescription:`输入 Agent 标题、会话标题,或项目名称、路径。`,agents:`Agent`,files:`文件`,changes:`变更`,changedFiles:`变更文件`,trackedChanges:`已跟踪`,untrackedChanges:`未跟踪`,reviewChanges:`Review`,refreshChanges:`刷新变更`,worktrees:`工作树`,showWorktrees:`查看仓库工作树`,worktreeCurrent:`当前`,worktreeMain:`主工作树`,worktreeDetached:`游离`,worktreeLocked:`已锁定`,worktreePrunable:`可清理`,worktreeLoadFailed:`无法加载仓库工作树`,gitHistory:`历史`,gitHistoryEmpty:`还没有提交`,gitHistoryNotRepository:`当前项目不是 Git 仓库`,gitHistoryLoadMore:`加载更多`,gitHistoryView:`历史视图`,gitHistoryCurrentScope:`当前`,gitHistoryAllScope:`全部`,gitHistoryCurrentBranch:`当前分支`,gitHistoryAllBranches:`所有分支`,gitHistoryCommitMessage:`提交说明`,gitHistoryParent:`与父提交比较`,gitHistoryRootCommit:`根提交`,gitHistoryReviewCommit:`Review 提交`,gitHistoryCommitChanges:e=>`${e} 个文件有变化`,gitHistoryNoChanges:`没有文件变化`,gitHistoryChangesTruncated:`还有部分变更文件未展示`,searchOrPathLine:`搜索或路径:行号`,searchFilesOrJump:`搜索文件或跳转到路径行号`,openEditors:`打开的编辑器`,loading:`加载中...`,currentInfoLoadFailed:`当前信息加载失败。`,searching:`搜索中...`,noMatches:`无匹配`,searchIgnoredFolders:`同时在已忽略目录中搜索`,searchIncomplete:e=>`搜索提前停止(当前超时:${Math.round(e/1e3)} 秒)`,terminalSearchPlaceholder:`在终端中查找`,terminalSearchPrevious:`上一个匹配`,terminalSearchNext:`下一个匹配`,terminalSearchClose:`关闭终端搜索`,terminalSearchCaseSensitive:`区分大小写`,terminalSearchWholeWord:`全词匹配`,terminalSearchRegex:`使用正则表达式`,terminalSearchNoResults:`无结果`,terminalSearchResults:(e,t)=>`${e}/${t}`,terminalRecoveryRequesting:`正在获取终端状态…`,terminalRecoveryInstalling:`终端状态已获取,正在恢复画面…`,terminalRecoveryRetrying:e=>`终端状态获取失败,${e} 秒后重试…`,terminalRecoveryElapsed:e=>`已等待 ${e} 秒`,terminalRecoveryAttempt:e=>`第 ${e} 次尝试`,terminalSessionUnavailable:`终端会话不可用`,acpPermissionAllow:`允许`,acpPermissionTitle:`Agent 需要权限`,acpPermissionTool:`请求使用工具`,file:`文件`,folder:`文件夹`,go:`跳转`,moreMatchesOmitted:`更多匹配已省略`,stickyFolderPath:`固定文件夹路径`,containsUncommittedChanges:`包含未提交改动`,changedOnDisk:`磁盘上已变更`,unsavedChanges:`未保存改动`,gitStatus:e=>`Git 状态:${e}`,renameEntry:e=>`重命名 ${e}`,newFile:`新建文件`,newFolder:`新建文件夹`,refreshFiles:`刷新文件`,refreshingFiles:`正在刷新文件…`,filesRefreshed:`文件已刷新`,filesRefreshFailed:`文件刷新失败`,refresh:`刷新`,rename:`重命名`,copyRelativePath:`复制相对路径`,copyShareUrl:`拷贝分享 URL`,delete:`删除`,deleteFolderContents:e=>`删除文件夹及其所有内容:${e||``}`,deleteFile:e=>`删除文件:${e||``}`,saveFile:`保存文件`,savingFile:`正在保存文件`,reloadFile:`重新加载文件`,overwriteChangedFile:`覆盖已变更文件`,openFileDiff:`打开文件 Diff`,openFileDiffFor:e=>`打开 ${e} 的 Diff`,closeDiff:`关闭 Diff`,openFilePreview:`打开预览`,showFileSource:`显示源码`,enableWordWrap:`开启折行`,disableWordWrap:`关闭折行`,openMarkdownPreview:`打开 Markdown 预览`,showMarkdownSource:`显示 Markdown 源码`,openMarkdownSplitPreview:`打开 Markdown 侧边预览`,closeMarkdownSplitPreview:`关闭 Markdown 侧边预览`,markdownPreviewFor:e=>`${e} 的 Markdown 预览`,markdownFrontMatter:`Front matter`,markdownHeadingAnchor:`跳转到这个标题`,mermaidDiagram:`Mermaid 图表`,mermaidDiagramControls:`Mermaid 图表控制`,mermaidRendering:`正在渲染图表...`,mermaidRenderFailed:`无法渲染 Mermaid 图表`,mermaidZoomIn:`放大`,mermaidZoomOut:`缩小`,mermaidPanMode:`切换平移模式`,mermaidEnterFullscreen:`全屏查看图表`,mermaidExitFullscreen:`退出全屏查看`,mermaidResetView:`重置视图`,mermaidCopySource:`复制 Mermaid 源码`,mermaidCopiedSource:`已复制 Mermaid 源码`,fileDiff:`文件 Diff`,loadingDiff:`正在加载 Diff...`,noFileDiff:`文件没有变化。`,diffUnavailable:`这个文件没有可显示的 Diff 内容。`,binaryDiffUnavailable:`二进制文件不能显示 Diff。`,diffTooLarge:`Diff 过大,无法显示。`,deletedFileDiffOnly:`这个已删除文件只支持以 Diff 查看。`,showGitBlame:`显示 Git Blame`,hideGitBlame:`隐藏 Git Blame`,gitBlameAnnotations:`Git Blame 标注`,gitBlameDetails:`Git Blame 详情`,filePath:`文件路径`,editorFor:e=>`${e} 的编辑器`,revealInExplorer:e=>`在文件树中显示 ${e}`,previewFor:e=>`${e} 的预览`,author:`作者`,commit:`提交`,date:`日期`,line:`行`,unknown:`未知`,uncommitted:`未提交`,closeBlameDetails:`关闭 Blame 详情`,cut:`剪切`,copy:`复制`,paste:`粘贴`,selectAll:`全选`,annotateWithBlame:`用 Blame 标注`,hideBlame:`隐藏 Blame`,openLineChangesWithPreviousRevision:`打开与上一版的行变化`,openLineChangesWithWorkingFile:`打开与工作区文件的行变化`,lineChanges:`行变化`,loadingLineChanges:`正在加载行变化...`,noLineChanges:`这一行没有可显示的变化。`,closeLineChanges:`关闭行变化`,close:`关闭`,closeFile:e=>`关闭 ${e}`,closeOthers:`关闭其他`,closeToRight:`关闭右侧`,closeSaved:`关闭已保存`,closeAll:`全部关闭`,saveBeforeCloseTitle:e=>`是否保存对 ${e} 的更改?`,saveBeforeCloseDescription:`如果不保存,你的更改将丢失。`,dontSave:`不保存`,loadingBlame:`正在加载 Blame...`,notGitRepository:`不是 Git 仓库。`,noCommittedLines:`没有已提交行。`,cursorPosition:(e,t)=>`第 ${e} 行,第 ${t} 列`,startMainAgent:`启动 Main Agent`,startNewAgent:`启动新 Agent`,loadingAgents:`正在加载 Agent...`,agentListUnavailable:`Agent 列表不可用。`,noSupportedAgentsFound:`没有找到支持的 Agent。`,resumePreviousMainAgent:`恢复上一个 Main Agent`,codingAgents:`Coding Agent`,otherAgents:`Shell`,workspace:`工作区:`,workspacePathPlaceholder:`/工作区/路径`,chooseWorkspaceDirectory:`选择工作区目录`,workspaceDirectoryBrowserFailed:`无法读取这个目录。`,workspaceDirectoryBrowserHostHint:`浏览 Farming Host 上的目录。`,workspaceDirectoryBrowserGo:`转到目录`,workspaceDirectoryBrowserParent:`上级目录`,workspaceDirectoryBrowserEmpty:`没有子目录。`,workspaceDirectoryBrowserTruncated:`仅显示前 500 个目录,请输入更具体的路径继续浏览。`,workspaceDirectoryBrowserSelect:`选择此目录`,workspaceMissingTitle:`创建这个工作区?`,workspaceMissingDescription:`这个目录尚不存在。Farming 可以创建目录,并在其中启动 Agent。`,workspaceCreateAndStart:`创建并启动`,workspaceCreating:`正在创建…`,workspaceCreateFailedTitle:`无法创建工作区`,workspaceCreateForbiddenDescription:`Farming 没有权限创建这个目录。请选择其他位置,或调整父目录权限。`,workspaceCreateFailedDescription:`Farming 无法创建这个目录。请检查路径后重试。`,returnToWorkspace:`修改路径`,recentWorkspacesLower:`最近工作区`,start:`启动`,back:`返回`,backToAgent:`返回 Agent`,goBack:`后退`,goForward:`前进`,backendConnecting:`加载中…`,backendActionPending:`正在重新连接,这次操作尚未发送。`,backendConnectionLost:`Farming 后端暂时不可用,仍在重试…`,backendBusinessRecovering:`Farming 后端正在恢复业务状态…`,backendBusinessUnavailable:`Farming 后端业务状态没有响应,正在等待恢复…`};function Jz(e){return e===`zh`?qz:Kz}function Yz(){return window}function Xz(e,t={},n=Yz()){let r=t.delays??[],i=[],a=t.animationFrame!==!1,o;return t.runNow!==!1&&e(),a&&(o=n.requestAnimationFrame(e)),r.forEach(t=>{i.push(n.setTimeout(e,t))}),()=>{o!==void 0&&n.cancelAnimationFrame(o),i.forEach(e=>n.clearTimeout(e))}}function Zz(e,t,n=Yz()){let r=0,i,a,o=!1,s=()=>{i=void 0,!(o||r>=Math.max(1,t.maxAttempts))&&(r+=1,!(e()||r>=t.maxAttempts)&&(a=n.setTimeout(c,t.retryDelay??90)))},c=()=>{a=void 0,!o&&(t.animationFrame===!1?s():i=n.requestAnimationFrame(s))};return a=n.setTimeout(c,t.initialDelay??0),()=>{o=!0,i!==void 0&&n.cancelAnimationFrame(i),a!==void 0&&n.clearTimeout(a)}}var Qz={ask:`Ask for approval`,approve:`Approve for me`,full:`Full access`,custom:`Custom`},$z={ask:`Launch Codex with workspace-write sandbox and ask for untrusted actions`,approve:`Launch Codex with workspace-write sandbox and ask when Codex requests approval`,full:`Launch Codex with approvals and sandbox bypassed; use only in trusted sandboxes`,custom:`Launch Codex with permissions defined in config.toml`},eB=[`ask`,`approve`,`full`,`custom`].map(e=>({value:e,label:Qz[e],description:$z[e],color:e===`approve`?`blue`:e===`full`?`orange`:`muted`})),tB={default:`Default`,auto:`Auto`,acceptEdits:`Accept edits`,dontAsk:`Don't ask`,plan:`Plan`,bypassPermissions:`Bypass permissions`},nB={default:`Launch Claude Code with its default settings`,auto:`Launch Claude Code in auto permission mode`,acceptEdits:`Launch Claude Code allowing file edits while still asking for other risky actions`,dontAsk:`Launch Claude Code avoiding interactive approval prompts where supported`,plan:`Launch Claude Code in plan permission mode`,bypassPermissions:`Launch Claude Code with permission checks bypassed; use only in trusted sandboxes`},rB=[`default`,`auto`,`acceptEdits`,`dontAsk`,`plan`,`bypassPermissions`].map(e=>({value:e,label:tB[e],description:nB[e],color:e===`bypassPermissions`?`orange`:[`auto`,`acceptEdits`,`plan`].includes(e)?`blue`:`muted`})),iB=[{value:`low`,effort:`low`,label:`Low`},{value:`medium`,effort:`medium`,label:`Medium`},{value:`high`,effort:`high`,label:`High`},{value:`xhigh`,effort:`xhigh`,label:`Extra High`},{value:`max`,effort:`max`,label:`Max`}],aB=`Claude settings`,oB={value:`config`,effort:`config`,label:aB},sB=[{value:`config`,label:aB,displayName:aB,defaultEffort:`config`,reasoningLevels:[oB,...iB],source:`settings`}],cB={available:!1,effectiveModel:``,effectiveEffort:``,modelOptions:[],effortOptions:iB};function lB(e){return!!(e&&e in Qz)}function uB(e){return!!(e&&e in tB)}function dB(e,t,n){return e?lB(t)?t:`custom`:n}function fB(e,t,n){return e?uB(t)?t:`default`:n}function pB(e){if(typeof e!=`string`)return``;let t=e.trim();return!t||/[\s\x00-\x1f\x7f]/.test(t)||t.startsWith(`-`)?``:t}function mB(e){return e===`config`?e:pB(e)||`config`}function hB(e){return e&&iB.some(t=>t.value===e)?e:``}function gB(e){return e===`config`?e:hB(e)||`config`}function _B(e){let t=[];return Array.isArray(e)&&e.forEach(e=>{let n=hB(e?.value);n&&t.push({value:n,effort:n,label:e.label||CA(n),description:e.description})}),t.length>0?t:iB}function vB(e){let t=_B(e?.effortOptions),n=pB(e?.effectiveModel),r=hB(e?.effectiveEffort),i=[];return Array.isArray(e?.modelOptions)&&e.modelOptions.forEach(e=>{let n=pB(e?.value);n&&i.push({...e,value:n,label:e.label||n,displayName:e.displayName||n,defaultEffort:hB(e.defaultEffort)||r||`medium`,reasoningLevels:t,source:e.source||`settings`})}),n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,displayName:n,defaultEffort:r||`medium`,reasoningLevels:t,source:`settings`}),{available:e?.available===!0,effectiveModel:n,effectiveEffort:r,modelOptions:i,effortOptions:t}}function yB(e,t){let n=t.effortOptions?.length?t.effortOptions:iB,r=t.modelOptions?.length?t.modelOptions:sB.map(e=>({...e})),i=mB(e);return!i||i===`config`||r.some(e=>e.value===i)?r.map(e=>({...e,reasoningLevels:e.reasoningLevels?.length?e.reasoningLevels:n})):[...r.map(e=>({...e,reasoningLevels:e.reasoningLevels?.length?e.reasoningLevels:n})),{value:i,label:i,displayName:i,defaultEffort:t.effectiveEffort||`medium`,reasoningLevels:n,source:`settings`}]}function bB(e,t){return e===`config`?t.effectiveModel||t.modelOptions?.[0]?.value||`config`:mB(e)}function xB(e,t){return e===`config`?t.effectiveEffort||`config`:gB(e)}function SB(e,t){let n=t.effortOptions?.length?t.effortOptions:iB;return e===`config`?[oB,...n]:n.some(t=>t.value===e)?n:[...n,{value:e,effort:e,label:CA(e)}]}function CB(e,t,n,r){if(!e||r.some(t=>t.value===e))return r;let i=[{value:`default`,label:`Standard`,description:`Default speed`}];return n&&n!==`default`&&i.push({value:n,label:n===`priority`?`Fast`:n}),[...r,{value:e,label:TA(void 0,e),displayName:TA(void 0,e),defaultEffort:t,reasoningLevels:[{value:t,effort:t,label:CA(t)}],serviceTiers:i,source:`pending-catalog`}]}function wB(e){let t=e.agentLaunchProfiles?.codex??{},n=t.approvalMode??e.codexApprovalMode,r=wA(t.modelPreset??e.codexModelPreset),i=t.model||e.codexModel||r.model,a=t.reasoningEffort||e.codexReasoningEffort||r.effort,o=e.agentLaunchProfiles?.claude??{};return{codexApprovalMode:lB(n)?n:`approve`,codexModel:i,codexReasoningEffort:a,codexServiceTier:t.serviceTier||e.codexServiceTier||`default`,claudePermissionMode:uB(o.permissionMode)?o.permissionMode:`default`,claudeModel:mB(o.model),claudeEffort:gB(o.effort)}}function TB(e,t){return!e?.model||!e.reasoningEffort?t:{model:e.model,reasoningEffort:e.reasoningEffort,serviceTier:e.serviceTier||`default`}}function EB({agentKind:e,codexModel:t,codexReasoningEffort:n,codexServiceTier:r,codexModelOptions:i,codexApprovalMode:a,claudeModel:o,claudeEffort:s,claudeSettings:c,claudePermissionMode:l}){let u=bB(o,c),d=xB(s,c),f=e===`claude`?yB(o,c):e===`codex`?CB(t,n,r,i):i,p=e===`claude`?u:t,m=e===`claude`?d:n,h=e===`claude`?``:r,g=`${p}:${m}`,_=f.find(e=>e.value===p)??f[0],v=e===`claude`?SB(m,c):_?.reasoningLevels?.length?_.reasoningLevels:m?[{value:m,effort:m,label:CA(m)}]:[],y=e===`claude`?[]:_?.serviceTiers?.length?_.serviceTiers:[{value:`default`,label:`Standard`,description:`Default speed`}],b=v.find(e=>e.value===m)??v[0],x=y.find(e=>e.value===h)??y[0],S=e===`claude`?rB:eB,C=e===`claude`?l:a,w=S.find(e=>e.value===C)??S[0];return{agentModelOptions:f,agentModel:p,agentReasoningEffort:m,agentServiceTier:h,agentModelPreset:g,currentModelOption:_,currentReasoningOptions:v,currentServiceTierOptions:y,currentReasoningOption:b,currentServiceTierOption:x,currentModelLabel:TA(_,p),currentReasoningLabel:b?.label??CA(m),currentSpeedLabel:x?.label??``,permissionModeOptions:S,currentPermissionMode:C,currentPermissionOption:w,currentPermissionLabel:w?.label??C,currentPermissionColor:w?.color??`muted`}}function DB(e){return!e.isMain&&e.archived!==!0&&e.status!==`dead`&&e.status!==`stopped`}function OB(e){return!e.isMain&&e.archived===!0}function kB(e,t=[]){let n=new Map;return e.forEach(e=>{if(!DB(e))return;let t=e.providerSessionKey||iM(e.source);t&&n.set(e.id,t)}),n}function AB(e,t){return t.get(e.id)||`agent:${e.id}`}function jB(e){return e.providerSessionKey&&e.providerSessionTemporary!==!0?120:iM(e.source)?100:e.providerSessionKey?40:0}function MB(e){return e.status===`running`?30:e.status===`pending`?20:0}function NB(e,t){return jB(e)+(t.has(e.id)?50:0)+MB(e)}function PB(e,t){let n=new Map;return e.forEach(e=>{let r=AB(e,t),i=n.get(r);if(!i){n.set(r,e);return}let a=NB(e,t),o=NB(i,t),s=Number(e.startedAt)||0,c=Number(i.startedAt)||0;(a>o||a===o&&s>c)&&n.set(r,e)}),e.filter(e=>n.get(AB(e,t))===e)}function FB(e,t){return e.filter(e=>!t.has(OA(e)))}function IB(e,t,n){return e.filter(e=>{let r=OA(e);return(e.archived||!t.has(r))&&!n.has(r)})}function LB({allAgents:e,liveAgents:t,sessions:n,mainPageSessionKeys:r}){let i=t.filter(DB),a=kB(i,n),o=new Set(a.values()),s=PB(i,a),c=n.filter(e=>!e.archived&&r.has(OA(e))).sort(FA),l=FB(c,o),u=FB(n,o).sort(FA),d=IB(n,r,o).sort(FA);return{liveAgents:s,archivedAgents:e.filter(OB).sort((e,t)=>(t.archivedAt??0)-(e.archivedAt??0)),mainPageAgentSessions:c,sidebarAgentSessions:l,searchableAgentSessions:u,historyAgentSessions:d,claimedAgentSessionKeys:o,claimedAgentSessionKeyByAgentId:a}}var RB=`farming.workspaceDraftBackups.v1`,zB=32,BB=1024*1024,VB=2*1024*1024;function HB(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.key==`string`&&typeof t.agentId==`string`&&(t.workspaceRoot===void 0||typeof t.workspaceRoot==`string`)&&typeof t.filePath==`string`&&typeof t.baseSha1==`string`&&typeof t.draft==`string`&&typeof t.revision==`number`&&Number.isFinite(t.revision)&&typeof t.externalChanged==`boolean`&&typeof t.updatedAt==`number`&&Number.isFinite(t.updatedAt)}function UB(e,t=Date.now()){return{key:ve(e),agentId:e.agentId,...e.workspaceRoot===void 0?{}:{workspaceRoot:e.workspaceRoot},filePath:e.file.path,baseSha1:e.file.sha1,draft:e.draft,revision:e.revision??0,externalChanged:e.externalChanged,updatedAt:t}}function WB(e,t){if(t.key!==ve(e))return e;let n=t.draft!==e.file.content;return{...e,draft:n?t.draft:e.file.content,dirty:n,revision:Math.max(e.revision??0,t.revision),externalChanged:n&&(t.externalChanged||t.baseSha1!==e.file.sha1),saving:!1,saveRequestId:void 0,saveRevision:void 0,error:null,transient:!1}}function GB(e){let t=new Map;try{let n=JSON.parse(e.getItem(RB)||`null`);if(n?.version!==1||!Array.isArray(n.records))return t;n.records.forEach(e=>{HB(e)&&t.set(e.key,e)})}catch{try{e.removeItem(RB)}catch{}}return t}function KB(e,t){let n=Array.from(t.values()).filter(e=>e.draft.length<=BB).sort((e,t)=>t.updatedAt-e.updatedAt).slice(0,zB);for(;n.length>0;){let t=JSON.stringify({version:1,records:n});if(t.length>VB){n.pop();continue}try{e.setItem(RB,t);return}catch{n.pop()}}try{e.removeItem(RB)}catch{}}function qB(){return{activeFile:null,files:[],closedFileCache:new Map}}function JB(e){return{activeFile:e.activeFile,files:e.files,closedFileCache:e.closedFileCache}}function YB(){if(typeof window>`u`)return null;try{return window.localStorage}catch{return null}}function XB(e){return[...e.files,...e.closedFileCache.values()]}function ZB(){let[e,t]=(0,G.useState)(()=>qB()),n=(0,G.useRef)(e),r=(0,G.useRef)(null),i=(0,G.useRef)(null);if(r.current===null){let e=YB();r.current=e?GB(e):new Map}let a=(0,G.useCallback)(()=>{i.current!==null&&(clearTimeout(i.current),i.current=null);let e=YB();e&&KB(e,r.current??new Map)},[]),o=(0,G.useCallback)(()=>{i.current!==null&&clearTimeout(i.current),i.current=setTimeout(()=>{i.current=null;let e=YB();e&&KB(e,r.current??new Map)},250)},[]),s=(0,G.useCallback)((e,t)=>{let n=r.current;if(!n)return;let i=XB(t),a=new Set(i.map(ve));XB(e).forEach(e=>{let t=ve(e);a.has(t)||n.delete(t)}),i.forEach(e=>{let t=ve(e);e.dirty?n.set(t,UB(e)):n.delete(t)}),o()},[o]),c=(0,G.useCallback)(e=>{let r=n.current;return n.current=JB(e),s(r,n.current),t(n.current),n.current},[s]),l=(0,G.useCallback)((e,t,i)=>{let a=U(n.current,e,t,i),o=a.activeFile,s=o?r.current?.get(ve(o)):null;return o&&s&&(a=R(a,WB(o,s))),c(a)},[c]),u=(0,G.useCallback)((e,t,r)=>{let i=se(n.current,e,t,r);return i?c(i):null},[c]),d=(0,G.useCallback)(e=>{let t=re(n.current,e);return t.closedFiles.length>0&&c(t),t},[c]),f=(0,G.useCallback)(e=>{let t=V(n.current,{canReopen:e});return t?c(t):null},[c]),p=(0,G.useCallback)((e,t)=>{let r=ne(n.current.files,e);if(!r)return null;let i=t(r);return i!==r&&c(R(n.current,i)),i},[c]),m=(0,G.useCallback)((e,t)=>c(F(n.current,e,t)),[c]),h=(0,G.useCallback)(e=>{let t=n.current.activeFile;if(!t)return null;let r=ce(t,e);return c({...n.current,activeFile:r,files:oe(n.current.files,r)})},[c]),g=(0,G.useCallback)((e,t,r)=>{let i=te(n.current,e,t,r);return i!==n.current&&c(i),i},[c]),_=(0,G.useCallback)((e,t)=>{let r=ie(n.current,e,t);return r!==n.current&&c(r),r},[c]),v=(0,G.useCallback)((e,t)=>{let r=z(n.current,e,t);return t.length>0&&c(r),r},[c]),y=(0,G.useMemo)(()=>Array.from(e.closedFileCache.values()),[e.closedFileCache]);return(0,G.useEffect)(()=>{let e=()=>a();return window.addEventListener(`pagehide`,e),()=>{window.removeEventListener(`pagehide`,e),a()}},[a]),(0,G.useMemo)(()=>({activeFile:e.activeFile,files:e.files,closedFiles:y,openFromRead:l,select:u,close:d,reopenLastClosed:f,update:p,refreshFromReads:m,updateDraft:h,reorder:g,move:_,deleteEntries:v}),[y,d,v,_,l,m,g,f,u,e.activeFile,e.files,p,h])}var QB=286;function $B(e){return`key`in e}function eV(e){return!$B(e)||e.key===`ContextMenu`||e.shiftKey&&e.key===`F10`}function tV(e){return eV(e)?(e.preventDefault(),e.stopPropagation(),!0):!1}function nV(e,t){if($B(e)){let n=e.currentTarget.getBoundingClientRect();return eF(n.left+24,n.top+n.height,t)}return eF(e.clientX,e.clientY,t)}function rV({agents:e,projects:t,focusAgent:n,focusAgentSession:r,focusProject:i}){let[a,o]=(0,G.useState)(null),s=(0,G.useRef)(null),c=(0,G.useRef)(!1),l=(0,G.useRef)(0),u=(0,G.useCallback)(()=>o(null),[]),d=(0,G.useCallback)(()=>{let e=a;o(null),e?.kind===`agent`?n(e.agentId):e?.kind===`project`?i(e.projectId):e?.kind===`agent-session`?r(e.provider,e.sessionId):e?.kind===`options`&&e.returnFocusTarget&&window.requestAnimationFrame(()=>e.returnFocusTarget?.focus({preventScroll:!0}))},[a,n,r,i]),f=(0,G.useCallback)((t,n)=>{tV(t)&&o({kind:`agent`,agentId:n,...nV(t,rF(e.find(e=>e.id===n)))})},[e]),p=(0,G.useCallback)((e,n)=>{if(!tV(e))return;let r=e.currentTarget.getBoundingClientRect(),i=t.find(e=>e.id===n),a=i?.hasMain?4:pA(i)?8:7,s=$P(a,i?.hasMain?1:2)+a*8;o({kind:`project`,projectId:n,...de()?nF(r,s,void 0,QB):tF(r,s)})},[t]),m=(0,G.useCallback)((e,t,n)=>{tV(e)&&o({kind:`agent-session`,provider:t,sessionId:n,...nV(e,$P(3))})},[]),h=(0,G.useCallback)(e=>{tV(e);let t=e.currentTarget.getBoundingClientRect();o({kind:`options`,x:Math.max(8,t.right-164),y:Math.min(window.innerHeight-12,t.bottom+6),returnFocusTarget:e.currentTarget})},[]),g=(0,G.useCallback)((e,t)=>{if(!t)return!1;if(e.key===`Escape`)return e.preventDefault(),e.stopPropagation(),d(),!0;let n=Array.from(t.querySelectorAll(`button:not(:disabled)`));if(n.length===0)return!1;let r=n.findIndex(e=>e===document.activeElement),i=r===-1?Math.min(l.current,n.length-1):r,a=t=>(c.current=!0,e.preventDefault(),e.stopPropagation(),l.current=t,n[t]?.focus(),!0);if(e.key===`Tab`){e.preventDefault(),e.stopPropagation();let t=i+(e.shiftKey?-1:1);return t<0||t>=n.length?(d(),!0):a(t)}return e.key===`ArrowDown`||e.key===`ArrowUp`?a((i+(e.key===`ArrowDown`?1:-1)+n.length)%n.length):e.key===`Home`||e.key===`End`?a(e.key===`Home`?0:n.length-1):!1},[d]),_=(0,G.useCallback)(e=>{e.defaultPrevented||g(e.nativeEvent,e.currentTarget)},[g]);return(0,G.useLayoutEffect)(()=>{if(!a)return;let e=e=>{g(e,s.current)&&e.stopImmediatePropagation()},t=e=>{let t=e.target;t instanceof Element&&t.closest(`.code-context-menu`)||u()};return document.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t),()=>{document.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t)}},[u,a,g]),(0,G.useLayoutEffect)(()=>{if(a)return c.current=!1,l.current=0,Xz(()=>{if(c.current)return;let e=s.current,t=document.activeElement;if(!e||t instanceof HTMLButtonElement&&e.contains(t))return;let n=e.querySelector(`button:not(:disabled)`);n&&(l.current=0,n.focus())},{delays:[0,80,180,360]})},[a]),{contextMenu:a,contextMenuRef:s,agentMenu:a?.kind===`agent`?a:null,projectMenu:a?.kind===`project`?a:null,agentSessionMenu:a?.kind===`agent-session`?a:null,optionsMenu:a?.kind===`options`?a:null,closeContextMenu:u,closeContextMenuAndRestoreFocus:d,handleContextMenuKeyDown:_,handleContextMenuNavigation:g,openAgentMenu:f,openAgentSessionMenu:m,openOptionsContextMenu:h,openProjectMenu:p}}function iV(){let[e,t]=(0,G.useState)(()=>Nr()),n=(0,G.useRef)(e),r=(0,G.useRef)(!1),i=(0,G.useRef)(null),a=(0,G.useCallback)(e=>(n.current=e,t(e),e),[]),o=(0,G.useCallback)(e=>{r.current||a(Rr(n.current,e))},[a]),s=(0,G.useCallback)(e=>{o(Pr(e))},[o]),c=(0,G.useCallback)(e=>{o(Fr(e))},[o]),l=(0,G.useCallback)(e=>{r.current||(i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,o(Fr({...e,reason:`cursor`}))},650))},[o]),u=(0,G.useCallback)(e=>{let t=n.current,i=t.index+e,o=t.entries[i];return o?(r.current=!0,a({entries:t.entries,index:i}),o):null},[a]),d=(0,G.useCallback)(()=>{window.setTimeout(()=>{r.current=!1},120)},[]),f=(0,G.useCallback)(e=>{let t=n.current,r=t.entries.filter(e);if(r.length===t.entries.length)return;let i=t.entries[t.index],o=i?r.indexOf(i):-1;a({entries:r,index:o>=0?o:Math.min(t.index,r.length-1)})},[a]);return(0,G.useEffect)(()=>()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},[]),(0,G.useMemo)(()=>({canGoBack:e.index>0,canGoForward:e.index>=0&&e.index<e.entries.length-1,recordAgent:s,recordFile:c,recordFileCursor:l,beginNavigation:u,finishNavigation:d,pruneEntries:f}),[u,d,f,s,c,l,e.entries.length,e.index])}var aV=`farming.code.agentComposerCheckpoint.v1`,oV=1,sV=2e6,cV=720*60*60*1e3,lV=32,uV=64,dV=25e4,fV=100,pV=5e4,mV=25e4,hV=32,gV=32,_V=25e4,vV=8,yV=4096,bV=1e3,xV=200;function SV(e,t,n,r=Date.now()){return Math.max(r,(t.get(e)||0)+1,(n.get(e)||0)+1)}function CV(){return{states:{},updatedAtByKey:new Map}}function wV(){if(typeof window>`u`)return null;try{return window.localStorage}catch{return null}}function TV(e){return!!(e&&typeof e==`object`&&!Array.isArray(e))}function EV(e,t=0){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:t}function DV(e){return e===`goal`||e===`plan`?e:`default`}function OV(e,t){return typeof e==`string`&&e.length<=t?e:null}function kV(e){return typeof e==`string`&&/^[A-Za-z0-9._:-]{1,160}$/.test(e)?e:``}function AV(e,t){if(!TV(e)||e.kind!==`image`&&e.kind!==`audio`)return null;let n=OV(e.path,yV),r=OV(e.name,bV),i=OV(e.type,xV),a=typeof e.size==`number`&&Number.isFinite(e.size)&&e.size>=0?e.size:null;if(!n||r===null||i===null||a===null)return null;let o=t&&typeof e.id==`string`&&e.id.length<=500?e.id:void 0;return{...o?{id:o}:{},kind:e.kind,path:n,name:r,type:i,size:a}}function jV(e){return e.filter(e=>e.status===`ready`&&!!e.path).map(e=>AV(e,!0)).filter(e=>!!e).slice(0,vV)}function MV(e){return Array.isArray(e)?e.map(e=>AV(e,!0)).filter(e=>!!e).slice(0,vV).map((e,t)=>({id:e.id||`restored-checkpoint-${t}-${e.name}`,kind:e.kind,name:e.name,type:e.type,size:e.size,status:`ready`,path:e.path})):[]}function NV(e){if(!e)return;let t=e.map(e=>AV(e,!1)).filter(e=>!!e).slice(0,vV).map(({kind:e,path:t,name:n,type:r,size:i})=>({kind:e,path:t,name:n,type:r,size:i}));return t.length>0?t:void 0}function PV(e){let t=kV(e.id),n=OV(e.text,_V),r=e.editableText===void 0?void 0:OV(e.editableText,_V);if(!t||n===null||r===null)return null;let i=DV(e.composerMode),a=NV(e.attachments);return!n.trim()&&!a?null:{id:t,text:n,createdAt:EV(e.createdAt),...a?{attachments:a}:{},...r===void 0?{}:{editableText:r},...i===`default`?{}:{composerMode:i}}}function FV(e){if(!TV(e))return null;let t=kV(e.id),n=OV(e.text,_V),r=e.editableText===void 0?void 0:OV(e.editableText,_V);if(!t||n===null||r===null)return null;let i=NV(Array.isArray(e.attachments)?e.attachments:void 0);if(!n.trim()&&!i)return null;let a=DV(e.composerMode);return{id:t,text:n,createdAt:EV(e.createdAt),...i?{attachments:i}:{},...r===void 0?{}:{editableText:r},...a===`default`?{}:{composerMode:a}}}function IV(e){let t=[],n=0;for(let r=e.length-1;r>=0&&t.length<fV;--r){let i=OV(e[r],pV);i===null||n+i.length>mV||(t.push(i),n+=i.length)}return t.reverse()}function LV(e){return!!(e.draft||e.attachments.some(e=>e.status===`ready`&&e.path)||e.mode!==`default`||e.history.entries.length>0||e.pendingFollowUp?.messages.length||e.submissions?.length)}function RV(e,t){if(!LV(e))return null;let n=OV(e.draft,dV);if(n===null||(e.pendingFollowUp?.messages.length??0)>hV||(e.submissions?.length??0)>gV)return null;let r=(e.pendingFollowUp?.messages||[]).map(PV),i=(e.submissions||[]).map(e=>{let t=PV(e);return t?{...t,status:e.status,...e.historyRecorded===!0?{historyRecorded:!0}:{},...e.delivery===`prompt`||e.delivery===`steer`?{delivery:e.delivery}:{}}:null});if(r.some(e=>e===null)||i.some(e=>e===null))return null;let a=jV(e.attachments),o=IV(e.history.entries);return{updatedAt:t,...n?{draft:n}:{},...a.length>0?{attachments:a}:{},...e.mode===`default`?{}:{mode:e.mode},...o.length>0?{historyEntries:o}:{},...r.length>0?{pendingMessages:r}:{},...i.length>0?{submissions:i}:{}}}function zV(e){if(!TV(e))return null;let t=e.draft===void 0?``:OV(e.draft,dV);if(t===null)return null;let n=Array.isArray(e.pendingMessages)?e.pendingMessages:[],r=Array.isArray(e.submissions)?e.submissions:[];if(n.length>hV||r.length>gV)return null;let i=n.map(FV);if(i.some(e=>e===null))return null;let a=r.map(e=>{let t=FV(e);return!t||!TV(e)?null:{...t,status:`failed`,...e.historyRecorded===!0?{historyRecorded:!0}:{},...e.delivery===`prompt`||e.delivery===`steer`?{delivery:e.delivery}:{}}});if(a.some(e=>e===null))return null;let o=IV(Array.isArray(e.historyEntries)?e.historyEntries.filter(e=>typeof e==`string`):[]),s=VN();if(s.draft=t,s.attachments=MV(e.attachments),s.mode=DV(e.mode),s.history={entries:o,cursor:null},i.length>0){let e=i;s.pendingFollowUp={messages:e,createdAt:Math.min(...e.map(e=>e.createdAt))}}return a.length>0&&(s.submissions=a),LV(s)?s:null}function BV(e=wV(),t=Date.now()){if(!e)return CV();let n=VV(e,t);if(!n)return CV();let r={},i=new Map;for(let[e,t]of Object.entries(n.states)){if((n.tombstones?.[e]||0)>=t.updatedAt)continue;let a=zV(t);a&&(r[e]=a,i.set(e,t.updatedAt))}return{states:r,updatedAtByKey:i}}function VV(e,t){try{let n=e.getItem(aV);if(!n||n.length>sV)return null;let r=JSON.parse(n);if(!TV(r)||r.version!==oV||!TV(r.states))return null;let i=EV(r.savedAt);if(!i||t-i>cV)return null;let a={};Object.entries(r.states).slice(0,lV).forEach(([e,n])=>{if(!e||e.length>500||!TV(n))return;let r=EV(n.updatedAt,i);if(t-r>cV)return;let o=zV(n);if(!o)return;let s=RV(o,r);s&&(a[e]=s)});let o={};return TV(r.tombstones)&&Object.entries(r.tombstones).slice(0,uV).forEach(([e,n])=>{let r=EV(n);!e||e.length>500||!r||t-r>cV||(o[e]=r)}),{version:oV,savedAt:i,states:a,tombstones:o}}catch{return null}}function HV(e,t,n){return JSON.stringify({version:oV,savedAt:n,states:Object.fromEntries(e),...t.length>0?{tombstones:Object.fromEntries(t)}:{}})}function UV(e,t,n=new Map,r=wV(),i=Date.now()){if(!r)return!1;try{let a=VV(r,i),o=new Map(Object.entries(a?.states||{})),s=new Map(Object.entries(a?.tombstones||{}));for(let[n,r]of Object.entries(e)){if(!n||n.length>500)continue;let e=t.get(n)??i,a=o.get(n)?.updatedAt||0,c=s.get(n)||0;if(e<a||e<=c)continue;let l=RV(r,e);if(!l){if(LV(r))continue;o.delete(n),s.set(n,e);continue}o.set(n,l),s.delete(n)}for(let[e,t]of n){if(!e||e.length>500||!Number.isFinite(t)||t<0)continue;let n=o.get(e)?.updatedAt||0,r=s.get(e)||0;t<n||t<r||(o.delete(e),s.set(e,t))}let c=Array.from(o.entries()).filter(([,e])=>JSON.stringify(e).length<sV).sort(([e,t],[n,r])=>r.updatedAt-t.updatedAt||e.localeCompare(n)).slice(0,lV),l=Array.from(s.entries()).sort(([e,t],[n,r])=>r-t||e.localeCompare(n)).slice(0,uV),u=HV(c,l,i);for(;u.length>sV&&(c.length>0||l.length>0);)(c[c.length-1]?.[1].updatedAt??1/0)<=(l[l.length-1]?.[1]??1/0)?c.pop():l.pop(),u=HV(c,l,i);return u.length>sV?!1:(r.setItem(aV,u),!0)}catch{return!1}}function WV({agents:e,permissionSwitchingAgentId:t,permissionSwitchReplacement:n,onDiscardAttachment:r}){let i=(0,G.useRef)(null);i.current===null&&(i.current=BV());let[a,o]=(0,G.useState)(i.current.states),s=(0,G.useRef)(i.current.updatedAtByKey),c=(0,G.useRef)(new Map),l=(0,G.useRef)(a);l.current=a;let u=(0,G.useCallback)(e=>SV(e,s.current,c.current),[]),d=(0,G.useCallback)(()=>{UV(l.current,s.current,c.current)},[]);(0,G.useEffect)(()=>{let e=window.setTimeout(d,250);return()=>window.clearTimeout(e)},[a,d]),(0,G.useEffect)(()=>(window.addEventListener(`pagehide`,d),()=>window.removeEventListener(`pagehide`,d)),[d]),(0,G.useLayoutEffect)(()=>{let i=new Set(e.filter(e=>!e.archived&&e.status!==`dead`&&e.status!==`stopped`).flatMap(e=>[XN(e),kP(e)]).filter(Boolean));t&&(i.add(t),i.add(`acp:${t}`)),o(t=>{let a=t,o=!1,l=()=>(a===t&&(a={...t}),o=!0,a);if(n){let t=e.find(e=>e.id===n.replacementAgentId),r=Array.from(new Set([n.originalAgentId,n.transitionFromAgentId,...t?.restartedFromAgentIds??[],t?.restartedFromAgentId].filter(e=>!!e&&e!==n.replacementAgentId))),i=(e,t)=>{if(e===t)return;let n=a[e];if(!n)return;let r=l(),i=r[t];r[t]=i?JN(i,n):n,s.current.set(t,Math.max(u(t),(s.current.get(e)||0)+1)),c.current.delete(t),c.current.set(e,u(e)),s.current.delete(e),delete r[e]},o=t?XN(t):n.replacementAgentId,d=t?kP(t):`acp:${n.replacementAgentId}`;r.forEach(e=>{i(e,o),i(`acp:${e}`,d)})}return e.forEach(e=>{let t=XN(e);if(!t)return;ZN(e).forEach(e=>{if(e===t)return;let n=a[e];if(!n)return;let r=l();r[t]=r[t]?JN(r[t],n):n,s.current.set(t,Math.max(u(t),(s.current.get(e)||0)+1)),c.current.delete(t),c.current.set(e,u(e)),s.current.delete(e),delete r[e]});let n=kP(e);AP(e).forEach(e=>{if(e===n)return;let t=a[e];if(!t)return;let r=l();r[n]=r[n]?JN(r[n],t):t,s.current.set(n,Math.max(u(n),(s.current.get(e)||0)+1)),c.current.delete(n),c.current.set(e,u(e)),s.current.delete(e),delete r[e]})}),Object.entries(a).forEach(([e,t])=>{if(i.has(e)||t.draft||t.attachments.length>0||t.mode!==`default`||t.history.entries.length>0||(t.pendingFollowUp?.messages.length??0)>0||(t.submissions?.length??0)>0)return;let n=l();t.attachments.forEach(r),c.current.set(e,u(e)),s.current.delete(e),delete n[e]}),o?a:t})},[e,u,r,t,n]);let f=(0,G.useCallback)(t=>{if(!t)return``;for(let n of e){let e=jP(t),r=e?kP(n):XN(n);if(!r)continue;let i=e?AP(n):ZN(n);if(t===r||i.includes(t))return r}return t},[e]);return{composerByAgentKey:a,updateComposerStateForKey:(0,G.useCallback)((e,t)=>{o(n=>{let r=f(e);if(!r)return n;let i=n[r]??VN(),a=t(i);return a===i?n:(s.current.set(r,u(r)),c.current.delete(r),{...n,[r]:a})})},[u,f]),updateExistingComposerStateForKey:(0,G.useCallback)((e,t)=>{o(n=>{let r=f(e);if(!r)return n;let i=n[r];if(!i)return n;let a=t(i);return a===i?n:(s.current.set(r,u(r)),c.current.delete(r),{...n,[r]:a})})},[u,f])}}function GV(e,t=20){let n=[];for(let t of e){if(!t)continue;let e=n.indexOf(t);e>=0&&n.splice(e,1),n.push(t)}let r=Math.max(0,Math.floor(t));return r===0?[]:n.slice(-r)}function KV(e,t,n=20){let r=GV(t,n);return r.length===e.length&&r.every((t,n)=>t===e[n])?e:r}function qV(e,t,n=20){return KV(e,[...e,t],n)}function JV(){if(typeof window>`u`)return``;let e=window.location.hostname;return e?e===`localhost`||e===`127.0.0.1`||e===`::1`?`Local server`:`Remote server`:``}function YV(e){return e.replace(/^Language:\s*/i,``).replace(/^语言[::]\s*/,``)}function XV(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.trim(),i=String(n??``).trim();!r||!i||(t[r]=i.slice(0,80))}),t}function ZV(e){return e.replace(/^Appearance:\s*/i,``).replace(/^外观[::]\s*/,``)}function QV(e,t){return e.size===t.length?t.every(t=>e.has(t)):!1}function $V(e){return(e.ctrlKey||e.metaKey)&&e.shiftKey&&!e.altKey&&e.key.toLowerCase()===`t`}var eH=296,tH=220,nH=840,rH=360,iH=5*6e4,aH=52,oH=172,sH=900,cH=12,lH=4,uH=15e3,dH=60,fH=1e3,pH=150,mH=35e3,hH=15e3;async function gH(e,t){let n=new AbortController,r=window.setTimeout(()=>n.abort(),hH);try{return await fetch(e,{...t,signal:n.signal})}finally{window.clearTimeout(r)}}async function _H(e,t){let n=[],r=!0,i=0,a=Array.from({length:Math.min(lH,t.length)},async()=>{for(;i<t.length;){let a=t[i];i+=1;let o=new AbortController,s=window.setTimeout(()=>o.abort(),uH);try{n.push(await fe(e,a,{signal:o.signal}))}catch{r=!1}finally{window.clearTimeout(s)}}});return await Promise.all(a),{files:n,successful:r}}function vH(){return typeof window>`u`?!1:ae()&&xe()}function yH(e){let t=(e||``).trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e))?.split(`/`).pop()||``;return t===`qoder`||t===`qodercli`||t===`opencode`||t===`qwen`}function bH(e){return!!(e&&nA(e.command)===`codex`&&e.runtimeBinding.kind===`terminal`)}function xH(e){return e instanceof HTMLElement?e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable:!1}function SH(e){return rM(e)}function CH(e){return e.kind===`agent-session`?OA(e):vA(e)}function wH(){return de()}function TH(e){return!wH()&&e>0&&e<sH}function EH(){return wH()?!0:typeof window<`u`&&TH(window.innerWidth)}function DH(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}function OH(e){let t=(e||``).replace(/\/+$/,``);return t.split(`/`).filter(Boolean).pop()||t||`workspace`}function kH(){return typeof window>`u`?null:new URL(window.location.href).searchParams.get(`browser`)}function AH(){return typeof window>`u`?null:new URL(window.location.href).searchParams.get(`computer`)}function jH(e){if(e.lineNumber)return{lineNumber:e.lineNumber,column:e.column,endLineNumber:e.endLineNumber,endColumn:e.endColumn}}function MH(e){let t=new Map;for(let n of e)n.kind!==`path`||t.has(n.path)||t.set(n.path,n);return Array.from(t.values())}function NH(e){let t=new Map;for(let n of e)t.has(n.path)||t.set(n.path,n);return Array.from(t.values())}function PH(e,t){let n=new Set(e);return t.forEach(e=>{e.sessionKeys.forEach(t=>{e.operation===`add`?n.add(t):n.delete(t)})}),Array.from(n)}function FH({agents:e,taskHistory:t,mainPageSessionKeys:n,activeView:i,dialogOpen:a,usageSummary:o,contextWindowByAgentId:s={},activeTerminalId:c,permissionSwitchingAgentId:l,agentSwitchingKind:u,permissionSwitchReplacement:d,retainedAgentViewIds:f,terminalFocusRequest:p,remoteProjectWorkspaces:m,remotePinnedProjectWorkspaces:h,browserResourceState:b,computerResourceState:x,keyMap:D,keyboardShortcutsEnabled:j,uiPreferences:M,onOpenTerminal:N,onOpenTerminalWhenReady:P,onNewAgent:F,onStartAgent:ee,onRenameAgent:I,onUpdateAgentFlags:L,onOpenArchivedAgent:te,onForkAgent:R,onDeleteForkWorktreeProject:ne,onRestartMainAgent:re,onWorkspaceViewChange:z,onKill:ie,onInterruptAgent:oe,sendComposerInput:V,onSessionOutput:se,onBrowserResource:ce,onBrowserResourceDeletion:ue,onComputerResource:pe,onComputerResourceDeletion:me,onSyncUiPreferences:he,onUpdateUiPreferences:ye}){yr(`codeWorkspace`);let xe=jn(),{composerByAgentKey:U,updateComposerStateForKey:Ce,updateExistingComposerStateForKey:we}=WV({agents:e,permissionSwitchingAgentId:l,permissionSwitchReplacement:d,onDiscardAttachment:dP}),Te=(0,G.useRef)({}),Ee=(0,G.useRef)(new Set),De=(0,G.useRef)({}),[,Oe]=(0,G.useState)({}),[ke,Ae]=(0,G.useState)(kH),[je,Me]=(0,G.useState)(null),[Ne,Pe]=(0,G.useState)(AH),[Fe,Ie]=(0,G.useState)(null),[Le,Re]=(0,G.useState)(()=>new Set),[ze,Be]=(0,G.useState)(()=>AH()?`computer`:kH()?`browser`:`terminal`),Ve=jz({collection:b,onResource:ce,onDeletion:ue}),He=Lz({collection:x,onResource:pe,onDeletion:me}),Ue=Ve.create,We=Ve.start,[Ge]=(0,G.useState)(()=>T().surface),Ke=(0,G.useRef)(!1),qe=(0,G.useRef)(!Ge),Je=ZB(),{canGoBack:Ye,canGoForward:Xe,recordAgent:Ze,recordFile:Qe,recordFileCursor:$e,beginNavigation:et,finishNavigation:tt,pruneEntries:nt}=iV(),W=Je.activeFile,rt=Je.files,it=ke?Ve.resources.find(e=>e.id===ke)??null:null,at=Ne?He.resources.find(e=>e.id===Ne)??null:null,ot=(0,G.useMemo)(()=>new Set(He.resources.map(e=>e.ownerAgentId)),[He.resources]),st=(0,G.useCallback)(async(e,t)=>{let n=Array.from(new Set(Je.files.filter(e=>e.workspaceRoot===t).map(e=>e.file.path)));if(n.length===0)return!0;let r=await _H(e,n);return Je.refreshFromReads(t,r.files),r.successful},[Je]),[ct,lt]=(0,G.useState)(!1),[ut,dt]=(0,G.useState)(``),[ft,pt]=(0,G.useState)(0),[mt,ht]=(0,G.useState)([]),[gt,_t]=(0,G.useState)(!1),[vt,yt]=(0,G.useState)([]),[bt,St]=(0,G.useState)({}),[Ct,Tt]=(0,G.useState)([]),[Et,Ot]=(0,G.useState)(()=>new Set),[kt,At]=(0,G.useState)(`approve`),[jt,Mt]=(0,G.useState)(`gpt-5.5`),[Nt,Pt]=(0,G.useState)(`xhigh`),[Ft,It]=(0,G.useState)(`default`),[Lt,Rt]=(0,G.useState)([]),[zt,Bt]=(0,G.useState)(()=>new Set),[Vt,Ht]=(0,G.useState)(()=>new Map),Ut=(0,G.useRef)(new Set),[Wt,Gt]=(0,G.useState)(`default`),[Kt,qt]=(0,G.useState)(`config`),[Jt,Yt]=(0,G.useState)(`config`),[Xt,Zt]=(0,G.useState)(cB),[Qt,$t]=(0,G.useState)([]),[en,tn]=(0,G.useState)([]),[nn,rn]=(0,G.useState)(``),[an,on]=(0,G.useState)(!1),[cn,ln]=(0,G.useState)(null),[un,dn]=(0,G.useState)(!1),[fn,pn]=(0,G.useState)(``),[mn,hn]=(0,G.useState)([]),[gn,_n]=(0,G.useState)(!1),vn=(0,G.useRef)(!1),yn=(0,G.useRef)(null),bn=(0,G.useRef)(0),xn=(0,G.useRef)(null),Sn=(0,G.useRef)(dH),[Cn,wn]=(0,G.useState)(()=>Qj().pinnedOverrides),[Tn,En]=(0,G.useState)(()=>new Set),[Dn,On]=(0,G.useState)(!1),[kn,An]=(0,G.useState)(!1),[Mn,Fn]=(0,G.useState)(()=>new Set),[In,Rn]=(0,G.useState)(()=>new Set),[zn,Bn]=(0,G.useState)(eH),[Vn,Hn]=(0,G.useState)(()=>EH()),[Un,Gn]=(0,G.useState)(null),[Kn,qn]=(0,G.useState)(()=>typeof window>`u`?null:y(window.location.search)),[Jn,Yn]=(0,G.useState)(0),[Xn,Zn]=(0,G.useState)(void 0),[Qn,$n]=(0,G.useState)(!1),[er,tr]=(0,G.useState)(`Farming`),[nr,rr]=(0,G.useState)(``),[ir,ar]=(0,G.useState)(null),[or,sr]=(0,G.useState)(null),[cr,lr]=(0,G.useState)(null),[ur,dr]=(0,G.useState)(null),[fr,pr]=(0,G.useState)(null),[gr,_r]=(0,G.useState)(null),vr=ir?ir.kind===`agent`?`agent:${ir.agentId}`:`project:${ir.projectId}`:``,[br,xr]=(0,G.useState)(Date.now()),Sr=(0,G.useRef)(null),Cr=(0,G.useRef)(null),Er=(0,G.useRef)([]),Dr=(0,G.useRef)(null),Or=(0,G.useRef)(null),kr=(0,G.useRef)(null),Nr=(0,G.useRef)(null),Pr=(0,G.useRef)(null),Fr=(0,G.useRef)(null),Ir=(0,G.useRef)(null),Lr=(0,G.useRef)(null),Rr=(0,G.useRef)(null),Br=(0,G.useRef)(null),Vr=(0,G.useRef)(null),Hr=(0,G.useRef)(null),Ur=(0,G.useRef)(null),Wr=(0,G.useRef)(0),Gr=(0,G.useRef)(``),Kr=(0,G.useRef)(0),qr=(0,G.useRef)(!1),Jr=(0,G.useRef)(()=>{}),Yr=(0,G.useRef)(c),q=(0,G.useRef)(0),Xr=(0,G.useRef)(0),Zr=(0,G.useRef)(0),Qr=(0,G.useRef)(0),$r=(0,G.useRef)(new mz),ei=(0,G.useRef)(0),ti=(0,G.useRef)(null),ni=(0,G.useRef)(null),ri=(0,G.useRef)(null),ii=(0,G.useRef)(0),ai=(0,G.useRef)(new Map),oi=(0,G.useRef)(eM(n)),si=(0,G.useRef)(0),ci=(0,G.useRef)([]),li=(0,G.useRef)(Promise.resolve()),ui=(0,G.useRef)(new Set),di=(0,G.useRef)(!1),fi=(0,G.useRef)(Vn),pi=(0,G.useRef)(wH()),mi=(0,G.useCallback)(()=>{fi.current=!1,Hn(!0)},[]),hi=(0,G.useCallback)(()=>{Hn(e=>(e||(fi.current=!0),!0))},[]),gi=(0,G.useCallback)(()=>{fi.current=!1,Hn(!1)},[]),_i=(0,G.useCallback)(()=>{fi.current=!1,Hn(e=>!e)},[]),vi=(0,G.useCallback)(e=>{Gn(t=>({kind:e,nonce:(t?.nonce||0)+1}))},[]);Yr.current=c;let J=(0,G.useMemo)(()=>Jz(M.language),[M.language]);(0,G.useEffect)(()=>{$j({promotedKeys:[],pinnedOverrides:Cn,archivedOverrides:{}})},[Cn]),(0,G.useEffect)(()=>{En(t=>{let n=!1,r=new Set(t);return t.forEach(t=>{let i=e.find(e=>e.id===t);(!i||i.archived===!0)&&(r.delete(t),n=!0)}),n?r:t})},[e]);let yi=(0,G.useMemo)(()=>e.filter(e=>!e.isMain&&!Tn.has(e.id)),[e,Tn]),bi=(0,G.useMemo)(()=>e.find(e=>e.isMain)??null,[e]),Y=(0,G.useMemo)(()=>yi.filter(DB),[yi]),xi=(0,G.useMemo)(()=>{let e=new Set(Y.map(e=>e.id));return bi&&e.add(bi.id),e},[Y,bi]),Si=(0,G.useMemo)(()=>{let e=new Set([Dt]);return mt.forEach(t=>e.add(Ar(t))),Y.forEach(t=>e.add(Ar(bA(t)))),xi.forEach(t=>e.add(t)),e},[Y,mt,xi]);(0,G.useEffect)(()=>{nt(e=>e.kind===`agent`?xi.has(e.agentId):Si.has(e.agentId))},[nt,xi,Si]);let Ci=(0,G.useCallback)((e,t)=>{let n=bi?[...Y,bi]:Y;if(wt(e)){let e=n.find(e=>e.id===t);return{filesId:Dt,workspaceRoot:`/`,sourceAgentId:e?.id,sourceAgent:e}}let r=jr(e);if(r){let e=Y.find(e=>e.id===t&&Ar(bA(e))===Ar(r));return{filesId:Ar(r),workspaceRoot:r,sourceAgentId:e?.id,sourceAgent:e}}let i=n.find(t=>t.id===e);if(i&&!i.isMain){let e=bA(i),n=Y.find(n=>n.id===t&&Ar(bA(n))===Ar(e))??i;return{filesId:Ar(e),workspaceRoot:e,sourceAgentId:n.id,sourceAgent:n}}return{filesId:e,workspaceRoot:i?bA(i):void 0,sourceAgentId:i?.id,sourceAgent:i}},[Y,bi]);(0,G.useEffect)(()=>{W?.sourceAgentId&&(Ci(W.agentId,W.sourceAgentId).sourceAgentId||Je.update({agentId:W.agentId,filePath:W.file.path,workspaceRoot:W.workspaceRoot},e=>({...e,sourceAgentId:void 0})))},[W,Ci,Je]);let wi=(0,G.useMemo)(()=>tM(en,Cn,{}),[Cn,en]),Ti=(0,G.useMemo)(()=>LB({allAgents:yi,liveAgents:Y,sessions:wi,mainPageSessionKeys:Et}),[Y,wi,Et,yi]),Ei=Ti.mainPageAgentSessions,Di=Ti.sidebarAgentSessions,Oi=Ti.searchableAgentSessions,ki=Ti.historyAgentSessions,Ai=Ti.liveAgents,ji=Ti.archivedAgents,Mi=t,Ni=ki,Pi=(0,G.useMemo)(()=>new Set(mn.map(OA)),[mn]),Fi=(0,G.useMemo)(()=>new Set(Array.from(Ti.claimedAgentSessionKeyByAgentId.entries()).filter(([,e])=>Pi.has(e)).map(([e])=>e)),[Ti.claimedAgentSessionKeyByAgentId,Pi]),Ii=(0,G.useMemo)(()=>{let e=new Map(Oi.map(e=>[OA(e),e]));return mn.forEach(t=>e.set(OA(t),t)),FB(Array.from(e.values()),Ti.claimedAgentSessionKeys)},[Ti.claimedAgentSessionKeys,mn,Oi]),Li=(0,G.useMemo)(()=>CF(Ai,Di,bt,rt,yi,mt,vt),[rt,vt,bt,mt,Di,yi,Ai]),Ri=(0,G.useMemo)(()=>aM(Li,In,!1),[In,Li]),zi=(0,G.useMemo)(()=>{let e=new Set(ot);return He.capability?.enabled===!0&&He.capability.available===!0&&Ri.forEach(t=>t.agents.forEach(t=>e.add(t.id))),e},[He.capability?.available,He.capability?.enabled,ot,Ri]),Bi=(0,G.useMemo)(()=>CF(Ai,Ii,bt,rt,yi,mt,vt),[rt,vt,bt,mt,Ii,yi,Ai]),Vi=ut.trim().toLowerCase(),Hi=Vi.length>0,Ui=(0,G.useMemo)(()=>wF((i===`search`||ct)&&Hi?Bi:Ri,Vi,In,Pi,Fi),[i,In,Hi,Vi,Ri,Bi,Fi,Pi,ct]),Wi=Ri.some(e=>!!e.workspace),Gi=(0,G.useMemo)(()=>Hi?Ui:[],[Ui,Hi]),Ki=(0,G.useMemo)(()=>TF(Ui,Mn,Vi),[Mn,Ui,Vi]),qi=(0,G.useMemo)(()=>Hi?Ki:[],[Hi,Ki]),Ji=(0,G.useMemo)(()=>{let e=new Map;return j&&D.forEach((t,n)=>{e.set(t,n)}),e},[D,j]),Yi=(0,G.useMemo)(()=>c?qV(f,c):f,[c,f]),Xi=(0,G.useMemo)(()=>Yi.map(e=>Y.find(t=>t.id===e)??(bi?.id===e?bi:null)).filter(e=>!!e),[Y,bi,Yi]),Zi=sn((0,G.useMemo)(()=>Xi.find(e=>e.id===c)??Xi[0]??null,[c,Xi])),Qi=(0,G.useMemo)(()=>Xi.map(e=>e.id===Zi?.id?Zi:e),[Zi,Xi]),X=sn((0,G.useMemo)(()=>Y.find(e=>e.id===c)??(bi?.id===c?bi:null),[Y,c,bi])),$i=X?.providerHomeId||`default`,ea=mr(X)?X.runtimeBinding:null,ta=!!(X&&X.id===l),na=!!(X&&zt.has(X.id)),ra=X?s[X.id]??null:null,ia=ea?kP(X):X?XN(X):``,aa=(0,G.useMemo)(()=>lA(X),[X]),oa=ia?U[ia]??(X?(ea?AP(X):ZN(X)).map(e=>U[e]).find(Boolean):void 0)??BN:BN,sa=oa.draft,ca=oa.attachments,la=oa.mode,{plusMenuOpen:ua,approvalMenuOpen:da,modelMenuOpen:fa,modelPickerPane:pa}=oa.ui,ma=!!(ea&&X&&De.current[X.id]!==void 0),ha=(0,G.useMemo)(()=>ma||tA(X),[ma,X]),ga=(0,G.useMemo)(()=>$k(X),[X]),_a=aa.kind,va=(0,G.useMemo)(()=>dB(!!(X&&_a===`codex`),X?.launchPermissionMode,kt),[X,kt,_a]),ya=(0,G.useMemo)(()=>fB(!!(X&&_a===`claude`),X?.launchPermissionMode,Wt),[X,Wt,_a]),ba=X&&Vt.get(X.id)||null,xa=(0,G.useMemo)(()=>TB(ba||X?.codexTerminalProfile,{model:jt,reasoningEffort:Nt,serviceTier:Ft}),[ba?.model,ba?.reasoningEffort,ba?.serviceTier,X?.codexTerminalProfile?.model,X?.codexTerminalProfile?.reasoningEffort,X?.codexTerminalProfile?.serviceTier,jt,Nt,Ft]),Sa=xa.model,Ca=xa.reasoningEffort,wa=xa.serviceTier,Ta=(0,G.useMemo)(()=>ha||!!X&&X?.status===`running`&&_a===`shell`&&ga.terminalBusy,[X,ga.terminalBusy,ha,_a]),Ea=(0,G.useMemo)(()=>cA([...sA(_a),...Qt]),[_a,Qt]),Da=oa.pendingFollowUp,Oa=oa.submissions;(0,G.useEffect)(()=>{!c||ze!==`terminal`||i!==`projects`||Ze(c)},[c,i,ze,Ze]),(0,G.useEffect)(()=>{!W||ze!==`editor`||i!==`projects`||Qe({agentId:W.agentId,filePath:W.file.path,view:W.diffRequestId?`diff`:`editor`,lineNumber:W.cursor?.lineNumber,column:W.cursor?.column,endColumn:W.cursor?.endColumn,sourceAgentId:W.sourceAgentId})},[i,ze,W?.agentId,W?.cursor?.column,W?.cursor?.endColumn,W?.cursor?.lineNumber,W?.cursor?.requestId,W?.diffRequestId,W?.file.path,W?.sourceAgentId,Qe]),(0,G.useEffect)(()=>{Ve.collectionLoading||!ke||it||(Ae(null),Be(`terminal`))},[ke,it,Ve.collectionLoading]),(0,G.useEffect)(()=>{He.collectionLoading||!Ne||at||(Pe(null),Be(`terminal`))},[Ne,at,He.collectionLoading]),(0,G.useEffect)(()=>{let e=new URL(window.location.href);if(ze===`browser`&&ke){e.searchParams.set(`browser`,ke),e.searchParams.delete(`computer`);for(let t of[`agent`,`file`,`folder`,`path`,`view`,`line`,`column`,`endColumn`])e.searchParams.delete(t)}else if(ze===`computer`&&Ne){e.searchParams.set(`computer`,Ne),e.searchParams.delete(`browser`);for(let t of[`agent`,`file`,`folder`,`path`,`view`,`line`,`column`,`endColumn`])e.searchParams.delete(t)}else e.searchParams.delete(`browser`),e.searchParams.delete(`computer`);e.href!==window.location.href&&window.history.replaceState(window.history.state,``,e)},[ke,Ne,ze]);let ka=fP(ca).length>0,Aa=ca.some(e=>e.status===`uploading`),ja=na?`disabled`:X&&!Aa&&(sa.trim()||ka)?`send`:Ta?`interrupt`:`disabled`,Ma=CP(X)?ja:`disabled`,Na=(0,G.useCallback)(e=>{ia&&Ce(ia,e)},[ia,Ce]),Pa=(0,G.useCallback)(()=>{Na(KN)},[Na]),Fa=(0,G.useCallback)(e=>{let t=Array.from(Sr.current?.querySelectorAll(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"]`)??[]).find(t=>t.dataset.agentId===e);return t?(t.focus({preventScroll:!0}),document.activeElement===t):!1},[]),Ia=(0,G.useCallback)(e=>{Xz(()=>{Fa(e)},{delays:[80,180]})},[Fa]),La=(0,G.useCallback)((e,t)=>{window.requestAnimationFrame(()=>{Array.from(Sr.current?.querySelectorAll(`[data-testid="code-active-session-row"]`)??[]).find(n=>n.dataset.provider===e&&n.dataset.sessionId===t)?.focus({preventScroll:!0})})},[]),Ra=(0,G.useCallback)(e=>{window.requestAnimationFrame(()=>{Array.from(Sr.current?.querySelectorAll(`[data-testid="code-project-title"]`)??[]).find(t=>t.dataset.projectId===e)?.focus()})},[]),{contextMenu:za,agentMenu:Ba,projectMenu:Va,agentSessionMenu:Ha,optionsMenu:Z,contextMenuRef:Ua,closeContextMenu:Wa,closeContextMenuAndRestoreFocus:Ga,handleContextMenuKeyDown:Ka,handleContextMenuNavigation:qa,openAgentMenu:Ja,openAgentSessionMenu:Ya,openOptionsContextMenu:Xa,openProjectMenu:Za}=rV({agents:Y,projects:Li,focusAgent:Ia,focusAgentSession:La,focusProject:Ra}),Qa=(0,G.useMemo)(()=>Y.find(e=>e.id===Ba?.agentId)??null,[Y,Ba?.agentId]),$a=(0,G.useMemo)(()=>Li.find(e=>e.id===Va?.projectId)??null,[Li,Va?.projectId]),eo=(0,G.useMemo)(()=>Ui.flatMap(e=>e.agentSessions).find(e=>e.provider===Ha?.provider&&OA(e)===Ha?.sessionId)??null,[Ha?.provider,Ha?.sessionId,Ui]),to=ct?qi[ft]??null:null,no=to?.kind===`agent`?to.id:null,ro=to?.kind===`agent-session`?OA(to):null,io=X?bA(X):void 0,ao=(0,G.useMemo)(()=>{if(W&&!wt(W.agentId))return W.agentId;if(X&&!X.isMain)return Ar(bA(X));if(io)return Ar(io);let e=Y.find(e=>!e.isMain);return e?Ar(bA(e)):null},[X,Y,io,W]),oo=(0,G.useCallback)(e=>{if(!(e instanceof Element))return null;let t=e.closest(`[data-testid="code-agent-row"][data-agent-id], [data-testid="code-project-agent-compact"][data-agent-id], [data-testid="code-pinned-agent-compact"][data-agent-id], [data-testid="code-agent-rail-item"][data-agent-id]`)?.dataset.agentId;if(t){let e=Y.find(e=>e.id===t&&!e.isMain);if(e)return Ar(bA(e))}let n=e.closest(`[data-testid="code-project-group"]`)?.querySelector(`[data-testid="code-project-title"][data-project-id]`)?.dataset.projectId;return!n||n===`__farming_main_agent__`?null:Ar(n)},[Y]),so=X?.isMain?Xn??Ri[0]?.workspace:io??Xn??Ri[0]?.workspace,co=ze===`editor`&&!!W,lo=(0,G.useMemo)(()=>{if(co&&W){let e=W.workspaceRoot??Y.find(e=>e.id===W.agentId)?.projectWorkspace??Y.find(e=>e.id===W.agentId)?.cwd??``;return{kind:`file`,agentId:W.agentId,filePath:W.file.path,...e?{absolutePath:k(e,W.file.path)}:{},...e?{projectLabel:v(e)}:{},view:W.diffRequestId?`diff`:`editor`,lineNumber:W.cursor?.lineNumber,column:W.cursor?.column,endColumn:W.cursor?.endColumn}}return c&&xi.has(c)?{kind:`agent`,agentId:c,readingSurface:hr(Y.find(e=>e.id===c))?`chat`:`terminal`}:null},[c,W?.agentId,W?.cursor?.column,W?.cursor?.endColumn,W?.cursor?.lineNumber,W?.diffRequestId,W?.file.path,W?.workspaceRoot,co,Y,xi]),{agentModelOptions:uo,agentModel:fo,agentReasoningEffort:po,agentServiceTier:mo,agentModelPreset:ho,currentReasoningOptions:go,currentServiceTierOptions:_o,currentPermissionMode:vo,currentPermissionLabel:yo,currentPermissionColor:bo,currentModelLabel:xo,currentReasoningLabel:So,currentSpeedLabel:Co,permissionModeOptions:wo}=(0,G.useMemo)(()=>EB({agentKind:_a,codexModel:Sa,codexReasoningEffort:Ca,codexServiceTier:wa,codexModelOptions:Lt,codexApprovalMode:va,claudeModel:Kt,claudeEffort:Jt,claudeSettings:Xt,claudePermissionMode:ya}),[Jt,Kt,Xt,ya,va,Sa,Lt,Ca,wa,_a]),To=JV(),Eo=ct||i===`search`?J.search:i===`history`?J.history:i===`plugins`?J.plugins:ze===`computer`&&at?at.name:ze===`browser`&&it?it.name:co&&W?yA(W.file.path):X?A(X):J.codex,Do=X?.isMain?`farming`:OH(X?bA(X):void 0),Oo=X?`${Do} · ${To}`:To,ko=co&&W?W.sourceAgentId:null,Ao=!!ko,jo=(0,G.useCallback)(()=>{let e=Cr.current;if(!e)return;e.style.height=`auto`;let t=Math.min(e.scrollHeight,132);e.style.height=`${t}px`,e.style.overflowY=e.scrollHeight>132?`auto`:`hidden`},[]),Mo=(0,G.useCallback)(()=>{let e=!1;Xz(()=>{if(document.querySelector(`.code-composer-menu`))return;let t=Cr.current??document.querySelector(`[data-testid="code-composer-input"]`);e&&document.activeElement instanceof HTMLElement&&document.activeElement!==document.body&&document.activeElement!==t||(t?.focus({preventScroll:!0}),document.activeElement===t&&(e=!0))},{delays:[60]})},[]),No=(0,G.useCallback)(e=>{let t=wB(e);At(t.codexApprovalMode),Mt(t.codexModel),Pt(t.codexReasoningEffort),It(t.codexServiceTier),Gt(t.claudePermissionMode),qt(t.claudeModel),Yt(t.claudeEffort)},[]),Po=(0,G.useCallback)(()=>{let e=!1,t=ii.current;return fetch(r(`/api/settings`)).then(e=>e.json()).then(n=>{if(e)return;let r=n.settings??{};t===ii.current&&Ot(new Set(eM(r.mainPageSessionKeys??[]))),St(XV(r.projectNames)),typeof r.instanceName==`string`&&r.instanceName.trim()&&tr(r.instanceName),No(r)}).catch(()=>{}),()=>{e=!0}},[No]),Fo=(0,G.useCallback)(async e=>{try{let t=await fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({instanceName:e})});if(!t.ok)return!1;let n=(await t.json()).settings?.instanceName;return n?(tr(n),!0):!1}catch{return!1}},[]),Io=(0,G.useCallback)(()=>{let e=Date.now()-Wr.current;if(Gr.current===$i&&Wr.current>0&&e<=iH)return()=>{};let t=!1,n=Kr.current+1;Kr.current=n,Rt([]);let i=new URLSearchParams({homeId:$i});return fetch(r(`/api/codex/models?${i.toString()}`)).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error||`Failed to load Codex model catalog (${e.status})`);return t}).then(e=>{if(t||Kr.current!==n)return;let r=DA(e);if(r.length===0)throw Error(`Codex model catalog did not contain any visible models`);Wr.current=Date.now(),Gr.current=$i,qr.current=!1,Rt(r)}).catch(e=>{if(!(t||Kr.current!==n)){if(Wr.current=0,Gr.current=``,!g().connected){qr.current=!0;return}qr.current=!1,dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to load Codex model catalog`})}}),()=>{t=!0}},[$i]),Lo=(0,G.useCallback)(()=>{let e=!1,t=new URLSearchParams({homeId:$i});return fetch(r(`/api/claude/settings?${t.toString()}`)).then(e=>e.json()).then(t=>{e||Zt(vB(t.settings))}).catch(()=>{e||Zt(cB)}),()=>{e=!0}},[$i]),Ro=(0,G.useCallback)(async(e,t)=>{let n=new URLSearchParams({q:e,limit:String(fH)}),i=await fetch(r(`/api/agent-sessions/search?${n.toString()}`),{signal:t,cache:`no-store`});if(!i.ok)throw Error(`Failed to search Agent sessions: ${i.status}`);let a=await i.json();return Array.isArray(a.sessions)?a.sessions:[]},[]),zo=(0,G.useCallback)(async(e,t)=>IB(tM(await Ro(e,t),Cn,{}),Et,Ti.claimedAgentSessionKeys),[Ti.claimedAgentSessionKeys,Cn,Ro,Et]),Bo=(0,G.useCallback)(async(e={})=>{let t=new URLSearchParams({limit:String(e.limit||dH)});e.cursor&&t.set(`cursor`,e.cursor),e.fresh&&t.set(`fresh`,`1`);let n=await fetch(r(`/api/agent-sessions?${t.toString()}`),{cache:e.fresh?`no-store`:`default`,signal:e.signal});if(!n.ok)throw Error(`Failed to load Agent sessions: ${n.status}`);let i=await n.json(),a=Array.isArray(i.sessions)?i.sessions:[];return{sessions:a,nextCursor:typeof i.nextCursor==`string`?i.nextCursor:``,hasMore:i.hasMore===!0,total:Number.isFinite(i.total)?Math.max(a.length,Math.floor(i.total)):a.length}},[]),Vo=(0,G.useCallback)((e=!1)=>{let t=!1;if(!e&&wr())return()=>{};xn.current?.abort();let n=new AbortController;xn.current=n;let r=bn.current+1;return bn.current=r,e&&(dn(!0),pn(``),tn([]),rn(``),on(!1),ln(null)),Bo(e?{fresh:!0,signal:n.signal}:{signal:n.signal}).then(e=>{t||r!==bn.current||(tn(e.sessions),rn(e.nextCursor),on(e.hasMore),ln(e.total),Sn.current=Math.max(dH,e.sessions.length))}).catch(()=>{n.signal.aborted||!t&&r===bn.current&&(tn([]),rn(``),on(!1),ln(null),e&&pn(J.currentInfoLoadFailed))}).finally(()=>{xn.current===n&&(xn.current=null),!t&&e&&r===bn.current&&dn(!1)}),()=>{t=!0,n.abort(),xn.current===n&&(xn.current=null),e&&r===bn.current&&dn(!1)}},[J.currentInfoLoadFailed,Bo]);(0,G.useEffect)(()=>Tr(()=>{xn.current?.abort()}),[]);let Ho=(0,G.useCallback)(()=>{bn.current+=1,dn(!0),pn(``),tn([]),rn(``),on(!1),ln(null)},[]),Uo=(0,G.useCallback)(()=>{if(yn.current)return yn.current;let e=Bo({limit:Sn.current,fresh:!0}).then(e=>{tn(e.sessions),rn(e.nextCursor),on(e.hasMore),ln(e.total)}).catch(()=>{tn([]),ln(null)}).finally(()=>{yn.current===e&&(yn.current=null)});return yn.current=e,e},[Bo]),Wo=(0,G.useCallback)(async()=>{if(!an||!nn||vn.current)return!1;vn.current=!0;try{let e=await Bo({cursor:nn});return tn(t=>{let n=new Set(t.map(OA)),r=[...t];return e.sessions.forEach(e=>{let t=OA(e);n.has(t)||(n.add(t),r.push(e))}),Sn.current=Math.max(dH,r.length),r}),rn(e.nextCursor),on(e.hasMore),ln(e.total),e.sessions.length>0}catch{return!1}finally{vn.current=!1}},[nn,an,Bo]);(0,G.useEffect)(()=>{if(!((i===`search`||ct)&&Hi)){hn([]),_n(!1);return}let e=new AbortController;hn([]),_n(!0);let t=window.setTimeout(()=>{Ro(Vi,e.signal).then(hn).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||hn([])}).finally(()=>{e.signal.aborted||_n(!1)})},pH);return()=>{window.clearTimeout(t),e.abort()}},[i,Ro,Hi,Vi,ct]);let Go=(0,G.useCallback)((e,t,n)=>{if(e!==`codex`&&e!==`claude`)return $t([]),()=>{};let i=!1,a=new URLSearchParams({provider:e,homeId:t});return n&&a.set(`workspace`,n),fetch(r(`/api/slash-commands?${a.toString()}`)).then(e=>e.json()).then(e=>{i||$t(Array.isArray(e.commands)?e.commands:[])}).catch(()=>{i||$t([])}),()=>{i=!0}},[]),Ko=(0,G.useCallback)(()=>{ia&&(Na(e=>({...e,ui:{...e.ui,plusMenuOpen:!1}})),Dr.current?.click())},[ia,Na]),qo=(0,G.useCallback)((e,t)=>{let n=lP(t),r=iP(t),i=rP(t,r?`pasted image`:`pasted audio`),a=r?uP(t):void 0,o={id:n,kind:r?`image`:`audio`,name:i,type:t.type||(r?`image/png`:`audio/wav`),size:t.size,status:`uploading`,previewUrl:a};Ce(e,e=>({...e,attachments:[...e.attachments,o]})),_P(t).then(t=>{we(e,e=>({...e,attachments:e.attachments.map(e=>e.id===n?{...e,name:i,type:t.type||e.type,size:t.size||e.size,status:`ready`,path:t.path,messageBlock:r?sP({...t,name:i}):cP({...t,name:i}),error:void 0}:e)}))}).catch(()=>{we(e,e=>({...e,attachments:e.attachments.map(e=>e.id===n?{...e,status:`error`,messageBlock:yP(t),error:`Upload failed`}:e)}))})},[Ce,we]),Jo=(0,G.useCallback)(async e=>{if(!ia||e.length===0)return;e.filter(e=>iP(e)||aP(e)).forEach(e=>qo(ia,e));let t=e.filter(e=>!iP(e)&&!aP(e));if(t.length===0){Mo();return}let n=[];for(let e of t)try{n.push(await vP(e))}catch{n.push(yP(e))}Ce(ia,e=>({...e,draft:nP(e.draft,n.join(`
696
+
697
+ `))})),Mo()},[ia,qo,Mo,Ce]),Yo=(0,G.useCallback)(e=>{Na(t=>{let n=t.attachments.find(t=>t.id===e);return n&&dP(n),{...t,attachments:t.attachments.filter(t=>t.id!==e)}}),Mo()},[Mo,Na]),Xo=(0,G.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value=``,Jo(t)},[Jo]),Zo=(0,G.useCallback)(e=>{let t=bP(e.clipboardData);t.length!==0&&(e.preventDefault(),Jo(t))},[Jo]);(0,G.useEffect)(()=>{let e=Dr.current;if(e)return e.addEventListener(`cancel`,Mo),()=>e.removeEventListener(`cancel`,Mo)},[Mo]),(0,G.useEffect)(()=>{Er.current=Object.values(U).flatMap(e=>e.attachments)},[U]),(0,G.useEffect)(()=>()=>{Er.current.forEach(dP)},[]);let Qo=(0,G.useCallback)(e=>{Na(t=>({...t,mode:e,ui:{...t.ui,plusMenuOpen:!1}})),Mo()},[Mo,Na]),$o=(0,G.useCallback)((e,t=!1,n=null)=>{let r=Y.find(t=>t.id===e);if(!r)return;let i=Number.isFinite(r.attentionSeq)?Math.max(0,Number(r.attentionSeq)):0,a=Number.isFinite(r.readAttentionSeq)?Math.max(0,Number(r.readAttentionSeq)):0;!t&&i<=a&&!r.unread||L(e,{unread:!1,...n?{readOutputEpoch:n.runtimeEpoch,readOutputSeq:n.outputSeq}:{}})},[Y,L]),es=(0,G.useCallback)((e,t=null)=>{$o(e,!0,t)},[$o]),ts=(0,G.useCallback)((e,t)=>{Oe(n=>{let r=n[e];return r?.following===t.following&&r?.hasUnreadOutput===t.hasUnreadOutput?n:{...n,[e]:t}})},[]),ns=(0,G.useCallback)(e=>{Na(t=>({...t,draft:e,history:{...t.history,cursor:null}}))},[Na]),rs=(0,G.useCallback)((e,t)=>{if(!X||!ia||!LN(t))return null;let n=RN(oa.history,e,t.value);return n.changed?(Ce(ia,e=>({...e,draft:n.value,history:n.history})),n.value):null},[X,ia,oa.history,Ce]),is=(0,G.useCallback)(async(e,t,n,i)=>{if(!bH(e))return!0;if(Ut.current.has(e.id))return!1;Ut.current.add(e.id);let a={model:t,reasoningEffort:n,serviceTier:i,source:`pending-terminal-command`};Ht(t=>{let n=new Map(t);return n.set(e.id,a),n}),Bt(t=>new Set(t).add(e.id)),dr({id:Date.now(),kind:`success`,message:J.terminalProfileApplying});let o=new AbortController,s=window.setTimeout(()=>{o.abort(new DOMException(`Timed out applying the Codex Terminal profile`,`TimeoutError`))},mH);try{let a=await fetch(r(`/api/agents/${encodeURIComponent(e.id)}/codex-terminal-profile`),{method:`POST`,headers:{"Content-Type":`application/json`},signal:o.signal,body:JSON.stringify({model:t,effort:n,serviceTier:i})}),s=await a.json().catch(()=>({}));if(!a.ok)throw Error(s.error||`Failed to update Codex Terminal (${a.status})`);return dr({id:Date.now(),kind:`success`,message:J.terminalProfileApplied}),!0}catch(t){Ht(t=>{let n=new Map(t);return n.delete(e.id),n});let n=t instanceof Error?t.message:`Failed to update Codex Terminal`;return dr({id:Date.now(),kind:`error`,message:J.terminalProfileFailed(n)}),!1}finally{window.clearTimeout(s),Ut.current.delete(e.id),Bt(t=>{let n=new Set(t);return n.delete(e.id),n})}},[J.terminalProfileApplied,J.terminalProfileApplying,J.terminalProfileFailed]);(0,G.useEffect)(()=>{let e=X?.codexTerminalProfile;!X||!e||Ht(t=>{let n=t.get(X.id);if(!n||e.model!==n.model||e.reasoningEffort!==n.reasoningEffort||e.serviceTier!==n.serviceTier)return t;let r=new Map(t);return r.delete(X.id),r})},[X?.id,X?.codexTerminalProfile?.model,X?.codexTerminalProfile?.reasoningEffort,X?.codexTerminalProfile?.serviceTier]);let as=(0,G.useCallback)((e,t,n=[],r,i)=>hr(e)?V(t,e.id,n,{awaitResult:!0,requestId:r,delivery:i}):nA(e.command)===`shell`||lA(e).kind===`shell`||yH(e.command)?yT(e.id,`${t}\r`):yT(e.id,Gz(t)),[V]),os=(0,G.useCallback)(e=>{let t=e??Cr.current?.value??sa;if(!X||!ia||ca.some(e=>e.status===`uploading`))return;let n=hr(X)?hP(ca):[],r=n.length>0?mP(t,ca):pP(t,ca);if(!r&&n.length===0)return;let i=SP(la,r,X),a=!0;eA(X)&&X.runtimeBinding.kind===`terminal`?Ce(ia,e=>{let n=e.pendingFollowUp;return{...e,pendingFollowUp:{messages:[...n?.messages||[],HN(i,[],t,la)],createdAt:n?.createdAt||Date.now()}}}):a=as(X,i,n);let o=()=>{Ce(ia,e=>e.draft===t?(e.attachments.forEach(dP),{...e,draft:``,attachments:[],mode:`default`,history:IN(e.history,t)}):e),Mo()};if(typeof a==`boolean`){a&&o();return}a.then(e=>{e&&o()})},[X,ia,ca,la,sa,Mo,as,Ce]),ss=(0,G.useCallback)((e,t)=>{let n=e??Cr.current?.value??sa,r=!!(ea&&X&&De.current[X.id]!==void 0),i=TP({agent:X,composerKey:ia,draft:n,attachments:ca,composerMode:la,turnActive:ha||r,followUpBehavior:wP(M.composerFollowUpBehavior,t?.oppositeFollowUpBehavior===!0,X?.providerCapabilities.supportsSteer===!0),sendMessage:(e,t,n,r,i)=>as(e,t,n,r,i),updateComposerState:Ce}),a=(e,t)=>{e&&(X&&ea&&!ha&&!r&&(De.current[X.id]=Number(ea.sessionRevision)||0),t&&Mo())};typeof i==`boolean`?a(i,!0):i.then(e=>a(e,!1))},[ea,X,ha,ia,ca,la,sa,Mo,as,M.composerFollowUpBehavior,Ce]),cs=(0,G.useCallback)(e=>{if(!X||!ia)return;let t=U[ia]?.submissions?.find(t=>t.id===e&&t.status===`failed`);if(!t)return;let n=`${ia}:${e}`;if(Ee.current.has(n))return;Ee.current.add(n),Ce(ia,t=>({...t,submissions:t.submissions?.map(t=>t.id===e?{...t,status:`submitting`}:t)}));let r=r=>{Ce(ia,n=>({...n,...r&&t.historyRecorded!==!0?{history:IN(n.history,t.text)}:{},submissions:r?GN(n.submissions,e):n.submissions?.map(t=>t.id===e?{...t,status:`failed`}:t)})),Ee.current.delete(n)},i;try{i=as(X,t.text,t.attachments,t.id,t.delivery||`prompt`)}catch{r(!1);return}typeof i==`boolean`?r(i):i.then(r,()=>r(!1))},[X,ia,U,as,Ce]),ls=(0,G.useCallback)(e=>{if(!X||!ia||!ha||X.providerCapabilities.supportsSteer!==!0)return;let t=U[ia]?.pendingFollowUp?.messages.find(t=>t.id===e);if(!t)return;let n=`${ia}:${e}`;if(Ee.current.has(n))return;Ee.current.add(n),Ce(ia,n=>n.pendingFollowUp?.messages.some(t=>t.id===e)?{...n,pendingFollowUp:WN(n.pendingFollowUp,e),submissions:[...n.submissions||[],{...t,status:`submitting`,historyRecorded:!0,delivery:`steer`}]}:n);let r=t=>{Ce(ia,n=>({...n,submissions:t?GN(n.submissions,e):n.submissions?.map(t=>t.id===e?{...t,status:`failed`}:t)})),Ee.current.delete(n)},i;try{i=as(X,t.text,t.attachments,t.id,`steer`)}catch{r(!1);return}typeof i==`boolean`?r(i):i.then(r,()=>r(!1))},[X,ha,ia,U,as,Ce]),us=(0,G.useCallback)(e=>{ia&&(Ce(ia,t=>({...t,submissions:GN(t.submissions,e)})),Mo())},[ia,Mo,Ce]),ds=(0,G.useCallback)(()=>{!X||!Ta||(oe(X.id),Mo())},[X,Ta,Mo,oe]),fs=(0,G.useCallback)((e,t,n)=>{X&&EP(X.id,e,t,n===!0)},[X]),ps=(0,G.useCallback)((e,t,n)=>{X&&DP(X.id,e,t,n)},[X]),ms=(0,G.useCallback)(e=>{if(!X||!ia)return;let t=U[ia]?.pendingFollowUp;if(!t||t.messages.length===0)return;let n=t.messages.find(t=>t.id===e);if(!n)return;let r=()=>Ce(ia,t=>t.pendingFollowUp?{...t,pendingFollowUp:WN(t.pendingFollowUp,e)}:t);if(Te.current[ia])return;Te.current[ia]=n.id;let i=e=>{Te.current[ia]===n.id&&delete Te.current[ia],e&&(r(),Mo())},a;try{a=as(X,n.text,n.attachments,n.id,`prompt`)}catch{i(!1);return}if(typeof a==`boolean`){i(a);return}a.then(i,()=>i(!1))},[X,ia,U,Mo,as,Ce]),hs=(0,G.useCallback)(e=>{!X||!ia||(Ce(ia,t=>t.pendingFollowUp?{...t,pendingFollowUp:WN(t.pendingFollowUp,e)}:t),Mo())},[X,ia,Mo,Ce]),gs=(0,G.useCallback)(e=>!X||!ia||!U[ia]?.pendingFollowUp?.messages.find(t=>t.id===e)||Te.current[ia]===e||Ee.current.has(`${ia}:${e}`)?!1:(Ce(ia,t=>UN(t,e)),Mo(),!0),[X,ia,U,Mo,Ce]);(0,G.useEffect)(()=>{let e=new Set(Y.map(e=>e.id));Object.keys(De.current).forEach(t=>{e.has(t)||delete De.current[t]}),Y.forEach(e=>{let t=De.current[e.id];if(t===void 0)return;let n=mr(e)?e.runtimeBinding:null,r=tA(e)||(Number(n?.sessionRevision)||0)>t;(!n||r||n.state===`error`||e.archived||e.status===`dead`||e.status===`stopped`)&&delete De.current[e.id]})},[Y]),(0,G.useEffect)(()=>{let e=[];Y.forEach(t=>{let n=mr(t)?t.runtimeBinding:null,r=n?kP(t):XN(t);if(!r)return;let i=U[r]?.pendingFollowUp;if(!i||i.messages.length===0){delete Te.current[r];return}if(t.archived||t.status===`dead`||t.status===`stopped`)return;if(n){let e=De.current[t.id],r=Number(n.sessionRevision)||0;if(e!==void 0&&r<=e)return}if((n?tA(t):eA(t))||Te.current[r])return;let a=i.messages[0];a&&e.push({agent:t,composerKey:r,message:a})}),e.length!==0&&e.forEach(({agent:e,composerKey:t,message:n})=>{let r=()=>we(t,e=>e.pendingFollowUp?{...e,pendingFollowUp:WN(e.pendingFollowUp,n.id)}:e);Te.current[t]=n.id;let i=i=>{if(Te.current[t]===n.id&&delete Te.current[t],i){r();return}mr(e)&&we(t,e=>e.pendingFollowUp?.messages.some(e=>e.id===n.id)?{...e,pendingFollowUp:WN(e.pendingFollowUp,n.id),submissions:[...e.submissions||[],{...n,status:`failed`,historyRecorded:!0,delivery:`prompt`}]}:e)},a;try{a=as(e,n.text,n.attachments,n.id,`prompt`)}catch{i(!1);return}if(typeof a==`boolean`){i(a);return}a.then(i,()=>i(!1))})},[Y,U,as,we]);let _s=(0,G.useCallback)(()=>{Wa(),Pa(),gi(),z(`search`),lt(!0),requestAnimationFrame(()=>Pr.current?.focus())},[Pa,gi,z]),vs=(0,G.useCallback)(()=>{wH()&&hi()},[hi]),ys=(0,G.useCallback)(()=>{gi()},[gi]),bs=(0,G.useCallback)((e,t,n)=>{F(e,t,n),vs()},[vs,F]),xs=(0,G.useCallback)((e,t,n)=>{if(dt(``),lt(!1),pt(0),Be(`terminal`),z(`projects`),nA(e)!==`codex`){ee(e,t,n);return}let r=n?.codexApprovalMode||kt;ee(e,t,{...n,codexApprovalMode:r,...r===`full`?{dangerouslySkipPermissions:!0}:{}})},[kt,ee,z]);(0,G.useEffect)(()=>{let e=!1;return fetch(r(`/api/executables`)).then(e=>{if(!e.ok)throw Error(`Failed to load executables: ${e.status}`);return e.json()}).then(t=>{e||Tt(Wn(Array.isArray(t)?t:t.agents??[]))}).catch(()=>{e||Tt([])}),()=>{e=!0}},[]);let Ss=(0,G.useCallback)(e=>{Ot(t=>{let n=eM(e(t));return QV(t,n)?t:new Set(n)})},[]),Cs=(0,G.useCallback)(e=>{e&&(oi.current=eM(e));let t=PH(oi.current,ci.current);Ot(e=>QV(e,t)?e:new Set(t))},[]),ws=(0,G.useCallback)((e,t)=>{let n=eM(t);if(n.length===0)return;let i=++ii.current;ci.current.push({version:i,operation:e,sessionKeys:n}),li.current=li.current.catch(()=>{}).then(async()=>{let t=si.current,a=null;try{let t=await gH(r(`/api/main-page-agent-sessions`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({operation:e,sessionKeys:n})}),i=await t.json().catch(()=>null);if(!t.ok||!Array.isArray(i?.mainPageSessionKeys))throw Error(`Failed to update main-page sessions: ${t.status}`);a=i.mainPageSessionKeys}catch{try{let e=await gH(r(`/api/settings`));if(!e.ok)throw Error(`Failed to reconcile main-page sessions: ${e.status}`);let t=await e.json();if(!Array.isArray(t.settings?.mainPageSessionKeys))throw Error(`Failed to reconcile main-page sessions: invalid response`);a=t.settings.mainPageSessionKeys}catch{}}finally{ci.current=ci.current.filter(e=>e.version!==i),Cs(a!==null&&si.current===t&&a?a:void 0)}})},[Cs]);(0,G.useEffect)(()=>{si.current+=1,Cs(eM(n))},[Cs,n]);let Ts=(0,G.useCallback)((e,t,n=``)=>{let r=OA({provider:e,id:t,providerHomeId:n});Ss(e=>[...e,r]),ws(`add`,[r])},[ws,Ss]),Es=(0,G.useCallback)(e=>{Ss(t=>Array.from(t).filter(t=>t!==e)),ws(`remove`,[e])},[ws,Ss]),Ds=(0,G.useCallback)(e=>{let t=new Set(e);Ss(e=>Array.from(e).filter(e=>!t.has(e))),ws(`remove`,e)},[ws,Ss]),Os=(0,G.useCallback)(e=>{Promise.resolve(e).then(e=>{if(!e||typeof e!=`object`)return;let t=Array.isArray(e.removedMainPageSessionKeys)?e.removedMainPageSessionKeys:[];t.length>0&&Ds(t)}).catch(()=>{})},[Ds]),ks=(0,G.useCallback)(e=>{En(t=>t.has(e)?t:new Set(t).add(e));let t=()=>{ni.current===e&&(ni.current=null),En(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},n=L(e,{archived:!0});return Os(n),Promise.resolve(n).then(e=>{e===!0||typeof e==`object`&&e&&(e.archived===!0||e.uncertain===!0)||t()}).catch(t),n},[L,Os]);(0,G.useEffect)(()=>{let e=!1;Y.forEach(t=>{if(t.providerSessionTemporary===!0)return;let n=t.providerSessionKey||iM(t.source);if(!n)return;let r=`${t.id}:${n}`;ui.current.has(r)||(ui.current.add(r),Ss(e=>[...e,n]),e=!0)}),e&&Uo()},[Y,Uo,Ss]),(0,G.useEffect)(()=>{if(!xe||!Y.some(e=>e.providerSessionTemporary===!0))return;Uo();let e=window.setInterval(Uo,5e3);return()=>window.clearInterval(e)},[Y,xe,Uo]);let As=(0,G.useCallback)(()=>{let e=Yr.current,t=Array.from(Sr.current?.querySelectorAll(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"], [data-testid="code-active-session-row"]`)??[]),n=(e?t.find(t=>t.dataset.agentId===e):null)??t[0]??Hr.current;return n?(n.focus({preventScroll:!0}),document.activeElement===n):!1},[]),js=(0,G.useCallback)(e=>{let t=Array.from(Sr.current?.querySelectorAll(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"], [data-testid="code-active-session-row"]`)??[]).find(t=>e.kind===`agent`?t.dataset.agentId===e.id:t.dataset.provider===e.provider&&t.dataset.sessionId===CH(e));return t?(t.focus({preventScroll:!0}),document.activeElement===t):!1},[]),Ms=(0,G.useCallback)(()=>{if(a||document.querySelector(`.code-context-menu`)||document.querySelector(`.code-composer.menu-open, .code-composer-menu`))return!0;let e=document.activeElement;return e instanceof HTMLElement?e.closest(`.code-context-menu`)?!0:e===document.body||e===document.documentElement||Hr.current?.contains(e)||e.closest(`.code-sidebar`)?!1:!!e.closest(`.code-composer`):!1},[a]),Ns=(0,G.useCallback)(()=>{dt(``),lt(!1),pt(0)},[]),Ps=(0,G.useCallback)(()=>{Ns(),z(`projects`),ti.current=`active-force`},[Ns,z]);(0,G.useEffect)(()=>{if(!ct||i!==`search`)return;let e=e=>{let t=e.target;t instanceof Element&&(t.closest(`.code-search-panel, [data-testid="code-nav-search"], [data-testid="code-mobile-menu"]`)||Ps())};return document.addEventListener(`pointerdown`,e,!0),()=>{document.removeEventListener(`pointerdown`,e,!0)}},[i,Ps,ct]);let Fs=(0,G.useCallback)(e=>{Wa(),e===`projects`?(gi(),Ns()):e!==`search`&&Ns(),z(e)},[Ns,gi,z]),Is=(0,G.useCallback)(()=>{_s(),vs()},[vs,_s]),Ls=(0,G.useCallback)(e=>{e===`plugins`?(Ve.refreshCapability(),He.refreshCapability()):e===`history`&&Ho(),Fs(e),vs()},[Ve.refreshCapability,vs,He.refreshCapability,Ho,Fs]),Rs=(0,G.useCallback)(e=>{Fn(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),zs=(0,G.useCallback)(e=>{Array.isArray(e.projectWorkspaces)&&(ht(Mr(e.projectWorkspaces)),_t(!0)),Array.isArray(e.pinnedProjectWorkspaces)&&yt(Mr(e.pinnedProjectWorkspaces))},[]);(0,G.useEffect)(()=>{m&&zs({projectWorkspaces:m})},[zs,m]),(0,G.useEffect)(()=>{h&&zs({pinnedProjectWorkspaces:h})},[zs,h]);let Bs=(0,G.useCallback)(async e=>{let t=e.trim(),n=t===`/`?`/`:t.replace(/[\\/]+$/,``);if(!n)return;let i=await fetch(r(`/api/projects/mount`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspace:n})}),a=await i.json().catch(()=>null);if(!i.ok)throw Error(a?.error||`Project request failed (${i.status})`);let o=a?.workspace||n;Fn(e=>{if(!e.has(o))return e;let t=new Set(e);return t.delete(o),t})},[]),Vs=(0,G.useCallback)(e=>{Rn(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Hs=(0,G.useCallback)((e,t)=>{Be(`terminal`),z(`projects`),e.kind===`agent`?N(e.id,{focusTerminal:t?.focusTerminal}):Jr.current(e.provider,e.id,e.providerHomeId)},[N,z]),Us=(0,G.useCallback)(()=>{let e=document.activeElement;if(e instanceof HTMLElement){let t=e.closest(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"], [data-testid="code-active-session-row"]`);if(t?.dataset.agentId)return vA({kind:`agent`,id:t.dataset.agentId});if(t?.dataset.sessionId&&t.dataset.provider)return t.dataset.sessionId}let t=Yr.current;return t?vA({kind:`agent`,id:t}):``},[]),Ws=(0,G.useCallback)(e=>{if(Ki.length===0)return;let t=Us(),n=Ki.findIndex(e=>CH(e)===t),r=Ki[((n===-1?e>0?-1:0:n)+e+Ki.length)%Ki.length];r&&(Hs(r,{focusTerminal:!1}),r.kind===`agent`&&(Ms()||js(r),window.requestAnimationFrame(()=>{Ms()||js(r)})),ti.current=`active`)},[Us,js,Hs,Ms,Ki]),Gs=(0,G.useCallback)(e=>{if(!(e.ctrlKey||e.metaKey||e.altKey)){if(e.key===`/`&&!e.shiftKey){e.preventDefault(),_s();return}if(e.key===`ArrowDown`){e.preventDefault(),Ws(1);return}e.key===`ArrowUp`&&(e.preventDefault(),Ws(-1))}},[Ws,_s]),Ks=(0,G.useCallback)(e=>{qi.length!==0&&pt(t=>(t+e+qi.length)%qi.length)},[qi.length]),qs=(0,G.useCallback)(()=>{to&&(Hs(to),Ns())},[Ns,Hs,to]),Js=(0,G.useCallback)(e=>{if(e.key===`Escape`){e.preventDefault(),Ps();return}if(e.key===`ArrowDown`){e.preventDefault(),Ks(1);return}if(e.key===`ArrowUp`){e.preventDefault(),Ks(-1);return}e.key===`Enter`&&(e.preventDefault(),qs())},[Ps,Ks,qs]),Ys=(0,G.useCallback)(e=>{let t=Sr.current?.getBoundingClientRect(),n=e-(t?.left??0);if(n<=oH){mi();return}let r=t?.width??window.innerWidth,i=Math.max(tH,Math.min(nH,r-rH)),a=Math.max(tH,Math.min(i,n));gi(),Bn(a)},[mi,gi]),Xs=(0,G.useCallback)(async()=>{if(!eo)return;let e=OA(eo),t=eo.pinned!==!0;wn(n=>({...n,[e]:t})),Wa(),Et.has(e)?La(eo.provider,e):window.requestAnimationFrame(()=>Hr.current?.focus({preventScroll:!0}));try{if(!(await fetch(r(`/api/agent-sessions/${encodeURIComponent(eo.provider)}/${encodeURIComponent(eo.id)}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t,providerHomeId:eo.providerHomeId||`default`})})).ok)throw Error(J.updateFailed);let n=await Bo({limit:Sn.current});tn(n.sessions),rn(n.nextCursor),on(n.hasMore),wn(t=>{let n={...t};return delete n[e],n})}catch(n){wn(n=>({...n,[e]:!t})),dr({id:Date.now(),kind:`error`,message:n instanceof Error?n.message:J.updateFailed})}},[eo,J.updateFailed,Bo,La,Et]),Zs=(0,G.useCallback)(()=>{if(!eo)return;let e=OA(eo);wn(t=>({...t,[e]:!1})),Es(e),Wa(),window.requestAnimationFrame(()=>Hr.current?.focus({preventScroll:!0}))},[eo,Es]),Qs=(0,G.useCallback)(e=>{e.preventDefault(),gi(),di.current=!0,document.body.classList.add(`code-resizing-sidebar`),Ys(e.clientX)},[gi,Ys]),$s=(0,G.useCallback)((e,t)=>{Wa(),Ns(),Be(`terminal`),z(`projects`),N(e,t)},[Ns,N,z]),ec=(0,G.useCallback)(e=>{Wa(),Ns(),Ae(e.id),Be(`browser`),z(`projects`),vs()},[Ns,Wa,vs,z]),tc=(0,G.useCallback)(e=>{Me(c),ec(e)},[c,ec]),nc=(0,G.useCallback)((t,n)=>{let r=e.find(e=>e.id===t),i=r?.projectWorkspace||r?.cwd||``;i&&(Me(t),Ue(i,{agentId:t,url:n}).then(e=>We(e.id)).then(ec).catch(e=>{dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to open URL in Farming browser`})}))},[e,Ue,ec,We]),rc=(0,G.useCallback)(()=>{let t=je?e.find(e=>e.id===je):X;if(t){$s(t.id,{focusTerminal:!1});return}Be(`terminal`)},[X,e,je,$s]),ic=(0,G.useCallback)(e=>{Wa(),Ns(),Pe(e.id),Be(`computer`),z(`projects`),vs()},[Ns,Wa,vs,z]),ac=(0,G.useCallback)(e=>{Ie(c),ic(e)},[c,ic]),oc=(0,G.useCallback)(()=>{if(!Qa)return;let e=Qa.id,t=bA(Qa);Wa(),Me(e),Ue(t,{agentId:e}).then(e=>We(e.id)).then(ec).catch(e=>dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.updateFailed}))},[Wa,Qa,J.updateFailed,Ue,ec,We]),sc=(0,G.useCallback)(()=>{if(!Qa)return;let e=Qa.id,t=bA(Qa);Wa(),Ie(e),He.create(t,e).then(e=>He.start(e.id)).then(ic).catch(e=>dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.updateFailed}))},[Wa,He,Qa,J.updateFailed,ic]),cc=(0,G.useCallback)(()=>{let t=Fe?e.find(e=>e.id===Fe):X;if(t){$s(t.id,{focusTerminal:!1});return}Be(`terminal`)},[X,e,Fe,$s]),lc=(0,G.useCallback)(e=>{$s(e),vs()},[vs,$s]),uc=(0,G.useCallback)(e=>ge(e,{cursorRequestId:e?.lineNumber?q.current+=1:q.current,diffRequestId:e?.view===`diff`?Xr.current+=1:Xr.current}),[]),dc=(0,G.useCallback)(async(e,t,n)=>{let r=Ci(e,n?.sourceAgentId),i=jr(r.filesId);if(r.workspaceRoot)try{await Bs(r.workspaceRoot)}catch(e){throw dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to create Project`}),e}if(i||r.sourceAgent){let e=i||(r.sourceAgent?.isMain?`__farming_main_agent__`:bA(r.sourceAgent));Fn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}Wa(),Ns(),z(`projects`),Be(`editor`);let a={...uc(n),workspaceRoot:r.workspaceRoot,sourceAgentId:r.sourceAgentId};Je.openFromRead(r.filesId,t,a),H(n)&&pr({agentId:r.filesId,path:t.path,kind:`file`,requestId:Zr.current+=1}),r.sourceAgent&&r.sourceAgentId&&N(r.sourceAgentId,{focusTerminal:!1}),vs()},[Ns,vs,uc,Bs,N,z,Ci,Je]);(0,G.useEffect)(()=>{if(qe.current||Ke.current)return;let e=Ge;if(!e){qe.current=!0;return}if(e.kind===`agent`){if(Y.length===0)return;Ke.current=!0;let t=Y.find(t=>t.id===e.agentId)??Y.find(t=>!!e.providerSessionKey&&t.providerSessionKey===e.providerSessionKey)??Y.find(t=>!!e.workspace&&bA(t)===e.workspace);t?$s(t.id,{focusTerminal:!1}):S({surface:void 0}),qe.current=!0;return}if(!gt)return;Ke.current=!0;let t=Y.find(t=>t.id===e.sourceAgentId&&(e.workspace===`/`||Ar(bA(t))===Ar(e.workspace)))??Y.find(t=>Ar(bA(t))===Ar(e.workspace)),n=e.workspace===`/`?Dt:Ar(e.workspace);if(!(e.workspace===`/`||mt.some(e=>Ar(e)===n)||t)){S({surface:void 0}),qe.current=!0;return}let r=Ci(n,t?.id);fe(r.filesId,e.filePath).then(t=>dc(r.filesId,t,{view:e.view??`editor`,lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn,revealInTree:!0,sourceAgentId:r.sourceAgentId})).catch(()=>{S({surface:void 0})}).finally(()=>{qe.current=!0})},[Y,Ge,dc,$s,mt,gt,Ci]),(0,G.useEffect)(()=>{if(!qe.current||i!==`projects`)return;if(ze===`terminal`){let e=Y.find(e=>e.id===c);if(!e)return;S({surface:{kind:`agent`,agentId:e.id,providerSessionKey:e.providerSessionKey||void 0,workspace:bA(e)}});return}if(!W)return;let e=W.workspaceRoot??Y.find(e=>e.id===W.agentId)?.projectWorkspace??Y.find(e=>e.id===W.agentId)?.cwd??``;e&&S({surface:{kind:`file`,workspace:e,filePath:W.file.path,view:W.diffRequestId?`diff`:`editor`,lineNumber:W.cursor?.lineNumber,column:W.cursor?.column,endColumn:W.cursor?.endColumn,sourceAgentId:W.sourceAgentId}})},[Y,c,i,ze,W]);let fc=(0,G.useCallback)((e,t)=>{let n=Ci(e),r=jr(n.filesId);if(r||n.sourceAgent){let e=r||(n.sourceAgent?.isMain?`__farming_main_agent__`:bA(n.sourceAgent));Fn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}Wa(),Ns(),gi(),z(`projects`),_r({agentId:n.filesId,...t?{query:t}:{},requestId:Qr.current+=1})},[Ns,gi,z,Ci]),pc=(0,G.useCallback)((e,t)=>{fc(e,t)},[fc]),mc=(0,G.useCallback)((e,t,n)=>{let r=Ci(e),i=jr(r.filesId);if(i||r.sourceAgent){let e=i||(r.sourceAgent?.isMain?`__farming_main_agent__`:bA(r.sourceAgent));Fn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}Wa(),Ns(),gi(),z(`projects`),pr({agentId:r.filesId,path:t,kind:n,requestId:Zr.current+=1})},[Ns,gi,z,Ci]),hc=(0,G.useCallback)(async(e,t)=>{let n=Ci(e,e),r=VD(t.path,n.workspaceRoot??``);if(!r){let e=HD(t.path);return e?{...t,path:e,globalRoot:!0,exactExternal:!0}:null}try{let e=MH((await be(n.filesId,r,{limit:cH})).matches),i=e.find(e=>e.path===r)?.path??(e.length===1?e[0]?.path:``);return i?{...t,path:i}:null}catch{return null}},[Ci]),gc=(0,G.useCallback)((e,t)=>{let n=Ci(t.globalRoot?Dt:e,e),r=t.globalRoot?xt(t.path):VD(t.path,n.workspaceRoot??``);if(!r)return;let i=$r.current.begin(),a=jH(t),o={...a??{},...t.globalRoot?{globalRoot:!0}:{},...t.exactExternal?{exactExternal:!0}:{},sourceAgentId:n.sourceAgentId},s=async(e,r=o)=>{let a=await fe(n.filesId,e,{exactExternal:t.exactExternal});i.isCurrent()&&await dc(n.filesId,a,r)},c=e=>{i.isCurrent()&&mc(n.filesId,e,`directory`)},l=async e=>{if(e.entryType===`directory`){c(e.path);return}await s(e.path)},u=()=>{i.isCurrent()&&fc(n.filesId,r)};(async()=>{if(t.exactExternal){try{await s(r)}catch(e){dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to open external file`})}return}try{await le(n.filesId,r),c(r);return}catch{}try{await s(r);return}catch{}try{let e=await be(n.filesId,r,{limit:cH});if(!i.isCurrent())return;let t=MH(e.matches);if(t.length===1){let e=t[0];if(!e)return;await l(e);return}let c=NH(e.matches);if(t.length===0&&c.length===1){let e=c[0];if(!e)return;await s(e.path,!a&&e.kind===`content`?{lineNumber:e.lineNumber,column:e.ranges[0]?e.ranges[0].start+1:void 0,endColumn:e.ranges[0]?Math.max(e.ranges[0].start+1,e.ranges[0].end+1):void 0,sourceAgentId:n.sourceAgentId}:o);return}}catch{}u()})()},[fc,dc,Ci,mc,dr]),_c=(0,G.useCallback)((e,t,n)=>{let r=Ci(e,n?.sourceAgentId),i=jr(r.filesId);if(i||r.sourceAgent){let e=i||(r.sourceAgent?.isMain?`__farming_main_agent__`:bA(r.sourceAgent));Fn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}let a=_e({agentId:r.filesId,workspaceRoot:r.workspaceRoot,filePath:t});if(!rt.some(e=>ve(e)===a))return!1;let o={...uc(n),workspaceRoot:r.workspaceRoot,sourceAgentId:r.sourceAgentId};return Je.select(r.filesId,t,o)?(Wa(),Ns(),z(`projects`),Be(`editor`),H(n)&&pr({agentId:r.filesId,path:t,kind:`file`,requestId:Zr.current+=1}),r.sourceAgent&&r.sourceAgentId&&N(r.sourceAgentId,{focusTerminal:!1}),vs(),!0):!1},[Ns,vs,uc,N,z,rt,Ci,Je]),vc=(0,G.useCallback)(async(e,t,n)=>{let r=Ci(n?.globalRoot?Dt:e,n?.sourceAgentId??(n?.globalRoot?e:void 0)),i=r.filesId,a=n?.globalRoot?xt(t):t,o=n?{...n,sourceAgentId:r.sourceAgentId}:r.sourceAgentId?{sourceAgentId:r.sourceAgentId}:void 0;if(_c(i,a,o))return;let s=async(e,t=o)=>{await dc(i,await fe(i,e,{exactExternal:t?.exactExternal}),t)};try{await s(a,o)}catch{try{await le(i,a),mc(i,a,`directory`)}catch{try{let e=await be(i,a,{limit:cH}),t=MH(e.matches),c=NH(e.matches);if(t.length===1){let e=t[0];if(e?.entryType===`directory`){mc(i,e.path,`directory`);return}if(e?.path){await s(e.path,o);return}}if(t.length===0&&c.length===1){let e=c[0];if(e?.path){await s(e.path,!n&&e.kind===`content`?{lineNumber:e.lineNumber,column:e.ranges[0]?e.ranges[0].start+1:void 0,endColumn:e.ranges[0]?Math.max(e.ranges[0].start+1,e.ranges[0].end+1):void 0,sourceAgentId:r.sourceAgentId}:o);return}}}catch{}o?.suppressSearchOnMiss||fc(i,a)}}},[fc,dc,Ci,mc,_c]),yc=(0,G.useCallback)(async e=>{try{let t=e.exists?await fe(e.rootId,e.filePath):{path:e.filePath,content:``,size:0,mtimeMs:0,sha1:``};await dc(e.rootId,t,{revealInTree:!1})}catch(e){dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to open Agent Home configuration`})}},[dc]),bc=(0,G.useCallback)(async e=>{if(B(e.kind===`agent`?e.readingAnchor:void 0),e.kind===`agent`)return xi.has(e.agentId)?(Wa(),Ns(),z(`projects`),Be(`terminal`),N(e.agentId,{focusTerminal:!1}),vs(),!0):!1;let t=O(e,[...Y.filter(e=>!e.isMain).map(e=>({agentId:e.id,workspace:bA(e)})),...mt.map(e=>({agentId:Ar(e),workspace:e}))],Dt);if(!t)return!1;let n=Ci(t.agentId,t.agentId);if(e.kind===`folder`)try{let e=C((await le(n.filesId,t.filePath)).items);if(e){let t=await fe(n.filesId,e);return await dc(n.filesId,t,{sourceAgentId:n.sourceAgentId}),!0}return mc(n.filesId,t.filePath,`directory`),!0}catch{return!1}let r={..._(e),...t.globalRoot?{globalRoot:!0,exactExternal:!0}:{},sourceAgentId:n.sourceAgentId};if(_c(n.filesId,t.filePath,r))return!0;try{let e=await fe(n.filesId,t.filePath,{exactExternal:t.globalRoot});return await dc(n.filesId,e,r),!0}catch{return!1}},[Y,Ns,vs,N,z,dc,mt,mc,Ci,_c,xi]),xc=(0,G.useRef)(bc);xc.current=bc;let Q=(0,G.useCallback)(()=>{if(typeof window>`u`)return;let e=E(window.location.search);window.history.replaceState(window.history.state,``,`${window.location.pathname}${e}${window.location.hash}`)},[]);(0,G.useEffect)(()=>{if(!Kn)return;let e=!1,t=null,n=Kn.kind===`agent`?Kn.agentId:Kn.absolutePath||(Kn.kind===`folder`?Kn.folderPath:Kn.filePath);return xc.current(Kn).then(r=>{if(!e){if(r){qn(null),Q();return}if(ei.current+=1,ei.current>=20){dr({id:Date.now(),kind:`error`,message:J.sharedLocationUnavailable(n)}),qn(null),Q();return}t=window.setTimeout(()=>{Yn(e=>e+1)},250)}}).catch(()=>{e||(dr({id:Date.now(),kind:`error`,message:J.sharedLocationUnavailable(n)}),qn(null),Q())}),()=>{e=!0,t!==null&&window.clearTimeout(t)}},[Q,J.sharedLocationUnavailable,Kn,Jn]);let Sc=(0,G.useCallback)(async e=>{if(e.kind===`agent`){if(!xi.has(e.agentId))return!1}else if(!Si.has(e.agentId))return!1;if(Wa(),Ns(),z(`projects`),e.kind===`agent`)return Be(`terminal`),N(e.agentId),vs(),!0;let t={view:e.view,lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn,sourceAgentId:e.sourceAgentId},n=Ci(e.agentId,e.sourceAgentId);if(_c(n.filesId,e.filePath,t))return!0;try{let r=await fe(n.filesId,e.filePath);return await dc(n.filesId,r,t),!0}catch{return!1}},[Ns,vs,N,z,dc,Ci,_c,xi,Si]),Cc=(0,G.useCallback)(e=>{let t=et(e);return t?((async()=>{let n=t;for(;n;){if(await Sc(n))return;n=et(e)}})().finally(()=>{tt()}),!0):!1},[et,tt,Sc]),wc=(0,G.useCallback)(e=>{$r.current.invalidate(),Be(`terminal`),z(`projects`),N(e,{focusTerminal:!ae()}),vs()},[vs,N,z]),Tc=(0,G.useCallback)(e=>{let t=Je.close(e);t.closedFiles.length!==0&&t.activeFileClosed&&Be(t.activeFile?`editor`:`terminal`)},[Je]),Ec=(0,G.useCallback)((e,t,n)=>{Tc([{agentId:e,filePath:t,workspaceRoot:n}])},[Tc]),Dc=(0,G.useCallback)((e,t,n)=>{Je.reorder(e,t,n)},[Je]),Oc=(0,G.useCallback)(()=>{let e=Je.reopenLastClosed(e=>Si.has(e.agentId))?.activeFile;if(!e)return!1;Wa(),Ns(),z(`projects`),Be(`editor`);let t=e.sourceAgentId;return t&&Y.some(e=>e.id===t)&&N(t,{focusTerminal:!1}),vs(),!0},[Y,Ns,vs,N,z,Si,Je]),kc=(0,G.useCallback)((e,t)=>Je.update(e,t),[Je]),Ac=(0,G.useCallback)(e=>{Je.updateDraft(e)},[Je]),jc=(0,G.useCallback)((e,t)=>{t.length!==0&&Je.move(e,t)},[Je]),Mc=(0,G.useCallback)((e,t)=>{if(t.length===0)return;let n=Je.deleteEntries(e,t);n.activeFileDeleted&&(n.activeFile||Be(`terminal`))},[Je]),Nc=(0,G.useCallback)(()=>{if(!Qa)return;let e=A(Qa);Wa(),ar({kind:`agent`,agentId:Qa.id,title:e})},[Qa]),Pc=(0,G.useCallback)(()=>{$a&&(Wa(),ar({kind:`project`,projectId:$a.id,workspace:$a.workspace,title:$a.name}))},[$a]),Fc=(0,G.useCallback)(()=>{let e=ir;ar(null),e&&(e.kind===`agent`&&Ia(e.agentId),e.kind===`project`&&Ra(e.projectId))},[Ia,Ra,ir]),Ic=(0,G.useCallback)(()=>{if(!ir)return;let e=ir.title.trim();if(ir.kind===`agent`){if(!e)return;I(ir.agentId,e),ar(null),Ia(ir.agentId);return}e&&(St({...bt,[ir.workspace]:e}),fetch(r(`/api/projects/name`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspace:ir.workspace,name:e})}).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||J.copyFailed)}).catch(()=>{St(t=>{if(t[ir.workspace]!==e)return t;let n={...t},r=bt[ir.workspace];return r?n[ir.workspace]=r:delete n[ir.workspace],n}),dr({id:Date.now(),kind:`error`,message:J.copyFailed})}),ar(null),Ra(ir.projectId))},[J.copyFailed,Ia,Ra,I,bt,ir]),Lc=(0,G.useCallback)(async(e,t)=>{Wa();let n=await Se(e);dr({id:Date.now(),kind:n?`success`:`error`,message:n?J.copiedWorkingDirectory:J.copyFailed}),t?.kind===`agent`&&Ia(t.id),t?.kind===`agent-session`&&La(t.provider,OA(t))},[J.copiedWorkingDirectory,J.copyFailed,Ia,La]),Rc=(0,G.useCallback)(()=>{Qa&&(Wa(),sr({agentId:Qa.id,title:A(Qa),acknowledgeUnprovenAcpExit:Qa.requiresProcessExitAcknowledgement===!0}))},[Qa]),zc=(0,G.useCallback)(()=>{let e=or?.agentId;sr(null),e&&Ia(e)},[Ia,or?.agentId]),Bc=(0,G.useCallback)(()=>{or&&(ie(or.agentId,{acknowledgeUnprovenAcpExit:or.acknowledgeUnprovenAcpExit}),sr(null))},[or,ie]),Vc=(0,G.useCallback)(e=>{Qa&&(Wa(),R(Qa.id,e))},[Qa,R]),Hc=(0,G.useCallback)(e=>{if(!Qa)return;let t=Qa.id;if(Wa(),e.archived===!0){let e=Qa.providerSessionKey||iM(Qa.source);e&&Es(e),ni.current=t}e.archived===!0?ks(t):L(t,e),e.archived!==!0&&Ia(t)},[ks,Qa,Ia,L,Es]),Uc=(0,G.useCallback)((e,t)=>{let n=e.id;if(Wa(),t.archived===!0){let t=e.providerSessionKey||iM(e.source);t&&Es(t),ni.current=n}t.archived===!0?ks(n):L(n,t),t.archived!==!0&&Ia(n)},[ks,Ia,L,Es]),Wc=(0,G.useCallback)(async(e,t,n)=>{try{let i=await fetch(r(`/api/agents/${encodeURIComponent(e)}/reorder`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({beforeAgentId:t,afterAgentId:n})});if(!i.ok){let e=await i.json().catch(()=>null);throw Error(e?.error||J.reorderAgentFailed)}}catch(e){dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.reorderAgentFailed})}},[J.reorderAgentFailed]),Gc=(0,G.useCallback)(e=>{ni.current=null,ri.current=e,L(e,{archived:!1}),Ns(),z(`projects`),[120,360,720,1200,1800].forEach(t=>{window.setTimeout(()=>{Ms()||Fa(e)},t)})},[Ns,Fa,L,z,Ms]),Kc=(0,G.useCallback)(e=>{te(e)},[te]),qc=(0,G.useCallback)(async(e,t,n=``,i=``)=>{let a=OA({provider:e,id:t,providerHomeId:n}),o=()=>{tn(r=>r.map(r=>r.provider===e&&r.id===t&&(r.providerHomeId||`default`)===(n||`default`)?{...r,archived:!1}:r))},s=Y.find(r=>(r.providerSessionKey===a||r.source===nM(e,t,n))&&r.archived!==!0&&r.status!==`dead`&&r.status!==`stopped`);if(s){try{await Bs(bA(s))}catch(e){dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to resume agent session`});return}o(),Ts(e,t,n),N(s.id),vs();return}try{let a=await fetch(r(`/api/agent-sessions/${encodeURIComponent(e)}/${encodeURIComponent(t)}/resume`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({unarchiveArchived:!0,providerHomeId:n,...[`codex`,`claude`,`opencode`,`qoder`,`qwen`].includes(e)?{agentRuntimeMode:`chat`,acpHistoryMode:`load`}:{},...i?{customTitle:i}:{}})}),s=await a.json().catch(()=>null);if(!a.ok||!s?.agentId){dr({id:Date.now(),kind:`error`,message:s?.error||`Failed to resume agent session (${a.status})`});return}o(),Ts(e,t,n),P(s.agentId),vs()}catch(e){dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to resume agent session`})}},[Y,Ts,vs,Bs,N,P]);Jr.current=qc;let Jc=(0,G.useCallback)(e=>{let t=SH(e.source);if(t){qc(t.provider,t.sessionId,t.providerHomeId,e.customTitle||``),z(`projects`);return}F(SF(e),e.command||void 0,null,e.customTitle||void 0)},[F,z,qc]),Yc=(0,G.useCallback)(e=>{if(!de()){e.preventDefault(),e.stopPropagation(),Wa(),$n(!0);return}Xa(e)},[Wa,Xa]),Xc=(0,G.useCallback)(async()=>{Wa();try{let e=w(lo),t=await fetch(r(`/api/share/qr-ticket`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e?{target:e}:{})}),n=await t.json().catch(()=>null);if(!t.ok||!n?.longUrl&&!n?.shortUrl)throw Error(n?.error||J.shareLinkFailed);rr(n.longUrl||n.shortUrl||``)}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.shareLinkFailed})}},[J.shareLinkFailed,lo]),Zc=(0,G.useCallback)(e=>{Wa(),ye({language:e})},[ye]),Qc=(0,G.useCallback)(e=>{Wa(),ye({appearance:e})},[ye]),$c=(0,G.useCallback)(()=>{Wa(),$n(!0)},[]),el=(0,G.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),Wa(),$n(!0)},[]),tl=(0,G.useCallback)(e=>{$n(!1),FI(e,{onEnd:()=>$n(!0)})},[]),nl=(0,G.useMemo)(()=>de()?LP([{type:`separator`,id:`options-mobile-share-separator`},{type:`item`,id:`options-mobile-share`,label:J.sharePage,ariaLabel:J.sharePage,onSelect:Xc}]):LP([{type:`item`,id:`options-appearance-system`,label:ZV(J.appearanceSystem),ariaLabel:J.appearanceSystem,checked:M.appearance===`system`,onSelect:()=>Qc(`system`)},{type:`item`,id:`options-appearance-light`,label:ZV(J.appearanceLight),ariaLabel:J.appearanceLight,checked:M.appearance===`light`,onSelect:()=>Qc(`light`)},{type:`item`,id:`options-appearance-dark`,label:ZV(J.appearanceDark),ariaLabel:J.appearanceDark,checked:M.appearance===`dark`,onSelect:()=>Qc(`dark`)},{type:`separator`,id:`options-appearance-language-separator`},{type:`item`,id:`options-language-en`,label:YV(J.languageEnglish),ariaLabel:J.languageEnglish,checked:M.language===`en`,onSelect:()=>Zc(`en`)},{type:`item`,id:`options-language-zh`,label:YV(J.languageChinese),ariaLabel:J.languageChinese,checked:M.language===`zh`,onSelect:()=>Zc(`zh`)},{type:`separator`,id:`options-settings-separator`},{type:`item`,id:`options-open-settings`,label:J.openSettings,ariaLabel:J.openSettings,onSelect:$c}]),[J.appearanceDark,J.appearanceLight,J.appearanceSystem,J.languageChinese,J.languageEnglish,J.openSettings,J.sharePage,$c,Xc,M.appearance,M.language,Qc,Zc]),rl=(0,G.useCallback)((e,t)=>{fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentLaunchProfiles:{[e]:t}})}).catch(()=>{})},[]),il=(0,G.useCallback)(e=>{if(l)return;if(_a===`claude`){let t=uB(e)?e:`default`;Gt(t),rl(`claude`,{permissionMode:t}),X&&(dr({id:Date.now(),kind:`success`,message:J.permissionProfileRestarting}),L(X.id,{launchPermissionMode:t})),Pa(),Mo();return}let t=lB(e)?e:`approve`;At(t),rl(`codex`,{approvalMode:t}),X&&_a===`codex`&&(dr({id:Date.now(),kind:`success`,message:J.permissionProfileRestarting}),L(X.id,{launchPermissionMode:t})),Pa(),Mo()},[X,Pa,_a,J.permissionProfileRestarting,Mo,L,l,rl]),al=(0,G.useCallback)((e,t)=>{l||(dr({id:Date.now(),kind:`success`,message:J.runtimeModeRestarting}),L(e,{agentRuntimeMode:t}))},[J.runtimeModeRestarting,L,l]),ol=(0,G.useCallback)((e,t)=>{let n=Y.find(t=>t.id===e);l||!uA(n)||tA(n)||(Wa(),al(e,t))},[Y,l,al]),sl=(0,G.useCallback)((e,t,n)=>{Mt(e),Pt(t),It(n),rl(`codex`,{model:e,reasoningEffort:t,serviceTier:n})},[rl]),cl=(0,G.useCallback)(e=>{if(_a===`claude`){let t=mB(e);qt(t),Pa(),Mo(),rl(`claude`,{model:t,effort:Jt});return}let t=Lt.find(t=>t.value===e),n=t?.reasoningLevels??[],r=t?.serviceTiers??[],i=n.some(e=>e.value===Ca)?Ca:t?.defaultEffort||n[0]?.value||Ca,a=r.some(e=>e.value===wa)?wa:`default`;if(Pa(),Mo(),X&&bH(X)){is(X,e,i,a).then(t=>{t&&sl(e,i,a)});return}sl(e,i,a)},[X,is,Jt,Pa,Lt,Ca,wa,sl,_a,Mo,rl]),ll=(0,G.useCallback)((e,t)=>{if(_a!==`codex`)return;let n=Lt.find(t=>t.value===e);if(!n)return;let r=n.reasoningLevels?.some(e=>e.value===t)?t:n.defaultEffort||n.reasoningLevels?.[0]?.value||t,i=n.serviceTiers?.some(e=>e.value===wa)?wa:`default`;if(X&&bH(X)){is(X,e,r,i).then(t=>{t&&sl(e,r,i)});return}sl(e,r,i)},[X,is,Lt,wa,sl,_a]),ul=(0,G.useCallback)(e=>{if(_a===`claude`){let t=gB(e);Yt(t),Pa(),Mo(),rl(`claude`,{model:Kt,effort:t});return}if(Pa(),Mo(),X&&bH(X)){is(X,Sa,e,wa).then(t=>{t&&sl(Sa,e,wa)});return}sl(Sa,e,wa)},[X,is,Kt,Pa,Sa,wa,sl,_a,Mo,rl]),dl=(0,G.useCallback)(e=>{if(_a!==`claude`){if(Pa(),Mo(),X&&bH(X)){is(X,Sa,Ca,e).then(t=>{t&&sl(Sa,Ca,e)});return}sl(Sa,Ca,e)}},[X,is,Pa,Sa,Ca,sl,_a,Mo]),fl=(0,G.useCallback)(e=>{if(_a===`codex`){if(X&&bH(X)){is(X,Sa,Ca,e).then(t=>{t&&sl(Sa,Ca,e)});return}sl(Sa,Ca,e)}},[X,is,Sa,Ca,sl,_a]),pl=(0,G.useCallback)(()=>{if(kn){Ur.current?.stop(),Ur.current=null,An(!1);return}let e=ia;if(!e)return;let t=ae(),n=vH(),r=Dn&&!n?window.SpeechRecognition||window.webkitSpeechRecognition:null;if(!r){(vH()||t)&&Mo(),An(!1);return}let i=new r,a=null,o=()=>{a!==null&&(window.clearTimeout(a),a=null)},s=()=>{if(Ur.current===i)try{i.stop()}catch{An(!1),Ur.current=null}};i.continuous=!1,i.interimResults=!1,i.lang=M.language===`zh`?`zh-CN`:navigator.language||`en-US`,i.onresult=t=>{let n=``;for(let e=t.resultIndex;e<t.results.length;e+=1)n+=t.results[e]?.[0]?.transcript??``;n.trim()&&(Ce(e,e=>{let t=e.draft&&!/\s$/.test(e.draft)?` `:``;return{...e,draft:`${e.draft}${t}${n.trim()}`}}),Mo())},i.onerror=()=>{o(),An(!1)},i.onspeechend=s,i.onaudioend=s,i.onend=()=>{o(),An(!1),Ur.current=null},Ur.current=i,An(!0);try{i.start(),a=window.setTimeout(s,6e4)}catch{o(),Ur.current=null,An(!1),t&&Mo()}},[ia,Mo,kn,Dn,M.language,Ce]),ml=(0,G.useCallback)(async()=>{if(!$a?.workspace)return;let e=$a.id,t=$a.workspace;Wa();try{let e=await fetch(r(`/api/projects/pin`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspace:t,pinned:!$a.pinned})}),n=await e.json().catch(()=>null);if(!e.ok)throw Error(n?.error||`Project request failed (${e.status})`)}catch(e){dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.copyFailed})}window.requestAnimationFrame(()=>Ra(e))},[$a,J.copyFailed,Ra]),hl=(0,G.useCallback)(async()=>{if(!$a?.workspace)return;let e=$a.id,t=Ar($a.workspace);Wa();try{let e=await fetch(r(`/api/projects/reveal`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({rootId:t})}),n=await e.json().catch(()=>null);if(!e.ok)throw Error(n?.error||J.revealInFinderFailed)}catch(e){dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.revealInFinderFailed})}Ra(e)},[$a,J.revealInFinderFailed,Ra]),gl=(0,G.useCallback)(async()=>{if(!$a?.workspace)return;let e=$a.id,t=Ar($a.workspace);Wa();let n=`create:${t}`,i=ai.current.get(n)||globalThis.crypto?.randomUUID?.()||`${Date.now()}-${Math.random()}`;ai.current.set(n,i);try{let e=await fetch(r(`/api/projects/create-worktree`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({rootId:t,requestId:i})}),a=await e.json().catch(()=>null);if((e.ok||a?.retryable!==!0&&a?.uncertain!==!0)&&ai.current.delete(n),!e.ok)throw Error(a?.error||J.permanentWorktreeFailed);dr({id:Date.now(),kind:`success`,message:J.permanentWorktreeCreated})}catch(e){dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.permanentWorktreeFailed})}Ra(e)},[$a,J.permanentWorktreeCreated,J.permanentWorktreeFailed,Ra]),_l=(0,G.useCallback)(()=>{if(!$a)return;let e=$a.id;$a.agents.forEach(e=>{e.unread&&$o(e.id,!0)}),Wa(),Ra(e)},[$a,Ra,$o]),vl=(0,G.useCallback)(()=>{if(!$a)return;let e=$a.workspace,t=$a.agents.filter(e=>!e.isMain),n=Ei.filter(t=>AA(t)===e);if(t.length===0&&n.length===0){Wa(),ti.current=`list`;return}t.forEach(e=>ks(e.id)),Ds(n.map(OA)),Wa(),ti.current=`list`},[ks,Ei,$a,Ds]),yl=(0,G.useCallback)(async()=>{if(!(!$a||$a.hasMain||$a.agents.length>0||$a.agentSessions.length>0||$a.hasOpenFile)){try{let e=await fetch(r(`/api/projects/remove`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspace:$a.workspace})}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||`Project request failed (${e.status})`)}catch(e){dr({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.copyFailed})}Wa(),ti.current=`list`}},[$a,J.copyFailed]),bl=(0,G.useCallback)(()=>{$a&&(Wa(),lr({projectId:$a.id,workspace:$a.workspace,sessionHandles:$a.agentSessions.map(OA)}))},[$a]),xl=(0,G.useCallback)(()=>{let e=cr?.projectId;lr(null),e&&Ra(e)},[cr?.projectId,Ra]),Sl=(0,G.useCallback)(async()=>{if(!cr)return;let e=cr,t=await ne(e.workspace,{force:!0});t.deleted&&(Ds([...e.sessionHandles,...t.removedMainPageSessionKeys??[]]),ti.current=`list`,lr(null))},[cr,ne,Ds]),Cl=(0,G.useCallback)(e=>{let t=Array.from(e.currentTarget.querySelectorAll(`button:not(:disabled)`)),n=e.target instanceof Element?e.target.closest(`button`):null,r=t.findIndex(e=>e===n||e===document.activeElement);if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),Pa(),Mo();return}if(e.key===`Tab`){e.preventDefault(),e.stopPropagation();let t=da?`[data-testid="code-composer-model-picker"]`:fa?wH()?`[data-testid="code-composer-send"]`:`[data-testid="code-composer-mic"]`:`[data-testid="code-composer-approval"]`;Pa(),window.requestAnimationFrame(()=>{document.querySelector(t)?.focus({preventScroll:!0})});return}if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let n=e.key===`ArrowDown`?1:-1;t[r===-1?n>0?0:t.length-1:(r+n+t.length)%t.length]?.focus();return}if(e.key===`Home`){e.preventDefault(),e.stopPropagation(),t[0]?.focus();return}e.key===`End`&&(e.preventDefault(),e.stopPropagation(),t[t.length-1]?.focus())},[da,Pa,Mo,fa]),wl=(0,G.useCallback)(e=>{let t=e.relatedTarget;t&&(t instanceof Node&&e.currentTarget.contains(t)||t instanceof Element&&t.closest(`.code-composer`)||Pa())},[Pa]);(0,G.useEffect)(()=>{function e(e){if(a)return;let t=e.target;if(za){if(qa(e,Ua.current))return;if(e.key.length===1||e.key===`Tab`||e.key===`ArrowDown`||e.key===`ArrowUp`||e.key===`Home`||e.key===`End`){e.preventDefault(),e.stopPropagation();return}}if(e.key===`Escape`&&ir){e.preventDefault(),Fc();return}if(e.key===`Escape`&&or){e.preventDefault(),zc();return}if(e.key===`Escape`&&cr){e.preventDefault(),xl();return}if(ir||or||cr){Ln(t)||(e.preventDefault(),e.stopPropagation());return}let n=j?zr(e):null;if(n){DH(e),Cc(n);return}if($V(e)&&!Ln(t)){e.preventDefault(),e.stopPropagation(),Oc();return}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`p`&&!e.altKey&&!e.shiftKey&&!ir&&!or&&!cr&&!Ln(t)&&!xH(t)&&!Nn(t)){let n=oo(t)??ao;if(!n)return;e.preventDefault(),fc(n);return}if(!(Pn(t)||Nn(t))&&!(Ln(t)&&e.key!==`Escape`)&&!(e.key===`Escape`&&t instanceof HTMLElement&&t.closest(`.code-plugin-detail-dialog`))){if(e.key===`Escape`&&(ua||da||fa)){e.preventDefault(),Pa(),Mo();return}if(e.key===`Escape`&&i!==`projects`){e.preventDefault(),Wa(),Ns(),z(`projects`),ti.current=`active-force`;return}if(e.key===`Escape`&&za){e.preventDefault(),Ga();return}if(j){if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`b`){e.preventDefault(),_i();return}e.key===`/`&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey&&(e.preventDefault(),_s())}}}return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[i,da,Ns,Pa,Ga,xl,zc,Fc,za,cr,a,Mo,fc,qa,j,or,fa,Cc,z,_s,ua,ao,oo,ir,Oc,_i]),(0,G.useEffect)(()=>{if(!ir)return;let e=ir.title,t=!1;return Xz(()=>{let n=Fr.current;if(!n)return;let r=document.activeElement;if(r!==n&&!Ir.current?.contains(r)&&n.focus(),!t&&document.activeElement===n&&n.value===e){if(t=!0,ir.kind===`project`){let e=n.value.length;n.setSelectionRange(e,e);return}n.select()}},{delays:[0,80,180,360]})},[vr]),(0,G.useEffect)(()=>or?Xz(()=>{Lr.current?.contains(document.activeElement)||Rr.current?.focus()},{runNow:!1,delays:[180]}):void 0,[or]),(0,G.useEffect)(()=>cr?Xz(()=>{Br.current?.contains(document.activeElement)||Vr.current?.focus()},{runNow:!1,delays:[180]}):void 0,[cr]),(0,G.useEffect)(()=>{if(!ur)return;let e=window.setTimeout(()=>dr(null),1700);return()=>window.clearTimeout(e)},[ur]),(0,G.useEffect)(()=>{function e(e){let t=e.target;t instanceof Element&&t.closest(`.code-composer-menu-anchor`)||Pa()}if(!(!ua&&!da&&!fa))return window.addEventListener(`pointerdown`,e),()=>window.removeEventListener(`pointerdown`,e)},[da,Pa,fa,ua]),(0,G.useEffect)(()=>{if(!fa)return;let e=window.setTimeout(()=>{let e=pa===`model`?`.code-model-submenu .code-model-option.selected`:pa===`speed`?`.code-speed-submenu .code-model-option.selected`:`.code-model-picker-menu > .code-model-option.selected`,t=Nr.current?.querySelector(e),n=Nr.current?.querySelector(`button:not(:disabled)`);(t??n)?.focus()},0);return()=>window.clearTimeout(e)},[fa,pa,fo,po,mo]),(0,G.useEffect)(()=>{if(!ua)return;let e=window.setTimeout(()=>{Or.current?.querySelector(`button:not(:disabled)`)?.focus()},0);return()=>window.clearTimeout(e)},[ua]),(0,G.useEffect)(()=>{if(!da)return;let e=window.setTimeout(()=>{let e=kr.current?.querySelector(`.code-approval-option.selected`),t=kr.current?.querySelector(`button:not(:disabled)`);(e??t)?.focus()},0);return()=>window.clearTimeout(e)},[da,vo]),(0,G.useEffect)(()=>{if(!xe)return;let e=window.setInterval(()=>xr(Date.now()),6e4);return()=>window.clearInterval(e)},[xe]),(0,G.useEffect)(()=>{let e=window.matchMedia(`(max-width: 980px)`),t=()=>{On(!!(window.SpeechRecognition||window.webkitSpeechRecognition)&&!vH())};return t(),e.addEventListener(`change`,t),()=>{e.removeEventListener(`change`,t),Ur.current?.stop(),Ur.current=null}},[]),(0,G.useEffect)(()=>Po(),[Po]),(0,G.useEffect)(()=>{document.title=`${er} · Farming Code`},[er]),(0,G.useEffect)(()=>{let e=()=>{Po(),Vo()};return window.addEventListener(`farming-agent-homes-saved`,e),()=>window.removeEventListener(`farming-agent-homes-saved`,e)},[Vo,Po]),(0,G.useEffect)(()=>{if(_a===`claude`)return Lo()},[_a,Lo]),(0,G.useEffect)(()=>{Gr.current!==$i&&Rt([])},[$i]),(0,G.useEffect)(()=>Go(_a||``,$i,X?.cwd),[X?.cwd,$i,_a,Go]),(0,G.useEffect)(()=>{if(!(!fa||_a!==`codex`))return Io()},[_a,Io,fa]),(0,G.useEffect)(()=>{if(!fa||_a!==`codex`){qr.current=!1;return}let e=()=>{qr.current&&(qr.current=!1,Io())};return window.addEventListener(`farming:backend-connected`,e),()=>window.removeEventListener(`farming:backend-connected`,e)},[_a,Io,fa]),(0,G.useEffect)(()=>Vo(),[Vo]),(0,G.useEffect)(()=>{jo()},[jo,ia,la,sa]),(0,G.useEffect)(()=>{aa.composer.permissionMode||aa.composer.modelPicker||Na(e=>{let t=KN(e);return aa.composer.plusMenu||t.mode===`default`?t:{...t,mode:`default`}})},[aa,Na]),(0,G.useEffect)(()=>{i!==`search`&&ct&&Ns(),i!==`projects`&&(Wa(),Pa())},[i,Ns,Pa,ct]),(0,G.useEffect)(()=>{a&&(Wa(),Pa())},[Pa,a]),(0,G.useEffect)(()=>{if(i===`projects`)return Po()},[i,Po]),(0,G.useEffect)(()=>{if(i!==`history`)return;let e=Po(),t=Vo(!0);return()=>{e(),t()}},[i,Vo,Po]),(0,G.useEffect)(()=>{function e(e){di.current&&(e.preventDefault(),Ys(e.clientX))}function t(){di.current&&(di.current=!1,document.body.classList.remove(`code-resizing-sidebar`))}return window.addEventListener(`pointermove`,e),window.addEventListener(`pointerup`,t),window.addEventListener(`pointercancel`,t),()=>{window.removeEventListener(`pointermove`,e),window.removeEventListener(`pointerup`,t),window.removeEventListener(`pointercancel`,t),document.body.classList.remove(`code-resizing-sidebar`)}},[Ys]),(0,G.useEffect)(()=>{let e=Sr.current;if(!e||typeof ResizeObserver>`u`)return;let t=e=>{if(wH()){pi.current||hi(),pi.current=!0;return}if(pi.current=!1,TH(e)){hi();return}fi.current&&gi()};t(e.getBoundingClientRect().width);let n=new ResizeObserver(n=>{t(n[0]?.contentRect.width??e.getBoundingClientRect().width)});return n.observe(e),()=>n.disconnect()},[hi,gi]),(0,G.useEffect)(()=>{let e=ti.current;if(e&&!(i!==`projects`||ct))return ti.current=null,Zz(()=>{if(Ms())return!1;if(e===`list`)return Hr.current?.focus({preventScroll:!0}),document.activeElement===Hr.current;let t=As();return e===`active-force`?!1:t},{initialDelay:e===`list`?0:50,retryDelay:90,maxAttempts:e===`active-force`?4:12,animationFrame:!1})},[c,i,As,ct,Ms]),(0,G.useEffect)(()=>{let e=ni.current;if(e&&!(i!==`projects`||ct))return Zz(()=>{if(Ms())return!1;let t=As(),n=document.activeElement;return t&&n instanceof HTMLElement&&n.dataset.agentId!==e?(ni.current=null,!0):!1},{initialDelay:50,retryDelay:90,maxAttempts:12,animationFrame:!1})},[Y.length,c,i,As,ct,Ms]),(0,G.useEffect)(()=>{let e=ri.current;if(e&&!(i!==`projects`||ct)&&Y.some(t=>t.id===e))return ri.current=null,Zz(()=>!Ms()&&Fa(e),{initialDelay:50,retryDelay:80,maxAttempts:60})},[Y,i,Fa,ct,Ms]),(0,G.useEffect)(()=>{io&&Zn(io)},[io]),(0,G.useEffect)(()=>{pt(0)},[Vi,ct]),(0,G.useEffect)(()=>{pt(e=>qi.length===0?0:Math.min(e,qi.length-1))},[qi.length]);let Tl={"--code-sidebar-width":`${Vn?aH:zn}px`};return(0,K.jsxs)(`div`,{className:`code-workspace ${Vn?`sidebar-collapsed`:``}`,"data-testid":`code-workspace`,ref:Sr,style:Tl,children:[(0,K.jsx)(UR,{sidebarCollapsed:Vn,emptyHomeActionRequest:Un,activeView:i,searchOpen:ct,displayedProjects:Ri,collapsedProjectIds:Mn,normalizedSearch:``,hasProjectListItems:Wi,hasDisplayedProjectListItems:Wi,activeTerminalId:c,selectedSearchAgentId:no,selectedSearchSessionHandle:ro,claimedAgentSessionKeyByAgentId:Ti.claimedAgentSessionKeyByAgentId,agentShortcutKeys:Ji,keyboardShortcutsEnabled:j,now:br,mainAgent:bi,usageSummary:o,instanceName:er,language:M.language,appearancePreference:M.appearance,restReminderEntryBlocked:Qn||!!nr||!!ir||!!or||!!cr||a,shareTarget:lo,agentLaunchOptions:Ct,agentCreationWorkspace:so,openWorkspaceFile:W,openWorkspaceFiles:rt,fileRevealRequest:fr,fileSearchFocusRequest:gr,projectListRef:Hr,canLoadMoreAgentSessions:an,onLoadMoreAgentSessions:Wo,onNewAgent:bs,onStartAgent:xs,onToggleSidebar:_i,onOpenSearch:Is,onOpenWorkspaceView:Ls,onOpenMainAgent:()=>{bi&&(Be(`terminal`),z(`projects`),N(bi.id))},onRestartMainAgent:re,onProjectListKeyDown:Gs,onToggleProject:Rs,onToggleProjectSessions:Vs,onMountProject:Bs,onOpenProjectMenu:Za,onOpenAgent:lc,onUpdateAgentFlags:Uc,onReorderAgent:Wc,onOpenAgentMenu:Ja,onResumeAgentSession:qc,onOpenAgentSessionMenu:Ya,onOpenProjectFile:dc,onSelectOpenWorkspaceFile:_c,onCloseOpenWorkspaceFile:Ec,onMoveWorkspaceEntries:jc,onDeleteWorkspaceEntries:Mc,onRefreshProjectOpenFiles:st,onOpenOptionsMenu:el,onRenameInstance:Fo,copy:J}),(0,K.jsx)(kz,{projects:Ri,collapsedProjectIds:Mn,activeBrowserId:ze===`browser`?ke:null,controller:Ve,language:M.language,onOpen:tc,forceAvailable:zi.size>0,additionalAgentResourceIds:zi,renderAdditionalAgentResources:({agentId:e,workspace:t})=>{let n=He.byAgentId.get(e)??null,r=(Ve.byAgentId.get(e)??[]).filter(e=>e.browserKind===`isolated-computer`&&(e.status===`starting`||e.status===`running`||e.status===`stopping`)).length;return(0,K.jsx)(Fz,{workspace:t,agentId:e,resource:n,active:ze===`computer`&&Ne===n?.id,controller:He,language:M.language,collapsed:Le.has(e),isolatedBrowserCount:r,onToggle:()=>{Re(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},onOpen:ac})}}),(0,K.jsx)(Uz,{open:Qn,activeAgentId:i===`projects`?X?.id??null:null,language:M.language,uiPreferences:M,onClose:()=>$n(!1),onPreviewPetAppearance:tl,onSyncUiPreferences:he,onUpdateUiPreferences:ye}),nr&&(0,K.jsx)(IP,{copy:J,title:Eo,url:nr,onClose:()=>rr(``)}),(0,K.jsx)(`div`,{className:`code-sidebar-resizer`,"data-testid":`code-sidebar-resizer`,role:`separator`,"aria-label":J.resizeNavigation,"aria-orientation":`vertical`,"aria-valuemin":tH,"aria-valuemax":nH,"aria-valuenow":Vn?aH:zn,onPointerDown:Qs}),!Vn&&(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-sidebar-backdrop`,"data-testid":`code-mobile-sidebar-backdrop`,"aria-label":J.closeNavigation,onPointerDown:hi}),(0,K.jsxs)(`div`,{className:`code-mobile-topbar`,"data-testid":`code-mobile-topbar`,children:[Ao?(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button back`,"data-testid":`code-mobile-back`,"aria-label":J.backToAgent,onClick:()=>{ko&&wc(ko)},children:(0,K.jsx)(`span`,{"aria-hidden":`true`})}):(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button menu`,"data-testid":`code-mobile-menu`,"aria-label":J.openNavigation,onClick:ys,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})}),(0,K.jsxs)(`div`,{className:`code-mobile-topbar-title`,children:[(0,K.jsx)(`strong`,{children:Eo}),Oo&&(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`i`,{"aria-hidden":`true`}),Oo]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button more`,"data-testid":`code-mobile-more`,"aria-label":J.openOptions,onClick:Yc,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})})]}),Z&&(0,K.jsx)(`div`,{className:`code-context-menu code-options-menu`,"data-testid":`code-options-menu`,style:{left:Z.x,top:Z.y},role:`menu`,ref:Ua,onKeyDownCapture:Ka,onKeyDown:Ka,children:(0,K.jsx)(IH,{entries:nl})}),(0,K.jsx)(PN,{activeView:i,activeBrowserResource:ze===`browser`?it:null,browserController:Ve,onBackFromBrowser:rc,onOpenBrowserResource:ec,activeComputerResource:ze===`computer`?at:null,computerController:He,onBackFromComputer:cc,language:M.language,showFileEditor:co,openWorkspaceFile:W,openWorkspaceFiles:rt,openAgentsCount:Xi.length,openAgents:Qi,activeTerminalId:c,permissionSwitchingAgentId:l,agentSwitchingKind:u,terminalFocusRequest:p,agentCreationWorkspace:so,displayedProjects:Gi,searchQuery:ut,searchHasQuery:Hi,searchLoading:gn,visibleSearchTargetCount:qi.length,selectedSearchAgentId:no,selectedSearchSessionHandle:ro,searchInputRef:Pr,archivedRuns:Mi,archivedAgents:ji,historyAgentSessions:Ni,historyAgentSessionsLoading:un,historyAgentSessionsError:fn,providerSessionTotal:cn,canLoadMoreHistoryAgentSessions:an,now:br,acpComposerProps:{active:!!X&&!ta,agentId:X?.id||``,runtimeState:ea?.state||``,sessionUpdatedAt:ea?.sessionUpdatedAt||``,runtimeError:ea?.error||``,draft:sa,attachments:ca,composerMode:la,contextWindow:ra,pendingFollowUp:Da??null,submissions:Oa??[],canSteerPendingFollowUp:ha&&X?.providerCapabilities.supportsSteer===!0,submitAction:Ma,textareaRef:Cr,attachmentInputRef:Dr,permissions:ea?.pendingPermissions.length?ea.pendingPermissions:ea?.pendingPermission?[ea.pendingPermission]:[],elicitations:ea?.pendingElicitations.length?ea.pendingElicitations:ea?.pendingElicitation?[ea.pendingElicitation]:[],activeElicitations:ea?.activeElicitations||[],speechSupported:Dn,speechListening:kn,onDraftChange:ns,onNavigateHistory:rs,onRemoveAttachment:Yo,onSubmit:ss,onInterrupt:ds,onDiscardPendingFollowUp:hs,onEditPendingFollowUp:gs,onSteerPendingFollowUp:ls,onRetrySubmission:cs,onDiscardSubmission:us,onToggleSpeechInput:pl,onPasteAttachment:Zo,onAttachmentFiles:Xo,onChooseAttachmentFile:Ko,onActivateComposerMode:Qo,onClearComposerMode:()=>{Na(e=>({...e,mode:`default`}))},onRespondToPermission:fs,onRespondToElicitation:ps},composerProps:{active:!!X&&!ta,agentKind:_a,capabilities:aa.composer,slashCommands:Ea,draft:sa,attachments:ca,composerMode:la,plusMenuOpen:ua,approvalMenuOpen:da,modelMenuOpen:fa,modelPickerPane:pa,agentModelPreset:ho,agentModel:fo,agentReasoningEffort:po,agentServiceTier:mo,agentModelOptions:uo,currentPermissionMode:vo,permissionModeDisabled:!!l,modelProfileDisabled:na||!!(X&&bH(X)&&X.terminalStatus?.activity===`busy`),currentPermissionLabel:yo,currentPermissionColor:bo,permissionModeHint:J.permissionRestartHint,currentModelLabel:xo,currentReasoningLabel:So,currentSpeedLabel:Co,currentReasoningOptions:go,currentServiceTierOptions:_o,permissionModeOptions:wo,contextWindow:ra,pendingFollowUp:Da?{messages:Da.messages,createdAt:Da.createdAt}:null,submitAction:ja,speechSupported:Dn,speechListening:kn,textareaRef:Cr,attachmentInputRef:Dr,plusMenuRef:Or,approvalMenuRef:kr,modelMenuRef:Nr,onDraftChange:ns,onNavigateHistory:rs,onRemoveAttachment:Yo,onSubmit:os,onInterrupt:ds,onSendPendingFollowUp:ms,onDiscardPendingFollowUp:hs,onEditPendingFollowUp:gs,onPasteAttachment:Zo,onAttachmentFiles:Xo,onChooseAttachmentFile:Ko,onActivateComposerMode:Qo,onClearComposerMode:()=>{Na(e=>({...e,mode:`default`})),Mo()},onTogglePlusMenu:()=>{Na(e=>({...e,ui:{plusMenuOpen:!e.ui.plusMenuOpen,approvalMenuOpen:!1,modelMenuOpen:!1,modelPickerPane:null}}))},onToggleApprovalMenu:()=>{Na(e=>({...e,ui:{plusMenuOpen:!1,approvalMenuOpen:!e.ui.approvalMenuOpen,modelMenuOpen:!1,modelPickerPane:null}}))},onToggleModelMenu:()=>{Na(e=>({...e,ui:{plusMenuOpen:!1,approvalMenuOpen:!1,modelMenuOpen:!e.ui.modelMenuOpen,modelPickerPane:null}}))},onCloseMenus:Pa,onSetModelPickerPane:e=>{Na(t=>({...t,ui:{...t.ui,modelPickerPane:e}}))},onComposerMenuKeyDown:Cl,onComposerMenuBlur:wl,onUpdatePermissionMode:il,onUpdateModel:cl,onUpdateReasoningEffort:ul,onUpdateServiceTier:dl,onUpdateModelProfile:ll,onUpdateServiceTierInline:fl,onToggleSpeechInput:pl},onNewAgent:F,onOpenHistory:()=>Ls(`history`),onOpenPlugins:()=>Ls(`plugins`),onOpenAgentHomeConfiguration:yc,onOpenSearch:Is,onOpenShare:()=>vi(`share`),onOpenAppMode:()=>vi(`focus`),onOpenTerminal:N,onOpenTerminalPath:gc,onResolveTerminalPath:hc,onSearchTerminalWord:pc,onTerminalFollowOutputChange:ts,onAgentReadLatest:es,onRuntimeModeChange:al,onForkAgent:R,onSessionOutput:se,onOpenSearchAgent:$s,onOpenSearchSession:e=>{qc(e.provider,e.id,e.providerHomeId),Ns(),z(`projects`)},onSearchQueryChange:dt,onSearchKeyDown:Js,onCloseSearch:Ps,onBackToProjects:()=>Fs(`projects`),onLoadMoreHistoryAgentSessions:Wo,onSearchHistoryAgentSessions:zo,onResumeHistorySession:qc,onContinueArchivedRun:Jc,onOpenArchivedAgent:Kc,onRestoreArchivedAgent:Gc,onChangeWorkspaceFileDraft:Ac,onUpdateOpenWorkspaceFile:kc,onSelectOpenWorkspaceFile:_c,onOpenWorkspaceFilePath:vc,onOpenUrlInFarming:Ve.capability?.available?nc:void 0,canNavigateWorkspaceBack:Ye,canNavigateWorkspaceForward:Xe,onNavigateWorkspaceHistory:Cc,onCloseOpenWorkspaceFile:Ec,onCloseOpenWorkspaceFiles:Tc,onReorderOpenWorkspaceFile:Dc,onRevealWorkspaceFileInExplorer:mc,onFocusWorkspaceFilesSearch:fc,onRecordWorkspaceNavigationCursor:$e,onBackToAgentFromFile:wc,copy:J}),(0,K.jsx)(RP,{contextMenuAgent:Qa,contextMenuAgentSession:eo,contextMenuProject:$a,agentMenu:Ba,projectMenu:Va,agentSessionMenu:Ha,renameDialog:ir,killDialog:or,deleteWorktreeDialog:cr,copyNotice:ur,contextMenuRef:Ua,renameDialogRef:Ir,renameInputRef:Fr,killDialogRef:Lr,killCancelButtonRef:Rr,deleteWorktreeDialogRef:Br,deleteWorktreeCancelButtonRef:Vr,onContextMenuKeyDown:Ka,runtimeSwitchDisabled:!!l,canCreateAgentBrowser:Ve.capability?.available===!0,canCreateAgentDesktop:!!(He.capability?.enabled===!0&&He.capability.available===!0&&Qa&&!He.byAgentId.has(Qa.id)),onSwitchAgentRuntime:ol,onCreateAgentBrowser:oc,onCreateAgentDesktop:sc,onUpdateAgentFlags:Hc,onRenameAgent:Nc,onRenameProject:Pc,onCopyAgentWorkingDirectory:()=>{Qa&&Lc(bA(Qa),{kind:`agent`,id:Qa.id})},onForkAgent:Vc,onKillAgent:Rc,onOpenSession:(e,t)=>{Wa(),qc(e,t,eo?.providerHomeId),eo&&La(e,OA(eo))},onToggleSessionPinned:Xs,onArchiveSession:Zs,onCopySessionWorkingDirectory:()=>{eo&&Lc(jA(eo),{kind:`agent-session`,provider:eo.provider,id:eo.id,providerHomeId:eo.providerHomeId})},onToggleProjectPinned:ml,onRevealProject:hl,onCreatePermanentWorktree:gl,onMarkProjectRead:_l,onArchiveProject:vl,onRemoveProject:yl,onDeleteWorktree:bl,onCloseRenameDialog:Fc,onRenameDialogTitleChange:e=>ar(t=>t&&{...t,title:e}),onSubmitRenameDialog:Ic,onCloseKillDialog:zc,onSubmitKillDialog:Bc,onCloseDeleteWorktreeDialog:xl,onSubmitDeleteWorktreeDialog:Sl,copy:J})]})}function IH({entries:e}){return(0,K.jsx)(K.Fragment,{children:e.map(e=>e.type===`separator`?(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`},e.id):(0,K.jsxs)(`button`,{type:`button`,role:typeof e.checked==`boolean`?`menuitemradio`:`menuitem`,"aria-checked":typeof e.checked==`boolean`?e.checked:void 0,"aria-label":e.ariaLabel,className:[e.danger?`danger`:``,typeof e.checked==`boolean`?`selectable`:``,e.checked?`checked`:``].filter(Boolean).join(` `)||void 0,disabled:e.disabled,onClick:e.onSelect,children:[typeof e.checked==`boolean`&&(0,K.jsx)(`span`,{className:`code-options-menu-check`,"aria-hidden":`true`,children:e.checked?(0,K.jsx)(Ze,{}):null}),e.icon&&(0,K.jsx)(`span`,{className:`code-context-menu-icon`,"aria-hidden":`true`,children:(0,K.jsx)(VP,{kind:e.icon})}),(0,K.jsx)(`span`,{children:e.label}),e.trailingIcon&&(0,K.jsx)(`span`,{className:`code-context-menu-icon trailing`,"aria-hidden":`true`,children:(0,K.jsx)(VP,{kind:e.trailingIcon})})]},e.id))})}function LH(e=`terminal`,t={}){if(typeof document>`u`)return;let n=document.body,r=document.documentElement,i=t.crtEffects!==!1,a=mR(t.appearance),o=_R(a);r.dataset.appearancePreference=a,r.dataset.appearance=o,n.dataset.theme=e,n.dataset.crtEffects=i?`on`:`off`,n.dataset.appearancePreference=a,n.dataset.appearance=o,document.querySelector(`meta[name="color-scheme"]`)?.setAttribute(`content`,o),document.querySelector(`meta[name="theme-color"]`)?.setAttribute(`content`,o===`dark`?`#181818`:`#ffffff`),i?n.classList.remove(`no-crt`):n.classList.add(`no-crt`)}var RH=!1,zH=240,BH=3e4,VH=1e4,HH=6e4,UH=45e3,WH=6e4;function GH(e){if(e)return e.gitWorktree?.workspace?e.gitWorktree.workspace:e.projectWorkspace?e.projectWorkspace:e.cwd}function KH(e){return!e.archived&&e.status!==`dead`&&e.status!==`stopped`}function qH(e,t){return e.restartedFromAgentId===t||e.restartedFromAgentIds?.includes(t)===!0}function JH(e,t,n){return e.filter(e=>KH(e)&&qH(e,t)&&(!n?.providerSessionProvider||!n.providerSessionId||e.providerSessionProvider===n.providerSessionProvider&&(n.providerSessionTemporary===!0||e.providerSessionId===n.providerSessionId)&&(e.providerHomeId||``)===(n.providerHomeId||``))).sort((e,t)=>{let n=(t.restartedFromAgentIds?.length??0)-(e.restartedFromAgentIds?.length??0);return n===0?(t.startedAt??0)-(e.startedAt??0):n})[0]??null}function YH(e){return e?.providerSessionProvider===`codex`&&!!e.providerSessionId&&e.providerSessionTemporary!==!0}function XH(e){if(!e||!e.isConnected||e.getAttribute(`aria-disabled`)===`true`||`disabled`in e&&e.disabled)return!1;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&e.getClientRects().length>0}function ZH(e){return XH(e)?(e.focus({preventScroll:!0}),document.activeElement===e||e.contains(document.activeElement)):!1}function QH(){yr(`app`);let e=Dn(),t=jn(),{keyMap:n}=Mn(e.agents,e.mainAgentId),[i]=(0,G.useState)(()=>T()),[a,o]=(0,G.useState)(`none`),[s,c]=(0,G.useState)(void 0),[l,u]=(0,G.useState)(void 0),[d,p]=(0,G.useState)(void 0),[m,h]=(0,G.useState)(()=>i.openTerminalIds??[]),[_,v]=(0,G.useState)(()=>{let e=i.activeTerminalId??i.openTerminalIds?.[0];return e?[e]:[]}),[y,b]=(0,G.useState)(()=>i.activeTerminalId??null),[x,C]=(0,G.useState)(null),[w,E]=(0,G.useState)(null),[D,O]=(0,G.useState)(()=>i.activeView??`projects`),[k,A]=(0,G.useState)(null),[j,M]=(0,G.useState)(null),[N,P]=(0,G.useState)(null),[F,ee]=(0,G.useState)(null),[I,L]=(0,G.useState)({}),[te,R]=(0,G.useState)(()=>({...pR,appearance:mR(typeof document>`u`?void 0:document.documentElement.dataset.appearancePreference)})),ne=(0,G.useRef)(null),re=(0,G.useRef)(null),z=(0,G.useRef)(new Set),ie=(0,G.useRef)(new Map),B=(0,G.useRef)(new Map),oe=(0,G.useRef)(null),V=(0,G.useRef)(null),se=(0,G.useRef)([]),ce=(0,G.useRef)(!1),le=(0,G.useRef)(!1),ue=(0,G.useRef)(!1),fe=(0,G.useRef)(void 0),pe=(0,G.useRef)(null),me=(0,G.useRef)(0),he=(0,G.useRef)(0),ge=(0,G.useRef)(Promise.resolve()),H=(0,G.useRef)(null);(0,G.useEffect)(()=>Tr(()=>{H.current?.abort()}),[]),(0,G.useLayoutEffect)(()=>{se.current=m},[m]),(0,G.useEffect)(()=>{S({activeTerminalId:y,activeView:D,openTerminalIds:m})},[y,D,m]);let _e=(0,G.useCallback)(e=>{V.current=e,M(e)},[]),ve=a,ye=(0,G.useMemo)(()=>Jz(te.language),[te.language]),be=(0,G.useMemo)(()=>{if(!j)return e.agents;let t=e.agents.filter(e=>e.id===j.agent.id||!qH(e,j.originalAgentId));return t.some(e=>e.id===j.agent.id)?t:[...t,j.agent]},[j,e.agents]),Se=(0,G.useMemo)(()=>{let e=new Map,t=new Set([...m,..._]);return y&&t.add(y),t.forEach(t=>{if(be.some(e=>e.id===t&&KH(e)))return;let n=JH(be,t);n&&e.set(t,n.id)}),e},[y,be,m,_]),U=(0,G.useMemo)(()=>{if(y){let e=Se.get(y);if(e)return{originalAgentId:y,replacementAgentId:e}}let e=Se.entries().next().value;return e?{originalAgentId:e[0],replacementAgentId:e[1]}:null},[y,Se]),Ce=(0,G.useMemo)(()=>Array.from(new Set(m.map(e=>Se.get(e)??e))),[Se,m]),we=(0,G.useMemo)(()=>GV(_.map(e=>Se.get(e)??e)),[Se,_]),Te=y?Se.get(y)??y:null;(0,G.useLayoutEffect)(()=>{U&&(h(Ce),v(we),b(Te),P(U))},[Te,Ce,we,U]),(0,G.useLayoutEffect)(()=>{Te&&v(e=>qV(e,Te))},[Te]),(0,G.useEffect)(()=>{!N||U||P(null)},[N,U]),(0,G.useEffect)(()=>{let t=V.current;if(!t)return;let n=JH(e.agents,t.originalAgentId,t.agent);if(!n||n.id===t.agent.id)return;let r=t.agent.id,i={...t,agent:n,replacementAgentId:n.id,transitionFromAgentId:r};h(e=>Array.from(new Set(e.map(e=>qH(n,e)?n.id:e)))),v(e=>KV(e,e.map(e=>qH(n,e)?n.id:e))),b(e=>e&&qH(n,e)?n.id:e),_e(i)},[_e,j?.agent.id,j?.originalAgentId,e.agents]),(0,G.useEffect)(()=>{let t=j;!t?.requestSettled||!t.replacementAgentId||e.agents.some(e=>e.id===t.agent.id)&&V.current?.agent.id===t.agent.id&&(oe.current=null,_e(null))},[_e,j?.agent.id,j?.replacementAgentId,j?.requestSettled,e.agents]),(0,G.useEffect)(()=>{let e=j;if(!e?.requestSettled||!e.requestError||e.replacementAgentId)return;let t=e.requestErrorAt??Date.now(),n=()=>{let n=g();if(e.requestFreshStateAt||!n.connected||n.lastMessageAt<=t)return!1;let r=V.current;return r?.originalAgentId===e.originalAgentId&&!r.replacementAgentId&&!r.requestFreshStateAt&&_e({...r,requestFreshStateAt:n.lastMessageAt}),!0};if(n())return;let r=f(n),i=t+HH,a=e.requestFreshStateAt?e.requestFreshStateAt+VH:1/0,o=Math.max(0,Math.min(i,a)-Date.now()),s=window.setTimeout(()=>{let t=V.current;!t?.requestSettled||!t.requestError||t.replacementAgentId||t.originalAgentId!==e.originalAgentId||(oe.current=null,_e(null),A({id:Date.now(),kind:`error`,message:t.requestError}))},o);return()=>{r(),window.clearTimeout(s)}},[_e,j]),(0,G.useEffect)(()=>{let e=j;if(!e)return;let t=Math.max(0,e.startedAt+WH-Date.now()),n=window.setTimeout(()=>{let t=V.current;!t||t.startedAt!==e.startedAt||(oe.current=null,_e(null),A({id:Date.now(),kind:`error`,message:ye.agentRestartTimedOut}))},t);return()=>window.clearTimeout(n)},[_e,ye.agentRestartTimedOut,j]);let Ee=(0,G.useCallback)(e=>{let t={};Object.prototype.hasOwnProperty.call(e,`appearance`)&&(t.appearance=mR(e.appearance)),Object.prototype.hasOwnProperty.call(e,`language`)&&(t.language=hR(e.language)),Object.prototype.hasOwnProperty.call(e,`codeContentFontSize`)&&(t.codeContentFontSize=Lt(e.codeContentFontSize)),Object.prototype.hasOwnProperty.call(e,`composerFollowUpBehavior`)&&(t.composerFollowUpBehavior=gR(e.composerFollowUpBehavior));let n={...te,...t},i=he.current+1;he.current=i,R(n),ge.current=ge.current.catch(()=>{}).then(()=>fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).then(e=>e.json()).then(e=>{if(he.current!==i)return;let t=e.settings??{};R({appearance:mR(t.appearance??n.appearance),codeContentFontSize:Lt(t.codeContentFontSize??n.codeContentFontSize),composerFollowUpBehavior:gR(t.composerFollowUpBehavior??n.composerFollowUpBehavior),language:hR(t.language??n.language)})}).catch(()=>{he.current===i&&(R(te),A({id:Date.now(),kind:`error`,message:`Failed to save preferences`}))})},[te]),De=(0,G.useCallback)(e=>{R(t=>({...t,...Object.prototype.hasOwnProperty.call(e,`composerFollowUpBehavior`)?{composerFollowUpBehavior:gR(e.composerFollowUpBehavior)}:{}}))},[]),Oe=(0,G.useCallback)(e=>{let t=Array.from(new Set(e.filter(Boolean)));t.length!==0&&fetch(r(`/api/codex/context-windows`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentIds:t})}).then(e=>e.json()).then(e=>{let t=Array.isArray(e.contextWindows)?e.contextWindows:[];L(e=>{let n={...e};return t.forEach(e=>{let t=String(e?.agentId||``);t&&(e&&e.available===!0?n[t]=e:delete n[t])}),n})}).catch(()=>{})},[]);(0,G.useEffect)(()=>{if(e.connected){if(e.mainAgentId||e.agents.some(e=>e.isMain)){ce.current=!1;return}ce.current||(ce.current=!0,e.startAgent(`bash`,void 0,!0))}},[e.agents,e.connected,e.mainAgentId,e.startAgent]),(0,G.useEffect)(()=>{let e=()=>{let e=window.visualViewport,t=e?.width??window.innerWidth,n=e?.height??window.innerHeight,r=e?.offsetTop??0,i=e?.offsetLeft??0,a=de(),o=ae(),s=window.innerHeight||n||zH,c=a?Math.min(Math.max(n,zH),Math.max(s,zH)):n,l=Math.max(0,s-n-r),u=o&&xe(),d=a&&o&&l>80,f=navigator.standalone===!0||window.matchMedia(`(display-mode: standalone)`).matches;document.body.classList.toggle(`code-compact-layout`,a),document.body.classList.toggle(`code-mobile-touch`,a&&o),document.body.classList.toggle(`code-mobile-ios`,u),document.body.classList.toggle(`code-mobile-standalone`,a&&f),document.body.classList.toggle(`code-mobile-keyboard-active`,d),document.documentElement.style.setProperty(`--app-visual-width`,`${t}px`),document.documentElement.style.setProperty(`--app-visual-height`,`${c}px`),document.documentElement.style.setProperty(`--app-visual-offset-top`,`${r}px`),document.documentElement.style.setProperty(`--app-visual-offset-left`,`${i}px`),document.documentElement.style.setProperty(`--mobile-keyboard-offset`,`${l}px`)};return e(),window.addEventListener(`resize`,e),window.visualViewport?.addEventListener(`resize`,e),window.visualViewport?.addEventListener(`scroll`,e),()=>{window.removeEventListener(`resize`,e),window.visualViewport?.removeEventListener(`resize`,e),window.visualViewport?.removeEventListener(`scroll`,e),document.documentElement.style.removeProperty(`--app-visual-width`),document.documentElement.style.removeProperty(`--app-visual-height`),document.documentElement.style.removeProperty(`--app-visual-offset-top`),document.documentElement.style.removeProperty(`--app-visual-offset-left`),document.documentElement.style.removeProperty(`--mobile-keyboard-offset`),document.body.classList.remove(`code-compact-layout`),document.body.classList.remove(`code-mobile-touch`),document.body.classList.remove(`code-mobile-ios`),document.body.classList.remove(`code-mobile-standalone`),document.body.classList.remove(`code-mobile-keyboard-active`)}},[]);let ke=(0,G.useCallback)((t,n)=>{y!==t&&e.focusAgent(t),h(e=>e.includes(t)?e:[...e,t]),v(e=>qV(e,t)),b(t),O(`projects`),n?.focusTerminal!==!1&&C(e=>({agentId:t,nonce:(e?.nonce??0)+1})),o(`none`)},[y,e]),Ae=(0,G.useCallback)((e,t)=>{Cr(),E({agentId:e,options:t})},[]),je=(0,G.useCallback)((e,t)=>{if(e===y&&m.includes(e)){Cr(),ke(e,t);return}Ae(e,t)},[ke,y,m,Ae]);(0,G.useEffect)(()=>{w&&be.some(e=>e.id===w.agentId&&KH(e))&&(E(null),ke(w.agentId,w.options))},[ke,be,w]);let Me=(0,G.useCallback)((e,t={})=>{let n=new Set(e);if(n.size===0)return;let r=se.current,i=r.indexOf(y??``),a=r.filter(e=>!n.has(e)),o=i===-1?a[a.length-1]??null:a[Math.min(i,a.length-1)]??null;se.current=a,h(a),v(e=>{let t=GV(e.filter(e=>!n.has(e)));return o?qV(t,o):t}),b(e=>!e||!n.has(e)?e:o),t.focusNextTerminal!==!1&&y&&n.has(y)&&o&&C(e=>({agentId:o,nonce:(e?.nonce??0)+1}))},[y]),Ne=(0,G.useCallback)((e,t)=>{Me([e],t)},[Me]),Pe=(0,G.useCallback)(e=>{if(m.length===0)return;let t=m[(Math.max(0,m.findIndex(e=>e===y))+e+m.length)%m.length];t&&je(t)},[y,je,m]),Fe=(0,G.useCallback)((e,t,n,r)=>{let i=me.current+1;me.current=i,pe.current=n??(document.activeElement instanceof HTMLElement?document.activeElement:null),c(e),u(t),p(r),O(`projects`),o(`input`);let a=()=>{me.current===i&&o(e=>e===`input`?e:`input`)};window.requestAnimationFrame(a),window.setTimeout(a,80),window.setTimeout(a,180)},[]),Ie=(0,G.useCallback)(()=>{let e=me.current,t=pe.current,n=t?.getAttribute(`data-testid`)===`code-new-agent`;pe.current=null;let r=()=>{me.current===e&&(ZH(t)||n&&ZH(document.querySelector(`[data-testid="code-new-agent"]`))||ZH((y?Array.from(document.querySelectorAll(`[data-testid="code-agent-row"]`)).find(e=>e.dataset.agentId===y):null)??null)||ZH(document.querySelector(`[data-testid="code-new-agent"]`))||ZH(document.querySelector(`[data-testid="code-project-list"]`)))};window.requestAnimationFrame(r),window.setTimeout(r,80),window.setTimeout(r,180)},[y]),Le=(0,G.useCallback)(()=>{me.current+=1,o(`none`),Ie()},[Ie]),Re=(0,G.useCallback)(e=>{A({id:Date.now(),kind:`error`,message:e})},[]),ze=(0,G.useCallback)((t,n={})=>{CT(t).catch(e=>{console.error(`Failed to destroy killed terminal session:`,e)}),e.killAgent(t,n),Ne(t)},[e,Ne]),Be=(0,G.useCallback)(t=>{e.interruptAgent(t)},[e]),Ve=(0,G.useCallback)(t=>{re.current||(ce.current=!0,re.current={beforeIds:new Set(e.agents.map(e=>e.id))},e.restartMainAgent(t)||(re.current=null,ce.current=!1))},[e]),He=(0,G.useCallback)((t,n,r)=>{ne.current||(me.current+=1,ne.current={beforeIds:new Set(e.agents.map(e=>e.id))},e.startAgent(t,n,!1,r)||(ne.current=null))},[e]);(0,G.useEffect)(()=>{let t=e.lastStartedAgentId,n=ne.current;!t||!n||n.beforeIds.has(t)||(ne.current=null,o(`none`),Ae(t))},[Ae,e.lastStartedAgentId]);let Ue=(0,G.useCallback)(async(e,t,n)=>{if(z.current.has(e))return;z.current.add(e);let i=[e,t,n?.targetRuntime||``,n?.expectedRevision??``].join(`:`),a=ie.current.get(i)||globalThis.crypto?.randomUUID?.()||`${Date.now()}-${Math.random()}`;ie.current.set(i,a);try{let o=await fetch(r(`/api/agents/${e}/fork`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mode:t,...n,requestId:a})}),s=await o.json().catch(()=>null);if((o.ok||s?.retryable!==!0&&s?.uncertain!==!0)&&ie.current.delete(i),!o.ok||!s?.agentId){Re(s?.error||`Failed to fork agent (${o.status})`);return}Ae(s.agentId)}catch(e){Re(e instanceof Error?e.message:`Failed to fork agent`)}finally{z.current.delete(e)}},[Re,Ae]),We=(0,G.useCallback)(async(e,t)=>{let n=`delete:${e}:${t?.force===!0?`force`:`safe`}`,i=B.current.get(n)||globalThis.crypto?.randomUUID?.()||`${Date.now()}-${Math.random()}`;B.current.set(n,i);try{let a=await fetch(r(`/api/projects/delete-worktree`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspace:e,force:t?.force===!0,requestId:i})}),o=await a.json().catch(()=>null);if((a.ok||o?.retryable!==!0&&o?.uncertain!==!0)&&B.current.delete(n),!a.ok&&o?.requiresForce!==!0&&Re(o?.error||`Failed to delete worktree (${a.status})`),o?.deleted&&Me(o.archivedAgentIds??[]),o)return o;let s=`Failed to delete worktree (${a.status})`;return Re(s),{error:s}}catch(e){let t=e instanceof Error?e.message:`Failed to delete worktree`;return Re(t),{error:t}}},[Me,Re]),Ge=(0,G.useCallback)(async(e,t)=>{try{let n=await fetch(r(`/api/agents/${e}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({customTitle:t})}),i=await n.json().catch(()=>null);n.ok||Re(i?.error||`Failed to rename agent (${n.status})`)}catch(e){Re(e instanceof Error?e.message:`Failed to rename agent`)}},[Re]),Ke=(0,G.useCallback)(async(t,n)=>{if(n.unread===!1&&Object.keys(n).every(e=>e===`unread`||e===`readAttentionSeq`||e===`readOutputEpoch`||e===`readOutputSeq`)&&oe.current===t)return!0;let i=typeof n.launchPermissionMode==`string`?n.launchPermissionMode:``,a=typeof n.agentRuntimeMode==`string`,o=i||a?e.agents.find(e=>e.id===t)??null:null;if(o){if(oe.current)return!1;oe.current=t,_e({originalAgentId:t,agent:o,kind:a?`runtime`:`permission`,startedAt:Date.now()})}let s=()=>{o&&V.current?.originalAgentId===t&&(oe.current=null,_e(null))};try{let e=new AbortController,a=window.setTimeout(()=>e.abort(),UH),c=await fetch(r(`/api/agents/${t}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n),signal:e.signal});window.clearTimeout(a);let l=await c.json().catch(()=>null);if(!c.ok){let e=V.current;return o&&e?.originalAgentId===t&&e.replacementAgentId?(_e({...e,requestSettled:!0}),l??!0):(s(),Re(l?.error||`Failed to update agent (${c.status})`),n.archived===!0&&l?.archived===!0?l:!1)}if(l?.warning&&Re(l.warning),n.archived===!0&&Ne(t,{focusNextTerminal:!1}),l?.restartedAgentId){let e=l.restartedAgentId,r=V.current;o&&r?.originalAgentId===t&&(r.agent.id===t?(h(n=>n.map(n=>n===t?e:n)),v(n=>KV(n,n.map(n=>n===t?e:n))),b(n=>n===t?e:n),_e({...r,replacementAgentId:e,transitionFromAgentId:t,requestSettled:!0,agent:{...r.agent,id:e,launchPermissionMode:l.launchPermissionMode??i,runtimeBinding:gr(l.agentRuntimeMode??n.agentRuntimeMode,r.agent.runtimeBinding),restartedFromAgentId:t,restartedFromAgentIds:Array.from(new Set([...r.agent.restartedFromAgentIds??[],t]))}})):_e({...r,requestSettled:!0,requestError:void 0}))}else s();return l??!0}catch(e){let r=e instanceof DOMException&&e.name===`AbortError`?ye.agentRestartTimedOut:e instanceof Error?e.message:`Failed to update agent`,i=V.current;return o&&i?.originalAgentId===t?(_e({...i,requestSettled:!0,requestError:r,requestErrorAt:Date.now()}),!!i.replacementAgentId):n.archived===!0&&e instanceof DOMException&&e.name===`AbortError`?{uncertain:!0}:(Re(r),!1)}},[Ne,_e,ye.agentRestartTimedOut,Re,e.agents]),qe=(0,G.useCallback)(async e=>{await Ke(e,{archived:!1})&&Ae(e)},[Ke,Ae]),Je=(0,G.useMemo)(()=>be.find(e=>e.id===Te)??null,[be,Te]);return(0,G.useEffect)(()=>{if(!t||!YH(Je))return;let e=Je.id,n,r;return n=window.setTimeout(()=>Oe([e]),2500),r=window.setInterval(()=>Oe([e]),BH),()=>{n!==void 0&&window.clearTimeout(n),r!==void 0&&window.clearInterval(r)}},[Je?.id,Je?.providerSessionId,Je?.providerSessionProvider,Je?.providerSessionTemporary,t,Oe]),(0,G.useEffect)(()=>{let e=GH(Je);e&&(fe.current=e)},[Je]),Bn((0,G.useMemo)(()=>[],[Je,Pe,n,Fe,je]),RH),(0,G.useEffect)(()=>{if(e.error){if(ne.current=null,E(null),re.current=null,ce.current=!1,e.errorKind===`recoverable`){A({id:Date.now(),kind:`recovering`,message:ye.backendActionPending});return}Re(e.error)}},[ye.backendActionPending,Re,e.error,e.errorId,e.errorKind]),(0,G.useEffect)(()=>{if(!k)return;let e=window.setTimeout(()=>A(null),2800);return()=>window.clearTimeout(e)},[k]),(0,G.useEffect)(()=>{if(!t)return;let e=!1,n,i,a=()=>{if(wr())return;H.current?.abort();let t=new AbortController;H.current=t,fetch(r(`/api/usage`),{signal:t.signal}).then(e=>e.json()).then(t=>{e||ee(t.usage??null)}).catch(()=>{!e&&!t.signal.aborted&&ee(null)}).finally(()=>{H.current===t&&(H.current=null)})};return i=window.setTimeout(a,1500),n=window.setInterval(a,6e4),()=>{e=!0,H.current?.abort(),H.current=null,i!==void 0&&window.clearTimeout(i),n!==void 0&&window.clearInterval(n)}},[t]),(0,G.useEffect)(()=>{wT(we).catch(e=>{console.error(`Failed to prune terminal sessions:`,e)})},[we]),(0,G.useEffect)(()=>{let e=new Set(be.filter(KH).map(e=>e.id));h(t=>Array.from(new Set(t.map(t=>e.has(t)?t:JH(be,t)?.id??t))).filter(t=>e.has(t)||V.current?.agent.id===t)),v(t=>KV(t,t.map(t=>e.has(t)?t:JH(be,t)?.id??t).filter(t=>e.has(t)||V.current?.agent.id===t)))},[be]),(0,G.useEffect)(()=>{let e=new Set(be.filter(KH).map(e=>e.id));b(t=>t&&(e.has(t)||V.current?.agent.id===t)?t:m[0]??null)},[be,m]),(0,G.useEffect)(()=>{be.some(e=>!e.isMain&&KH(e))||(le.current=!1)},[be]),(0,G.useEffect)(()=>{if(m.length>0||le.current)return;let e=be.find(e=>!e.isMain&&KH(e))?.id;e&&(le.current=!0,h([e]),v([e]),b(e))},[be,m.length,e.mainAgentId]),(0,G.useEffect)(()=>{let t=re.current;if(!t)return;let n=e.agents.find(e=>e.isMain&&!e.archived&&!t.beforeIds.has(e.id));n&&(re.current=null,ce.current=!1,je(n.id))},[je,e.agents]),(0,G.useEffect)(()=>{if(ue.current||e.agents.length===0)return;let t=new URLSearchParams(window.location.search).get(`agent`);if(!t){ue.current=!0;return}e.agents.some(e=>e.id===t&&!e.archived)&&(ue.current=!0,je(t))},[je,e.agents]),(0,G.useLayoutEffect)(()=>(document.body.classList.add(`code-mode`),()=>{document.body.classList.remove(`code-mode`)}),[]),(0,G.useLayoutEffect)(()=>{let e=()=>{LH(`terminal`,{crtEffects:!1,appearance:te.appearance})};if(e(),te.appearance!==`system`)return;let t=window.matchMedia(`(prefers-color-scheme: dark)`);return t.addEventListener(`change`,e),()=>t.removeEventListener(`change`,e)},[te.appearance]),(0,G.useLayoutEffect)(()=>{DT(Mt(te.codeContentFontSize))},[te.codeContentFontSize]),(0,G.useEffect)(()=>{let e=!1;return fetch(r(`/api/settings`)).then(e=>e.json()).then(t=>{if(e)return;let n=t.settings??{};R({appearance:mR(n.appearance),codeContentFontSize:Lt(n.codeContentFontSize),composerFollowUpBehavior:gR(n.composerFollowUpBehavior),language:hR(n.language)})}).catch(()=>{}),()=>{e=!0}},[]),(0,K.jsxs)(`div`,{className:`app-container code-app-shell`,"data-testid":`app-shell`,children:[(0,K.jsx)(FH,{agents:be,taskHistory:e.taskHistory,mainPageSessionKeys:e.mainPageSessionKeys,activeView:D,dialogOpen:ve!==`none`,usageSummary:F,contextWindowByAgentId:I,activeTerminalId:Te,permissionSwitchingAgentId:j?.agent.id??null,agentSwitchingKind:j?.kind??null,permissionSwitchReplacement:j?.replacementAgentId?{originalAgentId:j.originalAgentId,replacementAgentId:j.replacementAgentId,transitionFromAgentId:j.transitionFromAgentId}:U??N,retainedAgentViewIds:we,terminalFocusRequest:x,remoteProjectWorkspaces:e.projectWorkspaces,remotePinnedProjectWorkspaces:e.pinnedProjectWorkspaces,browserResourceState:e.browserResources,computerResourceState:e.computerResources,keyMap:n,keyboardShortcutsEnabled:RH,uiPreferences:te,onOpenTerminal:je,onOpenTerminalWhenReady:Ae,onNewAgent:Fe,onStartAgent:He,onRenameAgent:Ge,onUpdateAgentFlags:Ke,onOpenArchivedAgent:qe,onForkAgent:Ue,onDeleteForkWorktreeProject:We,onRestartMainAgent:Ve,onWorkspaceViewChange:O,onKill:ze,onInterruptAgent:Be,sendComposerInput:e.sendComposerInput,onSessionOutput:e.onSessionOutput,onBrowserResource:e.mergeBrowserResource,onBrowserResourceDeletion:e.deleteBrowserResource,onComputerResource:e.mergeComputerResource,onComputerResourceDeletion:e.deleteComputerResource,onSyncUiPreferences:De,onUpdateUiPreferences:Ee}),(0,K.jsx)(fr,{open:ve===`input`,mustStartMain:!1,initialWorkspace:s,initialCommand:l,initialCustomTitle:d,showWorkflowTaskFields:!1,copy:ye,onStart:He,onClose:Le}),(0,K.jsx)(pr,{copy:ye}),k&&(0,K.jsx)(`div`,{className:`app-toast ${k.kind}`,"data-testid":`app-toast`,role:`status`,children:k.message})]})}export{QH as App};