@cortex-agent/server 2026.10.28 → 2026.12.5

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 (401) hide show
  1. package/LICENSE +255 -21
  2. package/README.md +36 -7
  3. package/THIRD_PARTY_NOTICES.txt +1990 -593
  4. package/defaults/hooks/cortex-hook-api.mjs +2 -1
  5. package/defaults/hooks/quota-stop.mjs +37 -0
  6. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
  7. package/defaults/prompts/clean-workspace.md +5 -0
  8. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  9. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  10. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  11. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  12. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  13. package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
  14. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  15. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  16. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  17. package/dist/chunks/chunk-2ABET62E.js +23 -0
  18. package/dist/chunks/chunk-2BVUA256.js +4 -0
  19. package/dist/chunks/{chunk-LEUENXI2.js → chunk-2WFL62UO.js} +1 -1
  20. package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
  21. package/dist/chunks/chunk-335SSANX.js +4 -0
  22. package/dist/chunks/chunk-377OPTXX.js +17 -0
  23. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  24. package/dist/chunks/chunk-3O6ZG5HA.js +7 -0
  25. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  26. package/dist/chunks/chunk-4HRI75GU.js +4 -0
  27. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  28. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  29. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  30. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  31. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  32. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  33. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  34. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  35. package/dist/chunks/{chunk-XNSSUVT6.js → chunk-5FHETFZM.js} +1 -1
  36. package/dist/chunks/{chunk-A34TDMIC.js → chunk-5LBLRAHS.js} +1 -1
  37. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  38. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  39. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  40. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  41. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  42. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  43. package/dist/chunks/{chunk-BGVHA2D4.js → chunk-B3NB243Z.js} +1 -1
  44. package/dist/chunks/chunk-BKYP6AGM.js +8 -0
  45. package/dist/chunks/chunk-BVEDNESB.js +4 -0
  46. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  47. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  48. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  49. package/dist/chunks/chunk-CI2RHH74.js +50 -0
  50. package/dist/chunks/chunk-CMSOOLJB.js +4 -0
  51. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  52. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  53. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  54. package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-DK4UCK7L.js} +1 -1
  55. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  56. package/dist/chunks/chunk-FDC2GRBK.js +27 -0
  57. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  58. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  59. package/dist/chunks/chunk-G264APQN.js +5 -0
  60. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  61. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  62. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  63. package/dist/chunks/chunk-HVN37UXD.js +4 -0
  64. package/dist/chunks/chunk-IA6IODY3.js +4 -0
  65. package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-IGZWZP7Z.js} +1 -1
  66. package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-IJ7XFQMI.js} +1 -1
  67. package/dist/chunks/chunk-IMMGYDAB.js +6 -0
  68. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  69. package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-ITGCWQFK.js} +1 -1
  70. package/dist/chunks/chunk-IVZ7QUEG.js +4 -0
  71. package/dist/chunks/{chunk-YAEVYJAR.js → chunk-IWY2HIFK.js} +1 -1
  72. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  73. package/dist/chunks/{chunk-QWAQHHRS.js → chunk-JGUEIW2W.js} +1 -1
  74. package/dist/chunks/chunk-JKL3AK5D.js +106 -0
  75. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  76. package/dist/chunks/chunk-KJUQCCB5.js +4 -0
  77. package/dist/chunks/chunk-KST6OY76.js +10 -0
  78. package/dist/chunks/chunk-KZSAFVSY.js +129 -0
  79. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  80. package/dist/chunks/chunk-LE6QPXN6.js +7 -0
  81. package/dist/chunks/chunk-LEAV3FFG.js +4 -0
  82. package/dist/chunks/chunk-LIIZI3HY.js +5 -0
  83. package/dist/chunks/chunk-LP72AF56.js +45 -0
  84. package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-MJQ2D2OP.js} +1 -1
  85. package/dist/chunks/{chunk-6LZK4DDH.js → chunk-NHHR4DCF.js} +1 -1
  86. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  87. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  88. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  89. package/dist/chunks/chunk-OJ37ZWBG.js +4 -0
  90. package/dist/chunks/chunk-OZXMPBUX.js +4 -0
  91. package/dist/chunks/{chunk-3THJYAEF.js → chunk-PG7452XE.js} +1 -1
  92. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  93. package/dist/chunks/chunk-PTS3J4DQ.js +6 -0
  94. package/dist/chunks/{chunk-PXS5SHOV.js → chunk-PVVEEBUU.js} +1 -1
  95. package/dist/chunks/chunk-Q7BZLPBU.js +8 -0
  96. package/dist/chunks/{chunk-FOJQXLL2.js → chunk-QC66ZXPP.js} +1 -1
  97. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  98. package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-R2CCD4OF.js} +1 -1
  99. package/dist/chunks/chunk-R6CGBSTC.js +22 -0
  100. package/dist/chunks/chunk-RG5GP4RB.js +5 -0
  101. package/dist/chunks/{chunk-D3NXKK2L.js → chunk-RW2F2QNP.js} +1 -1
  102. package/dist/chunks/{models-L5VF4I5O-XXNJYQMQ.js → chunk-RWPO3NZ3.js} +1 -1
  103. package/dist/chunks/chunk-SAJD4EKE.js +10 -0
  104. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  105. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  106. package/dist/chunks/chunk-SKHFU5DI.js +4 -0
  107. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  108. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  109. package/dist/chunks/chunk-TKFFQNAP.js +19 -0
  110. package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
  111. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  112. package/dist/chunks/{chunk-SUFW24P4.js → chunk-UEEW2R4E.js} +1 -1
  113. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  114. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  115. package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
  116. package/dist/chunks/chunk-V7K3KNDM.js +4 -0
  117. package/dist/chunks/chunk-VHX2GHBF.js +4 -0
  118. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  119. package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
  120. package/dist/chunks/chunk-W34AK4SK.js +65 -0
  121. package/dist/chunks/{chunk-REBNWCKI.js → chunk-WU7RNAZD.js} +1 -1
  122. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  123. package/dist/chunks/chunk-WZYS2HAK.js +4 -0
  124. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  125. package/dist/chunks/{chunk-H2FP6DG4.js → chunk-X5ND4H4P.js} +1 -1
  126. package/dist/chunks/{chunk-4U7XXM4W.js → chunk-Y3AOGNDT.js} +1 -1
  127. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  128. package/dist/chunks/{chunk-KENCMLRE.js → chunk-YAEHSSR4.js} +1 -1
  129. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  130. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  131. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  132. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  133. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  134. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  135. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  136. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  137. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  138. package/dist/chunks/context-CI2FKEQE.js +4 -0
  139. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  140. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  141. package/dist/chunks/easter-egg-3d-XR5S2O3T.js +4 -0
  142. package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
  143. package/dist/chunks/{execution-repo-ZLJTBWFC.js → execution-repo-5TLV2NM4.js} +1 -1
  144. package/dist/chunks/{executions-6ARGR3IO.js → executions-I3UUIGSL.js} +1 -1
  145. package/dist/chunks/file-Y5G56IUT.js +4 -0
  146. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  147. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  148. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  149. package/dist/chunks/init-A6GY656J.js +4 -0
  150. package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-FALWKQYO.js} +1 -1
  151. package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-O5HGF6CH.js} +1 -1
  152. package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-JTVDN3BC.js} +1 -1
  153. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  154. package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  155. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  156. package/dist/chunks/{memory-cli-PYOILNN5.js → memory-cli-DIT4DQF3.js} +1 -1
  157. package/dist/chunks/meta-JQH66YU7.js +4 -0
  158. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  159. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  160. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  161. package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
  162. package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
  163. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  164. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  165. package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-JU6QQKEM.js} +1 -1
  166. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  167. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  168. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  169. package/dist/chunks/radius-THYKWV4E.js +4 -0
  170. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  171. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  172. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  173. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  174. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  175. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  176. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  177. package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
  178. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  179. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  180. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  181. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  182. package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-SRD4ILBS.js} +1 -1
  183. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  184. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  185. package/dist/chunks/waitpoint-M6JZBSLT.js +5 -0
  186. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  187. package/dist/client-bundle/client.mjs +273 -93
  188. package/dist/client-bundle/manifest.json +2 -2
  189. package/dist/core/pi-sdk.js +1 -1
  190. package/dist/domain/auth/cc-auth-cli.js +1 -1
  191. package/dist/domain/mcp/bundled-server.js +1 -1
  192. package/dist/domain/mcp/feishu/client.js +4 -0
  193. package/dist/entry/app.js +151 -559
  194. package/dist/entry/browser-cli.js +10 -10
  195. package/dist/entry/cli.js +1 -1
  196. package/dist/entry/cortex-cli.js +1 -1
  197. package/dist/entry/daemon.js +4 -4
  198. package/dist/entry/hook-cli.js +2 -2
  199. package/dist/entry/production-app-bootstrap.js +1 -1
  200. package/dist/entry/production-evidence-export-cli.js +1 -1
  201. package/dist/entry/signal-cli.js +2 -2
  202. package/dist/tui/index.js +41 -41
  203. package/package.json +3 -3
  204. package/vendor/pi/CHANGELOG.md +330 -0
  205. package/vendor/pi/dist/codemode-worker.js +2 -0
  206. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  207. package/vendor/pi/dist/core/export-html/template.css +9 -0
  208. package/vendor/pi/dist/core/export-html/template.js +166 -46
  209. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  210. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  211. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  212. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  213. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  214. package/vendor/pi/dist/utils/image-resize.js +1 -1
  215. package/vendor/pi/docs/cli.md +35 -12
  216. package/vendor/pi/docs/custom-provider.md +2 -0
  217. package/vendor/pi/docs/environment-variables.md +2 -0
  218. package/vendor/pi/docs/extensions.md +3192 -225
  219. package/vendor/pi/docs/keybindings.md +2 -2
  220. package/vendor/pi/docs/llama-cpp.md +27 -19
  221. package/vendor/pi/docs/mcp.md +6 -4
  222. package/vendor/pi/docs/message-types.md +1 -1
  223. package/vendor/pi/docs/models-configuration.md +9 -3
  224. package/vendor/pi/docs/models.md +2 -1
  225. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  226. package/vendor/pi/docs/packages.md +24 -0
  227. package/vendor/pi/docs/prompt-templates.md +1 -1
  228. package/vendor/pi/docs/providers.md +4 -2
  229. package/vendor/pi/docs/quickstart.md +7 -3
  230. package/vendor/pi/docs/rpc-commands.md +1 -1
  231. package/vendor/pi/docs/rpc.md +4 -2
  232. package/vendor/pi/docs/sessions.md +17 -3
  233. package/vendor/pi/docs/settings.md +6 -5
  234. package/vendor/pi/docs/slash-commands.md +3 -2
  235. package/vendor/pi/docs/terminal-setup.md +3 -1
  236. package/vendor/pi/docs/tmux.md +6 -0
  237. package/vendor/pi/docs/tui.md +4 -0
  238. package/vendor/pi/docs/windows.md +27 -0
  239. package/vendor/pi/examples/extensions/README.md +2 -1
  240. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  241. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  242. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  243. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  244. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  245. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  246. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  247. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  248. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  249. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  250. package/vendor/pi/examples/extensions/preset.ts +2 -0
  251. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  252. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  253. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  254. package/vendor/pi/examples/extensions/todo.ts +7 -0
  255. package/vendor/pi/examples/extensions/tools.ts +2 -0
  256. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  257. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  258. package/vendor/pi/examples/tsconfig.json +208 -0
  259. package/vendor/pi/package.json +15 -16
  260. package/vendor/pi/schemas/models.schema.json +66 -37
  261. package/vendor/pi/schemas/settings.schema.json +18 -1
  262. package/vendor/pi-ai/bedrock.js +1 -1
  263. package/vendor/pi-ai/oauth-load.js +1 -1
  264. package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-DKX6FcUS.js} +1 -1
  265. package/web/dist/assets/index-D11wi0uG.js +540 -0
  266. package/web/dist/assets/index-JedYumhY.css +1 -0
  267. package/web/dist/assets/{index-WCm6wwmM.js → index-jl30Gy8P.js} +1 -1
  268. package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
  269. package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
  270. package/web/dist/index.html +2 -2
  271. package/web/dist/theme.css +22 -0
  272. package/dist/chunks/anthropic-messages-M3SMXACA.js +0 -8
  273. package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
  274. package/dist/chunks/azure-openai-responses-76YWXHSB.js +0 -4
  275. package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
  276. package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
  277. package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
  278. package/dist/chunks/chunk-3F6WW7HR.js +0 -13
  279. package/dist/chunks/chunk-3OKHUVEM.js +0 -7
  280. package/dist/chunks/chunk-3YHOCPQU.js +0 -10
  281. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  282. package/dist/chunks/chunk-4LLH5OWM.js +0 -10
  283. package/dist/chunks/chunk-52T37Y47.js +0 -8
  284. package/dist/chunks/chunk-7MU2AKNM.js +0 -4
  285. package/dist/chunks/chunk-AAA3UBIS.js +0 -4
  286. package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
  287. package/dist/chunks/chunk-BKHDWCRT.js +0 -79
  288. package/dist/chunks/chunk-CQLH4UVX.js +0 -4
  289. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  290. package/dist/chunks/chunk-D6UA4BZC.js +0 -19
  291. package/dist/chunks/chunk-DGMNI4AO.js +0 -4
  292. package/dist/chunks/chunk-DHSA5ACV.js +0 -125
  293. package/dist/chunks/chunk-DPQPXBTP.js +0 -68
  294. package/dist/chunks/chunk-DXBSQXJL.js +0 -18
  295. package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
  296. package/dist/chunks/chunk-EQITBTJC.js +0 -10
  297. package/dist/chunks/chunk-EXJA5RIX.js +0 -357
  298. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  299. package/dist/chunks/chunk-FH74NME3.js +0 -115
  300. package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
  301. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  302. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  303. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  304. package/dist/chunks/chunk-J5DVLUKY.js +0 -6
  305. package/dist/chunks/chunk-JW2HFMTF.js +0 -4
  306. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  307. package/dist/chunks/chunk-KIGMAATV.js +0 -23
  308. package/dist/chunks/chunk-KIU5FAPY.js +0 -5
  309. package/dist/chunks/chunk-KIWMQPH7.js +0 -739
  310. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  311. package/dist/chunks/chunk-LACGULCN.js +0 -10
  312. package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
  313. package/dist/chunks/chunk-MEPASGPP.js +0 -6
  314. package/dist/chunks/chunk-MFAEUHMV.js +0 -28
  315. package/dist/chunks/chunk-NAA7GF6Q.js +0 -5
  316. package/dist/chunks/chunk-NKDMKRSB.js +0 -68
  317. package/dist/chunks/chunk-NKXV32S6.js +0 -4
  318. package/dist/chunks/chunk-NVX5IPRN.js +0 -4
  319. package/dist/chunks/chunk-O3JW2F7D.js +0 -8
  320. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  321. package/dist/chunks/chunk-OISO5JXB.js +0 -4
  322. package/dist/chunks/chunk-OPYXNSMY.js +0 -4
  323. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  324. package/dist/chunks/chunk-P52RMIYX.js +0 -6
  325. package/dist/chunks/chunk-PBJ5MPPX.js +0 -60
  326. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  327. package/dist/chunks/chunk-PZMXHA6X.js +0 -9
  328. package/dist/chunks/chunk-Q7CE3UIE.js +0 -133
  329. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  330. package/dist/chunks/chunk-QEOFEETJ.js +0 -4
  331. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  332. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  333. package/dist/chunks/chunk-REPYBMQS.js +0 -4
  334. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  335. package/dist/chunks/chunk-TAWLERZA.js +0 -4
  336. package/dist/chunks/chunk-TWAEABGG.js +0 -52
  337. package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
  338. package/dist/chunks/chunk-UD3NMUHR.js +0 -12
  339. package/dist/chunks/chunk-UNVEZI57.js +0 -4
  340. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  341. package/dist/chunks/chunk-W25TB3PU.js +0 -4
  342. package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
  343. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  344. package/dist/chunks/chunk-XAJLZR7C.js +0 -28
  345. package/dist/chunks/chunk-XH6FMP3N.js +0 -71
  346. package/dist/chunks/chunk-XSRZHN63.js +0 -4
  347. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  348. package/dist/chunks/chunk-YG7OEPR2.js +0 -6
  349. package/dist/chunks/chunk-YHIWOGVL.js +0 -4
  350. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  351. package/dist/chunks/chunk-YZSHTWNM.js +0 -92
  352. package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
  353. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  354. package/dist/chunks/client-XOGYH5UR.js +0 -4
  355. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  356. package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
  357. package/dist/chunks/context-VCQH5OB6.js +0 -4
  358. package/dist/chunks/cost-PGGFI7QJ.js +0 -5
  359. package/dist/chunks/dist-PUKMZ7GW.js +0 -4
  360. package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
  361. package/dist/chunks/es5-VNTQPCKX.js +0 -4
  362. package/dist/chunks/file-7BN7RCAY.js +0 -4
  363. package/dist/chunks/gateway-UCRPMR75.js +0 -36
  364. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  365. package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
  366. package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
  367. package/dist/chunks/init-HA7FAQ73.js +0 -4
  368. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  369. package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
  370. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  371. package/dist/chunks/mistral-conversations-34F66L3O.js +0 -7
  372. package/dist/chunks/model-resolver-N3DTAQ2S.js +0 -4
  373. package/dist/chunks/openai-codex-responses-ZBVHREB3.js +0 -12
  374. package/dist/chunks/openai-completions-VVIB26SH.js +0 -9
  375. package/dist/chunks/openai-responses-735XA2ZX.js +0 -6
  376. package/dist/chunks/openrouter-images-3IKETHAC.js +0 -4
  377. package/dist/chunks/pi-messages-I3E4ZFHA.js +0 -10
  378. package/dist/chunks/radius-HXRZVBDB.js +0 -4
  379. package/dist/chunks/remote-ops-BALZYKH6.js +0 -14
  380. package/dist/chunks/runner-PLVZDGHB.js +0 -4
  381. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  382. package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
  383. package/dist/chunks/slack-WAGSPZUX.js +0 -4
  384. package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
  385. package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
  386. package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
  387. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  388. package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
  389. package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
  390. package/dist/chunks/ui-view-O7PLANT7.js +0 -4
  391. package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
  392. package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
  393. package/dist/chunks/workers-XN4PSTH6.js +0 -4
  394. package/vendor/aistatus/gateway-cli.js +0 -21
  395. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  396. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  397. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  398. package/web/dist/assets/index-BHZpFXhc.js +0 -525
  399. package/web/dist/assets/index-DqWMdMkh.css +0 -1
  400. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
  401. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
@@ -0,0 +1,132 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a as hc,b as uc,c as dc,d as fc,e as pc,f as gc,g as mc,h as xc,i as bc,j as yc,k as wc,l as kc,m as Sc,n as Cc,o as Tc,p as vc,q as Mc,r as Ic,s as Rc,t as Ac,u as Lc,v as Ec}from"./chunk-ZQ7LGTSN.js";import{a as st}from"./chunk-3TGQSGG4.js";import{T as Ls,q as As,z as ji}from"./chunk-2BVUA256.js";import{d as cc,e as V}from"./chunk-WHC7AYZD.js";var bn=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],yn=12288,wn=65510,kn=[12288,12288,65281,65376,65504,65510];var Sn=4352,Cn=262141,Gi=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var Es=(s,e)=>{let t=0,i=Math.floor(s.length/2)-1;for(;t<=i;){let r=Math.floor((t+i)/2),n=r*2;if(e<s[n])i=r-1;else if(e>s[n+1])t=r+1;else return!0}return!1};var Tn=19968,[_c,Oc]=Bc(Gi);function Bc(s){let e=s[0],t=s[1];for(let i=0;i<s.length;i+=2){let r=s[i],n=s[i+1];if(Tn>=r&&Tn<=n)return[r,n];n-r>t-e&&(e=r,t=n)}return[e,t]}var vn=s=>s<161||s>1114109?!1:Es(bn,s),Mn=s=>s<yn||s>wn?!1:Es(kn,s);var In=s=>s>=_c&&s<=Oc?!0:s<Sn||s>Cn?!1:Es(Gi,s);function Dc(s){if(!Number.isSafeInteger(s))throw new TypeError(`Expected a code point, got \`${typeof s}\`.`)}function Yi(s,{ambiguousAsWide:e=!1}={}){return Dc(s),Mn(s)||In(s)||e&&vn(s)?2:1}var re=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Nc=new Intl.Segmenter(void 0,{granularity:"word"});function rt(){return re}function nt(){return Nc}function Wc(s){let e=s.codePointAt(0);return e>=126976&&e<=130047||e>=8960&&e<=9215||e>=9728&&e<=10175||e>=11088&&e<=11093||s.includes("\uFE0F")||s.length>2}var Fc=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),Hc=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),Kc=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$","v"),Vc=new RegExp("^\\p{Mark}$","v"),Rn=new RegExp("^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$","v"),qc=new RegExp("^\\p{RGI_Emoji}$","v"),Uc=512,Xt=new Map,ot=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,Zi=new RegExp(`(?:(?=\\p{Punctuation})${ot.source}|[\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\uFF3B\uFF3D\uFF5B\uFF5D\u201C\u201D\u2018\u2019\u2026\u2014])`,"u"),lt=new RegExp(`(?:\\s|${Zi.source})`,"u"),$s=new RegExp(`(?:^|${lt.source})`,"u");function Zt(s){for(let e=0;e<s.length;e++){let t=s.charCodeAt(e);if(t<32||t>126)return!1}return!0}function zc(s,e){if(e<=0||s.length===0)return{text:"",width:0};if(Zt(s)){let a=s.slice(0,e);return{text:a,width:a.length}}let t=s.includes("\x1B"),i=s.includes(" ");if(!t&&!i){let a="",c=0;for(let{segment:h}of re.segment(s)){let u=we(h);if(c+u>e)break;a+=h,c+=u}return{text:a,width:c}}let r="",n=0,o=0,l="";for(;o<s.length;){let a=K(s,o);if(a){l+=a.code,o+=a.length;continue}if(s[o]===" "){if(n+3>e)break;l&&(r+=l,l=""),r+=" ",n+=3,o++;continue}let c=o;for(;c<s.length&&s[c]!==" "&&!K(s,c);)c++;for(let{segment:h}of re.segment(s.slice(o,c))){let u=we(h);if(n+u>e)return{text:r,width:n};l&&(r+=l,l=""),r+=h,n+=u}o=c}return{text:r,width:n}}function Qi(s,e,t,i,r,n){let o="\x1B[0m",l=sh(s),a=e+i,c;return t.length>0?c=`${s}${l}${o}${t}${o}`:c=`${s}${l}${o}`,n?c+" ".repeat(Math.max(0,r-a)):c}function Pn(s){return s>=32&&s<=126?!0:s>=160&&s<=767?s!==173:s>=8208&&s<=11263?!(s>=8232&&s<=8238)&&!(s>=8288&&s<=8303)&&!(s>=8400&&s<=8447):s>=12352&&s<=12438||s>=12448&&s<=12543||s>=19968&&s<=40959||s>=65281&&s<=65376}function jc(s){for(let e=0;e<s.length;e++)if(!Pn(s.charCodeAt(e)))return!1;return!0}function*Gc(s){let e=i=>i<0||i>=s.length||Pn(s.charCodeAt(i)),t=-1;for(let i=0;i<s.length;i++)if(e(i)&&e(i-1)&&e(i+1)){if(t>=0){for(let{segment:r}of re.segment(s.slice(t,i)))yield r;t=-1}yield s[i]}else t<0&&(t=i);if(t>=0)for(let{segment:i}of re.segment(s.slice(t)))yield i}function $n(s){return jc(s)?s:Gc(s)}var An=new Map;function we(s){if(s.length!==1)return Ln(s);let e=s.charCodeAt(0);if(e>=32&&e<=126)return 1;if(e===9)return 3;let t=An.get(e);return t===void 0&&(t=Ln(s),An.set(e,t)),t}function Ln(s){if(Rn.test(s))return[...s].length;if(Fc.test(s))return 0;if(Wc(s)&&qc.test(s))return 2;let e=s.replace(Hc,""),t=e.codePointAt(0);if(t===void 0)return 0;if(t>=127462&&t<=127487)return 2;let i=Yi(t),r=!1,n=[...e];for(let o of n.slice(1))if(Rn.test(o))i+=1,r=!1;else if(Vc.test(o))r=!0;else if(!Kc.test(o)){let l=o.codePointAt(0);r||l>=65280&&l<=65519?i+=Yi(l):(l===3635||l===3763)&&(i+=1),r=!1}return i}function S(s){if(s.length===0)return 0;let e=eh(s);if(e!==-1)return e;let t=Xt.get(s);if(t!==void 0)return t;let i=s;s.includes(" ")&&(i=i.replace(/\t/g," "));let r=i.indexOf("\x1B");if(r!==-1){let o="",l=0;for(;r!==-1;){let a=Oe(i,r);a>0?(o+=i.slice(l,r),r+=a,l=r):r++,r=i.indexOf("\x1B",r)}i=o+i.slice(l)}let n=0;for(let{segment:o}of re.segment(i))n+=we(o);if(Xt.size>=Uc){let o=Xt.keys().next().value;o!==void 0&&Xt.delete(o)}return Xt.set(s,n),n}function _e(s){if(!s.includes("\x1B"))return s;let e="",t=0;for(;t<s.length;){let i=K(s,t);if(i){t+=i.length;continue}e+=s[t],t++}return e}function En(s){let e="",t=s.indexOf("\x1B");for(;t!==-1;){let i=Oe(s,t);i>0?(e+=s.substring(t,t+i),t+=i):t++,t=s.indexOf("\x1B",t)}return e}var Yc=/\s/;function Qc(s){let e=0;for(;e<s.length;){let t=s.charCodeAt(e);if(t===27){let i=Oe(s,e);if(i===0)return!1;e+=i}else if(t===32||t>=9&&t<=13)e++;else{if(t<128||!Yc.test(s[e]))return!1;e++}}return!0}var Xc=/[\u0000-\u001f\u007f-\u009f]+/g;function at(s){return s.replace(Xc," ")}function Jt(s,e){let t=0,i=0;for(;i<s.length;){let r=K(s,i);if(r){i+=r.length;continue}let n=i;for(;n<s.length&&!K(s,n);)n++;let o=s.slice(i,n);if(Zt(o)){if(e>=t&&e<t+o.length)return{start:e,end:e+1};t+=o.length,i=n;continue}for(let l of $n(o)){let a=we(l);if(a>0&&e>=t&&e<t+a)return{start:t,end:t+a};t+=a}i=n}}function _s(s,e){let t,i=0,r=0;for(;r<s.length;){let n=K(s,r);if(n){let l=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(n.code);l&&(t=l[1]||void 0),r+=n.length;continue}let o=r;for(;o<s.length&&!K(s,o);)o++;for(let{segment:l}of re.segment(s.slice(r,o))){let a=l===" "?3:we(l);if(e>=i&&e<i+a)return t;i+=a}r=o}}var Zc=/[\u0e33\u0eb3]/,Jc=/[\u0e33\u0eb3]/g;function _n(s){let e=s;if(Zc.test(e)&&(e=e.replace(Jc,r=>r==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2")),!e.includes(" "))return e;let t="",i=0;for(;i<e.length;){let r=K(e,i);if(r){t+=r.code,i+=r.length;continue}t+=e[i]===" "?" ":e[i],i++}return t}function K(s,e){let t=Oe(s,e);return t>0?{code:s.substring(e,e+t),length:t}:null}function eh(s){let e=0,t=0;for(;t<s.length;){let i=s.charCodeAt(t);if(i>=32&&i<=126)e++,t++;else if(i===9)e+=3,t++;else if(i===27){let r=Oe(s,t);if(r===0)return-1;t+=r}else return-1}return e}function Oe(s,e){if(e>=s.length||s.charCodeAt(e)!==27)return 0;let t=s[e+1];if(t==="["){for(let i=e+2;i<s.length;i++){let r=s.charCodeAt(i);if(r===109||r===71||r===75||r===72||r===74)return i+1-e}return 0}if(t==="]"||t==="_"){for(let i=e+2;i<s.length;i++){let r=s.charCodeAt(i);if(r===7)return i+1-e;if(r===27&&s[i+1]==="\\")return i+2-e}return 0}return 0}function On(s){if(!s.startsWith("\x1B]8;"))return;let e=s.endsWith("\x07")?"\x07":"\x1B\\",t=s.slice(4,e==="\x07"?-1:-2),i=t.indexOf(";");if(i===-1)return;let r=t.slice(0,i),n=t.slice(i+1);return n?{params:r,url:n,terminator:e}:null}function th(s){return`\x1B]8;${s.params};${s.url}${s.terminator}`}function Bn(s){return`\x1B]8;;${s}`}function sh(s){if(!s.includes("\x1B]8;"))return"";let e=null,t=0;for(;t<s.length;){let i=K(s,t);if(i){let r=On(i.code);r!==void 0&&(e=r),t+=i.length}else t++}return e?Bn(e.terminator):""}var it=class{bold=!1;dim=!1;italic=!1;underline=!1;blink=!1;inverse=!1;hidden=!1;strikethrough=!1;fgColor=null;bgColor=null;activeHyperlink=null;process(e){let t=On(e);if(t!==void 0){this.activeHyperlink=t;return}if(!e.endsWith("m"))return;let i=e.match(/\x1b\[([\d;]*)m/);if(!i)return;let r=i[1];if(r===""||r==="0"){this.reset();return}let n=r.split(";"),o=0;for(;o<n.length;){let l=Number.parseInt(n[o],10);if(l===38||l===48){if(n[o+1]==="5"&&n[o+2]!==void 0){let a=`${n[o]};${n[o+1]};${n[o+2]}`;l===38?this.fgColor=a:this.bgColor=a,o+=3;continue}else if(n[o+1]==="2"&&n[o+4]!==void 0){let a=`${n[o]};${n[o+1]};${n[o+2]};${n[o+3]};${n[o+4]}`;l===38?this.fgColor=a:this.bgColor=a,o+=5;continue}}switch(l){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:l>=30&&l<=37||l>=90&&l<=97?this.fgColor=String(l):(l>=40&&l<=47||l>=100&&l<=107)&&(this.bgColor=String(l));break}o++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let e=[];this.bold&&e.push("1"),this.dim&&e.push("2"),this.italic&&e.push("3"),this.underline&&e.push("4"),this.blink&&e.push("5"),this.inverse&&e.push("7"),this.hidden&&e.push("8"),this.strikethrough&&e.push("9"),this.fgColor&&e.push(this.fgColor),this.bgColor&&e.push(this.bgColor);let t=e.length>0?`\x1B[${e.join(";")}m`:"";return this.activeHyperlink&&(t+=th(this.activeHyperlink)),t}getActiveBackgroundCode(){return this.bgColor?`\x1B[${this.bgColor}m`:""}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let e="";return this.underline&&(e+="\x1B[24m"),this.strikethrough&&(e+="\x1B[29m"),this.activeHyperlink&&(e+=Bn(this.activeHyperlink.terminator)),e}};function Ps(s,e){let t=s.indexOf("\x1B");for(;t!==-1;){let i=Oe(s,t);i>0?(e.process(s.substring(t,t+i)),t+=i):t++,t=s.indexOf("\x1B",t)}}function Dn(s){let e=new it;return Ps(s,e),e.getActiveBackgroundCode()}function*ih(s){for(let{segment:e}of re.segment(s))yield e}function rh(s){let e=[],t="",i="",r=null,n=0,o=()=>{t&&(e.push(t),t="",r=null)};for(;n<s.length;){let l=K(s,n);if(l){i+=l.code,n+=l.length;continue}let a=s.indexOf("\x1B",n+1);for(;a!==-1&&Oe(s,a)===0;)a=s.indexOf("\x1B",a+1);a===-1&&(a=s.length);let c=s.slice(n,a),h=Zt(c);for(let u of h?c:ih(c)){let d=u===" ";if(!h&&!d&&ot.test(u)){o();let p=i+u;i="",e.push(p);continue}let f=d?"space":"word";t&&r!==f&&o(),i&&(t+=i,i=""),r=f,t+=u}n=a}return i&&(t?t+=i:e.length>0?e[e.length-1]+=i:t=i),t&&e.push(t),e}function Be(s){for(let e of s)Number(e)}function ne(s,e){if(!s)return[""];let t=s.split(/\r\n|\r|\n/),i=[],r=new it;for(let n of t){let o=i.length>0?r.getActiveCodes():"",l=nh(o+n,e);for(let a of l)i.push(a);Ps(n,r)}return i.length>0?i:[""]}function nh(s,e){if(!s)return[""];if(S(s)<=e)return[s];let i=[],r=new it,n=rh(s),o="",l=0;for(let a of n){let c=S(a),h=Qc(a);if(c>e&&!h){if(o){o=o.trimEnd();let f=r.getLineEndReset();f&&(o+=f),i.push(o),o="",l=0}let d=oh(a,e,r);for(let f=0;f<d.length-1;f++)i.push(d[f]);o=d[d.length-1],l=S(o);continue}let u=l+c;if(u>e&&l>0){let d=o.trimEnd();h&&(d+=En(a),Ps(a,r));let f=r.getLineEndReset();if(f&&(d+=f),i.push(d),h){o=r.getActiveCodes(),l=0;continue}o=r.getActiveCodes()+a,l=c}else h&&u>e&&a.includes("\x1B")?o+=En(a):(o+=a,l+=c);Ps(a,r)}return o&&i.push(o),i.length>0?i.map(a=>a.trimEnd()):[""]}var Ji=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function ee(s){return/\s/.test(s)}function oh(s,e,t){let i=[],r=t.getActiveCodes(),n=0,o=0,l=[];for(;o<s.length;){let a=K(s,o);if(a)l.push({type:"ansi",value:a.code}),o+=a.length;else{let c=o;for(;c<s.length&&!K(s,c);)c++;let h=s.slice(o,c);for(let u of re.segment(h))l.push({type:"grapheme",value:u.segment});o=c}}for(let a of l){if(a.type==="ansi"){r+=a.value,t.process(a.value);continue}let c=a.value;if(!c)continue;let h=S(c);if(n+h>e){let u=t.getLineEndReset();u&&(r+=u),i.push(r),r=t.getActiveCodes(),n=0}r+=c,n+=h}return r&&i.push(r),i.length>0?i:[""]}function ct(s,e,t){let i=S(s),r=Math.max(0,e-i),n=" ".repeat(r),o=s+n;return t(o)}function D(s,e,t="...",i=!1){if(e<=0)return"";if(s.length===0)return i?" ".repeat(e):"";let r=S(t);if(r>=e){let g=S(s);if(g<=e)return i?s+" ".repeat(e-g):s;let x=zc(t,e);return x.width===0?i?" ".repeat(e):"":Qi("",0,x.text,x.width,e,i)}if(Zt(s)){if(s.length<=e)return i?s+" ".repeat(e-s.length):s;let g=e-r;return Qi(s.slice(0,g),g,t,r,e,i)}let n=e-r,o="",l="",a=0,c=0,h=!0,u=!1,d=!1,f=s.includes("\x1B"),p=s.includes(" ");if(!f&&!p){for(let{segment:g}of re.segment(s)){let x=we(g);if(h&&c+x<=n?(o+=g,c+=x):h=!1,a+=x,a>e){u=!0;break}}d=!u}else{let g=0;for(;g<s.length;){let x=K(s,g);if(x){l+=x.code,g+=x.length;continue}if(s[g]===" "){if(h&&c+3<=n?(l&&(o+=l,l=""),o+=" ",c+=3):(h=!1,l=""),a+=3,a>e){u=!0;break}g++;continue}let m=g;for(;m<s.length&&s[m]!==" "&&!K(s,m);)m++;for(let{segment:w}of re.segment(s.slice(g,m))){let b=we(w);if(h&&c+b<=n?(l&&(o+=l,l=""),o+=w,c+=b):(h=!1,l=""),a+=b,a>e){u=!0;break}}if(u)break;g=m}d=g>=s.length}return!u&&d?i?s+" ".repeat(Math.max(0,e-a)):s:Qi(o,c,t,r,e,i)}function H(s,e,t,i=!1){return er(s,e,t,i).text}function er(s,e,t,i=!1){if(t<=0)return{text:"",width:0};let r=e+t,n="",o=0,l=0,a=0,c="";for(;a<s.length;){let h=K(s,a);if(h){l>=e&&l<r?(n+=c+h.code,c=""):l<e&&!h.code.startsWith("\x1B_")&&(c+=h.code),a+=h.length;continue}let u=a;for(;u<s.length&&!K(s,u);)u++;let d=s.slice(a,u);if(Zt(d)){let f=Math.max(0,e-l),p=Math.min(d.length,r-l);if(p>f&&(n+=c+d.slice(f,p),c="",o+=p-f),l+=d.length,a=u,l>=r)break;continue}for(let f of $n(d)){let p=we(f),g=l>=e&&l<r,x=!i||l+p<=r;if(g&&x&&(c&&(n+=c,c=""),n+=f,o+=p),l+=p,l>=r)break}if(a=u,l>=r)break}return{text:n,width:o}}var Xi=new it;function Nn(s,e,t,i,r=!1){let n="",o=0,l="",a=0,c=0,h=0,u="",d=!1,f=t+i;for(Xi.clear();h<s.length;){let p=K(s,h);if(p){Xi.process(p.code),c<e?u+=p.code:c>=t&&c<f&&(d||p.code.startsWith("\x1B_"))&&(l+=p.code),h+=p.length;continue}let g=h;for(;g<s.length&&!K(s,g);)g++;for(let{segment:x}of re.segment(s.slice(h,g))){let m=we(x);if(c<e&&c+m<=e?(u&&(n+=u,u=""),n+=x,o+=m):c>=t&&c<f&&(!r||c+m<=f)&&(d||(l+=Xi.getActiveCodes(),d=!0),l+=x,a+=m),c+=m,i<=0?c>=e:c>=f)break}if(h=g,i<=0?c>=e:c>=f)break}return{before:n,beforeWidth:o,after:l,afterWidth:a}}var Ds=(s,[e,t,i])=>s.map(r=>r[0]*e+r[1]*t+r[2]*i),lh=[[.4122214694707629,.5363325372617349,.0514459932675022],[.2119034958178251,.6806995506452344,.1073969535369405],[.0883024591900564,.2817188391361215,.6299787016738222]],ah=[[.210454268309314,.793617774702305,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],Os=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],tr=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-.341319376002657],[-.0041960761386756,-.7034186179359362,1.7076146940746117]],Wn=[[[-1.8817031,-.80936501],[1.19086277,1.76576728,.59662641,.75515197,.56771245]],[[1.8144408,-1.19445267],[.73956515,-.45954404,.08285427,.12541073,-.14503204]],[[.13110758,1.81333971],[1.35733652,-.00915799,-1.1513021,-.50559606,.00692167]]],Ns=.206,sr=.03,Bs=(1+Ns)/(1+sr),ht=s=>.5*(Bs*s-Ns+Math.sqrt((Bs*s-Ns)**2+4*sr*Bs*s)),ch=s=>(s*s+Ns*s)/(Bs*(s+sr)),hh=s=>s>.0031308?1.055*s**(1/2.4)-.055:12.92*s,uh=s=>s<=.04045?s/12.92:((s+.055)/1.055)**2.4;function Ws(s){return Ds(tr,Ds(Os,s).map(e=>e**3))}function dh(s){return Ds(ah,Ds(lh,s).map(Math.cbrt))}function ir({r:s,g:e,b:t}){return dh([s/255,e/255,t/255].map(uh))}function Fs(s){let[e,t,i]=s.map(r=>Math.round(Math.min(1,Math.max(0,hh(r)))*255));return{r:e,g:t,b:i}}function Fn(s,e){return[Os[0],Os[1],Os[2]].map(t=>t[1]*s+t[2]*e)}function fh(s,e){let t=Wn.findIndex(([[x,m]],w)=>w===2||x*s+m*e>1),[i,r,n,o,l]=Wn[t][1],a=tr[t],c=i+r*s+n*e+o*s*s+l*s*e,h=Fn(s,e),u=h.map(x=>1+c*x),d=x=>x.reduce((m,w,b)=>m+a[b]*w,0),f=d(u.map(x=>x**3)),p=d(u.map((x,m)=>3*h[m]*x**2)),g=d(u.map((x,m)=>6*h[m]**2*x));return c-f*p/(p*p-.5*f*g)}function ph(s,e){let t=fh(s,e),i=Math.cbrt(1/Math.max(...Ws([1,t*s,t*e])));return[i,i*t]}function gh(s,e,t,[i,r]){if(t<=i)return r*t/i;let n=r*(t-1)/(i-1),o=Fn(s,e),l=o.map(f=>t+n*f),a=l.map(f=>f**3),c=l.map((f,p)=>3*o[p]*f**2),h=l.map((f,p)=>6*o[p]**2*f),u=(f,p)=>f[0]*p[0]+f[1]*p[1]+f[2]*p[2],d=tr.map(f=>{let p=u(f,a)-1,g=u(f,c),x=u(f,h),m=g/(g*g-.5*p*x);return m>=0?-p*m:Number.MAX_VALUE});return n+Math.min(...d)}function Hn(s,e,t){let i=ph(e,t),r=gh(e,t,s,i),n=r/Math.min(s*(i[1]/i[0]),(1-s)*(i[1]/(1-i[0]))),o=.11516993+1/(7.4477897+4.1590124*t+e*(-2.19557347+1.75198401*t+e*(-2.13704948-10.02301043*t+e*(-4.24894561+5.38770819*t+4.69891013*e)))),l=.11239642+1/(1.6132032-.68124379*t+e*(.40370612+.90148123*t+e*(-.27087943+.6122399*t+e*(.00299215-.45399568*t-.14661872*e)))),a=.9*n*Math.sqrt(Math.sqrt(1/(1/(s*o)**4+1/((1-s)*l)**4)));return[Math.sqrt(1/(1/(s*.4)**2+1/((1-s)*.8)**2)),a,r]}function Kn(s,e,t){let i=ch(t),r=[i,0,0];if(i>0&&i<1&&e>0){let n=2*Math.PI*((s%360+360)%360)/360,o=Math.cos(n),l=Math.sin(n),[a,c,h]=Hn(i,o,l),u;if(e<.8){let d=1.25*e,f=.8*a;u=d*f/(1-(1-f/c)*d)}else{let d=5*(e-.8),f=.2*c**2*1.25**2/a;u=c+d*f/(1-(1-f/(h-c))*d)}r=[i,u*o,u*l]}return Fs(Ws(r))}function Vn(s){let[e,t,i]=ir(s),r=Math.hypot(t,i),n=ht(e);if(r<1e-9||n<=0||n>=1)return{h:0,s:0,l:n};let o=(Math.atan2(i,t)*180/Math.PI+360)%360,[l,a,c]=Hn(e,t/r,i/r),h;if(r<a){let u=.8*l;h=.8*(r/(u+(1-u/a)*r))}else{let u=.2*a**2*1.5625/l,d=r-a;h=.8+.2*(d/(u+(1-u/(c-a))*d))}return{h:o,s:Math.min(1,Math.max(0,h)),l:n}}function Re(s,e){if(!Number.isFinite(s))throw new Error(`${e} must be finite`)}function es(s){if(!Number.isInteger(s)||s<0||s>255)throw new Error(`ANSI color index must be an integer from 0 to 255: ${s}`);return Object.freeze({kind:"indexed",index:s})}function he(s,e,t){for(let[i,r]of[["r",s],["g",e],["b",t]])if(Re(r,i),r<0||r>255)throw new Error(`${i} must be between 0 and 255: ${r}`);return Object.freeze({kind:"rgb",r:s,g:e,b:t})}function dt(s,e,t){if(Re(s,"l"),Re(e,"c"),Re(t,"h"),s<0||s>1)throw new Error(`l must be between 0 and 1: ${s}`);if(e<0)throw new Error(`c must not be negative: ${e}`);return Object.freeze({kind:"oklch",l:s,c:e,h:(t%360+360)%360})}var ut=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,mh=new RegExp(`^oklch\\(\\s*(${ut})(%)?\\s+(${ut})\\s+(${ut})(?:deg)?\\s*\\)$`,"i"),xh=new RegExp(`^okhsl\\(\\s*(${ut})(?:deg)?\\s+(${ut})(%)?\\s+(${ut})(%)?\\s*\\)$`,"i");function De(s,e,t){if(Re(s,"h"),Re(e,"s"),Re(t,"l"),e<0||e>1)throw new Error(`s must be between 0 and 1: ${e}`);if(t<0||t>1)throw new Error(`l must be between 0 and 1: ${t}`);let{r:i,g:r,b:n}=Kn(s,e,t);return he(i,r,n)}function Ks(s){return Vn(me(s))}function Se(s){if(typeof s=="number")return es(s);let e=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(s);if(e){let r=e[1].length===3?[...e[1]].map(n=>n+n).join(""):e[1];return he(Number.parseInt(r.slice(0,2),16),Number.parseInt(r.slice(2,4),16),Number.parseInt(r.slice(4,6),16))}let t=mh.exec(s);if(t){let r=Number.parseFloat(t[1])/(t[2]?100:1);return dt(r,Number.parseFloat(t[3]),Number.parseFloat(t[4]))}let i=xh.exec(s);if(i){let r=Number.parseFloat(i[2])/(i[3]?100:1),n=Number.parseFloat(i[4])/(i[5]?100:1);return De(Number.parseFloat(i[1]),r,n)}throw new Error(`Invalid color value: ${s}`)}var bh=[{r:0,g:0,b:0},{r:128,g:0,b:0},{r:0,g:128,b:0},{r:128,g:128,b:0},{r:0,g:0,b:128},{r:128,g:0,b:128},{r:0,g:128,b:128},{r:192,g:192,b:192},{r:128,g:128,b:128},{r:255,g:0,b:0},{r:0,g:255,b:0},{r:255,g:255,b:0},{r:0,g:0,b:255},{r:255,g:0,b:255},{r:0,g:255,b:255},{r:255,g:255,b:255}],ke=[0,95,135,175,215,255],qn=Array.from({length:24},(s,e)=>8+e*10);function yh(s){if(s<16)return{...bh[s]};if(s<232){let t=s-16;return{r:ke[Math.floor(t/36)],g:ke[Math.floor(t%36/6)],b:ke[t%6]}}let e=8+(s-232)*10;return{r:e,g:e,b:e}}function Un(s){return s.every(t=>t>=-1e-7&&t<=1+1e-7)}function wh({l:s,c:e,h:t}){let i=t*Math.PI/180,r=Math.cos(i),n=Math.sin(i),o=u=>Ws([s,u*r,u*n]),l=o(e);if(Un(l))return Fs(l);let a=o(0),c=0,h=e;for(let u=0;u<20;u++){let d=(c+h)/2,f=o(d);Un(f)?(c=d,a=f):h=d}return Fs(a)}function me(s){switch(s.kind){case"indexed":return yh(s.index);case"rgb":return{r:s.r,g:s.g,b:s.b};case"oklch":return wh(s)}}function xe(s){if(s.kind==="oklch")return{l:s.l,c:s.c,h:s.h};let[e,t,i]=ir(me(s));return{l:e,c:Math.hypot(t,i),h:(Math.atan2(i,t)*180/Math.PI+360)%360}}function ft(s){let{r:e,g:t,b:i}=me(s),r=n=>Math.round(n).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(i)}`}function Vs(s,e,t,i="oklch"){if(Re(t,"amount"),t<0||t>1)throw new Error(`amount must be between 0 and 1: ${t}`);if(i==="srgb"){let c=me(s),h=me(e);return he(c.r+(h.r-c.r)*t,c.g+(h.g-c.g)*t,c.b+(h.b-c.b)*t)}let r=xe(s),n=xe(e),o=r.c<1e-7?n.h:r.h,a=((n.c<1e-7?o:n.h)-o+540)%360-180;return dt(r.l+(n.l-r.l)*t,r.c+(n.c-r.c)*t,o+a*t)}function Hs(s,e){let t=0,i=1/0;for(let r=0;r<s.length;r++){let n=Math.abs(e-s[r]);n<i&&(t=r,i=n)}return t}function zn(s,e){let t=s.r-e.r,i=s.g-e.g,r=s.b-e.b;return t*t*.299+i*i*.587+r*r*.114}function kh(s){let e=Hs(ke,s.r),t=Hs(ke,s.g),i=Hs(ke,s.b),r={r:ke[e],g:ke[t],b:ke[i]},n=16+36*e+6*t+i,o=Math.round(.299*s.r+.587*s.g+.114*s.b),l=Hs(qn,o),a=qn[l];return Math.max(s.r,s.g,s.b)-Math.min(s.r,s.g,s.b)<10&&zn(s,{r:a,g:a,b:a})<zn(s,r)?232+l:n}function jn(s,e,t){if(s.kind==="indexed")return`\x1B[${t?48:38};5;${s.index}m`;let i=me(s);return e==="truecolor"?`\x1B[${t?48:38};2;${Math.round(i.r)};${Math.round(i.g)};${Math.round(i.b)}m`:`\x1B[${t?48:38};5;${kh(i)}m`}function pt(s,e){return jn(s,e,!1)}function gt(s,e){return jn(s,e,!0)}function Gn(s,e,t){return ts(s,e.fg&&pt(e.fg,t),e.bg&&gt(e.bg,t),e)}function ts(s,e,t,i){let r="",n="";return e&&(r+=e,n="\x1B[39m"),t&&(r+=t,n=`\x1B[49m${n}`),i.bold&&(r+="\x1B[1m"),i.dim&&(r+="\x1B[2m"),(i.bold||i.dim)&&(n=`\x1B[22m${n}`),i.italic&&(r+="\x1B[3m",n=`\x1B[23m${n}`),i.underline&&(r+="\x1B[4m",n=`\x1B[24m${n}`),i.inverse&&(r+="\x1B[7m",n=`\x1B[27m${n}`),i.strikethrough&&(r+="\x1B[9m",n=`\x1B[29m${n}`),`${r}${s}${n}`}var z=!1;function xt(s){z=s}function Zn(){return z}var Jn={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:s=>`ctrl+${s}`,shift:s=>`shift+${s}`,alt:s=>`alt+${s}`,super:s=>`super+${s}`,ctrlShift:s=>`ctrl+shift+${s}`,shiftCtrl:s=>`shift+ctrl+${s}`,ctrlAlt:s=>`ctrl+alt+${s}`,altCtrl:s=>`alt+ctrl+${s}`,shiftAlt:s=>`shift+alt+${s}`,altShift:s=>`alt+shift+${s}`,ctrlSuper:s=>`ctrl+super+${s}`,superCtrl:s=>`super+ctrl+${s}`,shiftSuper:s=>`shift+super+${s}`,superShift:s=>`super+shift+${s}`,altSuper:s=>`alt+super+${s}`,superAlt:s=>`super+alt+${s}`,ctrlShiftAlt:s=>`ctrl+shift+alt+${s}`,ctrlShiftSuper:s=>`ctrl+shift+super+${s}`},Ae=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),eo=new Set("~!@#$%^&*()_+|{}:<>?"),Sh=["shift","alt","ctrl","super"],R={shift:1,alt:2,ctrl:4,super:8},Ne=192,_={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},q={up:-1,down:-2,right:-3,left:-4},L={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15,f1:-21,f2:-22,f3:-23,f4:-24,f5:-25,f6:-26,f7:-27,f8:-28,f9:-29,f10:-30,f11:-31,f12:-32},Ch=57344,Th=63743,vh=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,q.left],[57418,q.right],[57419,q.up],[57420,q.down],[57421,L.pageUp],[57422,L.pageDown],[57423,L.home],[57424,L.end],[57425,L.insert],[57426,L.delete]]);function mt(s){return vh.get(s)??s}function ns(s,e){return(e&~Ne&R.shift)!==0&&s>=65&&s<=90?s+32:s}function qs(s,e,t){if(s===void 0||(e&R.shift)===0)return;let i=mt(s);if(t.has(String.fromCharCode(i)))return{codepoint:i,modifier:e&~R.shift}}var oe={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},Mh={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},Ih={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]},Rh={"\x1BOA":"up","\x1BOB":"down","\x1BOC":"right","\x1BOD":"left","\x1BOH":"home","\x1BOF":"end","\x1B[E":"clear","\x1BOE":"clear","\x1BOe":"ctrl+clear","\x1B[e":"shift+clear","\x1B[2~":"insert","\x1B[2$":"shift+insert","\x1B[2^":"ctrl+insert","\x1B[3$":"shift+delete","\x1B[3^":"ctrl+delete","\x1B[[5~":"pageUp","\x1B[[6~":"pageDown","\x1B[a":"shift+up","\x1B[b":"shift+down","\x1B[c":"shift+right","\x1B[d":"shift+left","\x1BOa":"ctrl+up","\x1BOb":"ctrl+down","\x1BOc":"ctrl+right","\x1BOd":"ctrl+left","\x1B[5$":"shift+pageUp","\x1B[6$":"shift+pageDown","\x1B[7$":"shift+home","\x1B[8$":"shift+end","\x1B[5^":"ctrl+pageUp","\x1B[6^":"ctrl+pageDown","\x1B[7^":"ctrl+home","\x1B[8^":"ctrl+end","\x1BOP":"f1","\x1BOQ":"f2","\x1BOR":"f3","\x1BOS":"f4","\x1B[11~":"f1","\x1B[12~":"f2","\x1B[13~":"f3","\x1B[14~":"f4","\x1B[[A":"f1","\x1B[[B":"f2","\x1B[[C":"f3","\x1B[[D":"f4","\x1B[[E":"f5","\x1B[15~":"f5","\x1B[17~":"f6","\x1B[18~":"f7","\x1B[19~":"f8","\x1B[20~":"f9","\x1B[21~":"f10","\x1B[23~":"f11","\x1B[24~":"f12","\x1Bb":"alt+left","\x1Bf":"alt+right","\x1Bp":"alt+up","\x1Bn":"alt+down"},X=(s,e)=>e.includes(s),te=(s,e,t)=>t===R.shift?X(s,Mh[e]):t===R.ctrl?X(s,Ih[e]):!1,ss="press";function bt(s){return s.includes("\x1B[200~")?!1:!!(s.includes(":3u")||s.includes(":3~")||s.includes(":3A")||s.includes(":3B")||s.includes(":3C")||s.includes(":3D")||s.includes(":3H")||s.includes(":3F")||s.includes(":3P")||s.includes(":3Q")||s.includes(":3S"))}function to(s){return s.includes("\x1B[200~")?!1:!!(s.includes(":2u")||s.includes(":2~")||s.includes(":2A")||s.includes(":2B")||s.includes(":2C")||s.includes(":2D")||s.includes(":2H")||s.includes(":2F")||s.includes(":2P")||s.includes(":2Q")||s.includes(":2S"))}function is(s){if(!s)return"press";let e=parseInt(s,10);return e===2?"repeat":e===3?"release":"press"}function so(s){let e=s.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(e){let o=parseInt(e[1],10),l=e[2]&&e[2].length>0?parseInt(e[2],10):void 0,a=e[3]?parseInt(e[3],10):void 0,c=e[4]?parseInt(e[4],10):1,h=is(e[5]);return ss=h,{codepoint:o,shiftedKey:l,baseLayoutKey:a,modifier:c-1,eventType:h}}let t=s.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(t){let o=parseInt(t[1],10),l=is(t[2]),a={A:-1,B:-2,C:-3,D:-4};return ss=l,{codepoint:a[t[3]],modifier:o-1,eventType:l}}let i=s.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(i){let o=parseInt(i[1],10),l=i[2]?parseInt(i[2],10):1,a=is(i[3]),h={2:L.insert,3:L.delete,5:L.pageUp,6:L.pageDown,7:L.home,8:L.end,11:L.f1,12:L.f2,13:L.f3,14:L.f4,15:L.f5,17:L.f6,18:L.f7,19:L.f8,20:L.f9,21:L.f10,23:L.f11,24:L.f12}[o];if(h!==void 0)return ss=a,{codepoint:h,modifier:l-1,eventType:a}}let r=s.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(r){let o=parseInt(r[1],10),l=is(r[2]),a=r[3]==="H"?L.home:L.end;return ss=l,{codepoint:a,modifier:o-1,eventType:l}}let n=s.match(/^\x1b\[(?:1;(\d+)(?::(\d+))?)?([PQS])$/);if(n){let o=n[1]?parseInt(n[1],10):1,l=is(n[2]),a={P:L.f1,Q:L.f2,S:L.f4};return ss=l,{codepoint:a[n[3]],modifier:o-1,eventType:l}}return null}function E(s,e,t){let i=so(s);if(!i)return!1;let r=i.modifier&~Ne,n=t&~Ne,o=ns(mt(i.codepoint),i.modifier),l=ns(mt(e),t);if(r===n&&o===l)return!0;let a=qs(i.shiftedKey,r,Ae);if(a&&(a.modifier&~Ne)===n&&a.codepoint===mt(e))return!0;if(r!==n)return!1;if(i.baseLayoutKey!==void 0&&i.baseLayoutKey===e){let c=o,h=c>=97&&c<=122,u=Ae.has(String.fromCharCode(c));if(!h&&!u)return!0}return!1}function Us(s){let e=s.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!e)return null;let t=parseInt(e[1],10);return{codepoint:parseInt(e[2],10),modifier:t-1}}function le(s,e,t){let i=Us(s);return i?i.codepoint===e&&i.modifier===t:!1}function io(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function Yn(s,e){return s==="\x7F"?e===0:s!=="\b"?!1:io()?e===R.ctrl:e===0}function Ah(s){let e=s.toLowerCase(),t=e.charCodeAt(0);return t>=97&&t<=122||e==="["||e==="\\"||e==="]"||e==="_"?String.fromCharCode(t&31):e==="-"?"":null}function Qn(s){return s>="0"&&s<="9"}function rs(s,e,t){let i=Us(s);if(!i)return!1;if(i.modifier===t&&ns(i.codepoint,i.modifier)===ns(e,t))return!0;let n=qs(i.codepoint,i.modifier,eo);return n?.modifier===t&&n.codepoint===e}function Lh(s,e){let t=[],i=e&~Ne,r=R.shift|R.ctrl|R.alt|R.super;if((i&~r)===0)return i&R.shift&&t.push("shift"),i&R.ctrl&&t.push("ctrl"),i&R.alt&&t.push("alt"),i&R.super&&t.push("super"),t.length>0?`${t.join("+")}+${s}`:s}function Eh(s){let e=s.toLowerCase(),t=new Set;for(;;){let i=Sh.find(r=>e.startsWith(`${r}+`));if(!i)break;if(t.has(i))return null;t.add(i),e=e.slice(i.length+1)}return!e||e.includes("+")&&e!=="+"?null:{key:e,ctrl:t.has("ctrl"),shift:t.has("shift"),alt:t.has("alt"),super:t.has("super")}}function ue(s,e){let t=Eh(e);if(!t)return!1;let{key:i,ctrl:r,shift:n,alt:o,super:l}=t,a=0;switch(n&&(a|=R.shift),o&&(a|=R.alt),r&&(a|=R.ctrl),l&&(a|=R.super),i){case"escape":case"esc":return a!==0?!1:s==="\x1B"||E(s,_.escape,0)||le(s,_.escape,0);case"space":return!z&&(a===R.ctrl&&s==="\0"||a===R.alt&&s==="\x1B ")?!0:a===0?s===" "||E(s,_.space,0)||le(s,_.space,0):E(s,_.space,a)||le(s,_.space,a);case"tab":return a===R.shift?s==="\x1B[Z"||E(s,_.tab,R.shift)||le(s,_.tab,R.shift):a===0?s===" "||E(s,_.tab,0):E(s,_.tab,a)||le(s,_.tab,a);case"enter":case"return":return a===R.shift?E(s,_.enter,R.shift)||E(s,_.kpEnter,R.shift)||le(s,_.enter,R.shift)?!0:z?s==="\x1B\r"||s===`
5
+ `:!1:a===R.alt?E(s,_.enter,R.alt)||E(s,_.kpEnter,R.alt)||le(s,_.enter,R.alt)?!0:z?!1:s==="\x1B\r":a===0?s==="\r"||!z&&s===`
6
+ `||s==="\x1BOM"||E(s,_.enter,0)||E(s,_.kpEnter,0):E(s,_.enter,a)||E(s,_.kpEnter,a)||le(s,_.enter,a);case"backspace":return a===R.alt?s==="\x1B\x7F"||s==="\x1B\b"?!0:E(s,_.backspace,R.alt)||le(s,_.backspace,R.alt):a===R.ctrl?Yn(s,R.ctrl)?!0:E(s,_.backspace,R.ctrl)||le(s,_.backspace,R.ctrl):a===0?Yn(s,0)||E(s,_.backspace,0)||le(s,_.backspace,0):E(s,_.backspace,a)||le(s,_.backspace,a);case"insert":return a===0?X(s,oe.insert)||E(s,L.insert,0):te(s,"insert",a)?!0:E(s,L.insert,a);case"delete":return a===0?X(s,oe.delete)||E(s,L.delete,0):te(s,"delete",a)?!0:E(s,L.delete,a);case"clear":return a===0?X(s,oe.clear):te(s,"clear",a);case"home":return a===0?X(s,oe.home)||E(s,L.home,0):te(s,"home",a)?!0:E(s,L.home,a);case"end":return a===0?X(s,oe.end)||E(s,L.end,0):te(s,"end",a)?!0:E(s,L.end,a);case"pageup":return a===0?X(s,oe.pageUp)||E(s,L.pageUp,0):te(s,"pageUp",a)?!0:E(s,L.pageUp,a);case"pagedown":return a===0?X(s,oe.pageDown)||E(s,L.pageDown,0):te(s,"pageDown",a)?!0:E(s,L.pageDown,a);case"up":return a===R.alt?s==="\x1Bp"||E(s,q.up,R.alt):a===0?X(s,oe.up)||E(s,q.up,0):te(s,"up",a)?!0:E(s,q.up,a);case"down":return a===R.alt?s==="\x1Bn"||E(s,q.down,R.alt):a===0?X(s,oe.down)||E(s,q.down,0):te(s,"down",a)?!0:E(s,q.down,a);case"left":return a===R.alt?s==="\x1B[1;3D"||!z&&s==="\x1BB"||s==="\x1Bb"||E(s,q.left,R.alt):a===R.ctrl?s==="\x1B[1;5D"||te(s,"left",R.ctrl)||E(s,q.left,R.ctrl):a===0?X(s,oe.left)||E(s,q.left,0):te(s,"left",a)?!0:E(s,q.left,a);case"right":return a===R.alt?s==="\x1B[1;3C"||!z&&s==="\x1BF"||s==="\x1Bf"||E(s,q.right,R.alt):a===R.ctrl?s==="\x1B[1;5C"||te(s,"right",R.ctrl)||E(s,q.right,R.ctrl):a===0?X(s,oe.right)||E(s,q.right,0):te(s,"right",a)?!0:E(s,q.right,a);case"f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":{let c=i;return a===0&&X(s,oe[c])?!0:E(s,L[c],a)}}if(i.length===1&&(i>="a"&&i<="z"||Qn(i)||Ae.has(i))){let c=i.charCodeAt(0),h=Ah(i),u=i>="a"&&i<="z",d=Qn(i);return a===R.ctrl+R.alt&&!z&&h&&s===`\x1B${h}`||a===R.alt&&!z&&(u||d||Ae.has(i))&&s===`\x1B${i}`?!0:a===R.ctrl?h&&s===h?!0:E(s,c,R.ctrl)||rs(s,c,R.ctrl):a===R.shift+R.ctrl?E(s,c,R.shift+R.ctrl)||rs(s,c,R.shift+R.ctrl):a===R.shift?u&&s===i.toUpperCase()?!0:E(s,c,R.shift)||rs(s,c,R.shift):a!==0?E(s,c,a)||rs(s,c,a):s===i||E(s,c,0)||rs(s,c,0)}return!1}function Xn(s,e,t){let i=mt(s),r=ns(i,e),n=r>=97&&r<=122,o=r>=48&&r<=57,l=Ae.has(String.fromCharCode(r)),a=n||o||l?r:t??r,c;if(a===_.escape?c="escape":a===_.tab?c="tab":a===_.enter||a===_.kpEnter?c="enter":a===_.space?c="space":a===_.backspace?c="backspace":a===L.delete?c="delete":a===L.insert?c="insert":a===L.home?c="home":a===L.end?c="end":a===L.pageUp?c="pageUp":a===L.pageDown?c="pageDown":a<=L.f1&&a>=L.f12?c=`f${L.f1-a+1}`:a===q.up?c="up":a===q.down?c="down":a===q.left?c="left":a===q.right?c="right":(a>=48&&a<=57||a>=97&&a<=122||Ae.has(String.fromCharCode(a)))&&(c=String.fromCharCode(a)),!!c)return Lh(c,e)}function ro(s){let e=so(s);if(e){let r=qs(e.shiftedKey,e.modifier,Ae);return Xn(r?.codepoint??e.codepoint,r?.modifier??e.modifier,e.baseLayoutKey)}let t=Us(s);if(t){let r=qs(t.codepoint,t.modifier,eo);return Xn(r?.codepoint??t.codepoint,r?.modifier??t.modifier)}if(z&&(s==="\x1B\r"||s===`
7
+ `))return"shift+enter";let i=Rh[s];if(i)return i;if(s==="\x1B")return"escape";if(s==="")return"ctrl+\\";if(s==="")return"ctrl+]";if(s==="")return"ctrl+-";if(s==="\x1B\x1B")return"ctrl+alt+[";if(s==="\x1B")return"ctrl+alt+\\";if(s==="\x1B")return"ctrl+alt+]";if(s==="\x1B")return"ctrl+alt+-";if(s===" ")return"tab";if(s==="\r"||!z&&s===`
8
+ `||s==="\x1BOM")return"enter";if(s==="\0")return"ctrl+space";if(s===" ")return"space";if(s==="\x7F")return"backspace";if(s==="\b")return io()?"ctrl+backspace":"backspace";if(s==="\x1B[Z")return"shift+tab";if(!z&&s==="\x1B\r")return"alt+enter";if(!z&&s==="\x1B ")return"alt+space";if(s==="\x1B\x7F"||s==="\x1B\b")return"alt+backspace";if(!z&&s==="\x1BB")return"alt+left";if(!z&&s==="\x1BF")return"alt+right";if(!z&&s.length===2&&s[0]==="\x1B"){let r=s.charCodeAt(1);if(r>=1&&r<=26)return`ctrl+alt+${String.fromCharCode(r+96)}`;let n=String.fromCharCode(r);if(r>=97&&r<=122||r>=48&&r<=57||Ae.has(n))return`alt+${n}`}if(s==="\x1B[A")return"up";if(s==="\x1B[B")return"down";if(s==="\x1B[C")return"right";if(s==="\x1B[D")return"left";if(s==="\x1B[H"||s==="\x1BOH")return"home";if(s==="\x1B[F"||s==="\x1BOF")return"end";if(s==="\x1B[3~")return"delete";if(s==="\x1B[5~")return"pageUp";if(s==="\x1B[6~")return"pageDown";if(s.length===1){let r=s.charCodeAt(0);if(r>=1&&r<=26)return`ctrl+${String.fromCharCode(r+96)}`;if(r>=32&&r<=126)return s}}var Ph=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,$h=R.shift|Ne;function os(s){let e=s.match(Ph);if(!e)return;let t=Number.parseInt(e[1]??"",10);if(!Number.isFinite(t))return;let i=e[2]&&e[2].length>0?Number.parseInt(e[2],10):void 0,r=e[4]?Number.parseInt(e[4],10):1,n=Number.isFinite(r)?r-1:0;if((n&~$h)!==0||n&(R.alt|R.ctrl))return;let o=t;if(n&R.shift&&typeof i=="number"&&(o=i),o=mt(o),!(!Number.isFinite(o)||o<32)&&!(o>=Ch&&o<=Th))try{return String.fromCodePoint(o)}catch{return}}function _h(s){let e=Us(s);if(!(!e||(e.modifier&~Ne&~R.shift)!==0)&&!(!Number.isFinite(e.codepoint)||e.codepoint<32))try{return String.fromCodePoint(e.codepoint)}catch{return}}function rr(s){return os(s)??_h(s)}var or={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.historyPrevious":{defaultKeys:[],description:"Select previous prompt history entry"},"tui.editor.historyNext":{defaultKeys:[],description:"Select next prompt history entry"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:["pageUp","ctrl+pageUp"],description:"Page up"},"tui.editor.pageDown":{defaultKeys:["pageDown","ctrl+pageDown"],description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:["shift+enter","ctrl+j"],description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"},"tui.altScreen.pageUp":{defaultKeys:"pageUp",description:"Scroll viewport up one page"},"tui.altScreen.pageDown":{defaultKeys:"pageDown",description:"Scroll viewport down one page"},"tui.altScreen.halfPageUp":{defaultKeys:[],description:"Scroll viewport up half a page"},"tui.altScreen.halfPageDown":{defaultKeys:[],description:"Scroll viewport down half a page"},"tui.altScreen.lineUp":{defaultKeys:[],description:"Scroll viewport up one line"},"tui.altScreen.lineDown":{defaultKeys:[],description:"Scroll viewport down one line"},"tui.altScreen.previousPrompt":{defaultKeys:["ctrl+shift+up","ctrl+up"],description:"Jump to previous semantic prompt"},"tui.altScreen.nextPrompt":{defaultKeys:["ctrl+shift+down","ctrl+down"],description:"Jump to next semantic prompt"},"tui.altScreen.search":{defaultKeys:"ctrl+shift+f",description:"Search the primary scroll view"},"tui.altScreen.searchNext":{defaultKeys:["enter","ctrl+g"],description:"Select the next search match"},"tui.altScreen.searchPrevious":{defaultKeys:["shift+enter","ctrl+shift+g"],description:"Select the previous search match"},"tui.altScreen.searchClose":{defaultKeys:"escape",description:"Close transcript search"},"tui.altScreen.top":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"ctrl+end",description:"Scroll viewport to bottom"}};function nr(s){if(s===void 0)return[];let e=Array.isArray(s)?s:[s],t=new Set,i=[];for(let r of e)t.has(r)||(t.add(r),i.push(r));return i}var ls=class{definitions;userBindings;keysById=new Map;conflicts=[];constructor(e,t={}){this.definitions=e,this.userBindings=t,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let e=new Map;for(let[t,i]of Object.entries(this.userBindings))if(t in this.definitions)for(let r of nr(i)){let n=e.get(r)??new Set;n.add(t),e.set(r,n)}for(let[t,i]of e)i.size>1&&this.conflicts.push({key:t,keybindings:[...i]});for(let[t,i]of Object.entries(this.definitions)){let r=this.userBindings[t],n=nr(r===void 0?i.defaultKeys:r);this.keysById.set(t,n)}}matches(e,t){let i=this.keysById.get(t)??[];for(let r of i)if(ue(e,r))return!0;return!1}getKeys(e){return[...this.keysById.get(e)??[]]}getDefinition(e){return this.definitions[e]}getConflicts(){return this.conflicts.map(e=>({...e,keybindings:[...e.keybindings]}))}setUserBindings(e){this.userBindings=e,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let e={};for(let t of Object.keys(this.definitions)){let i=this.keysById.get(t)??[];e[t]=i.length===1?i[0]:[...i]}return e}},zs=null;function no(s){zs=s}function U(){return zs||(zs=new ls(or)),zs}function yt(s,e,t,i,r){let n;if(s.matches(e,"tui.select.pageUp"))n=-1;else if(s.matches(e,"tui.select.pageDown"))n=1;else return;return Math.max(0,Math.min(i-1,t+n*r))}var ap={};cc(ap,{Box:()=>ui,CURSOR_MARKER:()=>Z,CancellableLoader:()=>di,CombinedAutocompleteProvider:()=>Zs,Container:()=>ae,Editor:()=>gi,HStack:()=>xi,Image:()=>bi,Input:()=>$e,Key:()=>Jn,KeybindingsManager:()=>ls,Loader:()=>Lt,Markdown:()=>Si,Marked:()=>ds,MouseRegion:()=>Ci,ProcessTerminal:()=>Ei,ScrollView:()=>Ft,SelectList:()=>$t,SettingsList:()=>Ti,Spacer:()=>vi,StdinBuffer:()=>Kt,TUI_KEYBINDINGS:()=>or,Text:()=>At,TruncatedText:()=>Mi,TuiAltScreen:()=>Fi,TuiMainScreen:()=>Hi,VStack:()=>Ii,allocateImageId:()=>ti,backgroundAnsi:()=>gt,calculateImageRows:()=>Xo,colorToHex:()=>ft,colorToOkhsl:()=>Ks,colorToOklch:()=>xe,colorToRgb:()=>me,compositeTuiLine:()=>ye,decodeKittyPrintable:()=>os,deleteAllKittyImages:()=>si,deleteKittyImage:()=>It,detectCapabilities:()=>Sr,encodeITerm2:()=>vr,encodeKitty:()=>Cr,foregroundAnsi:()=>pt,formatProgramStatus:()=>Ht,fuzzyFilter:()=>Ke,fuzzyMatch:()=>br,getCapabilities:()=>se,getCellDimensions:()=>fs,getGifDimensions:()=>Ar,getImageDimensions:()=>oi,getJpegDimensions:()=>Rr,getKeybindings:()=>U,getNativeClipboard:()=>_l,getOsc8LinkAtColumn:()=>_s,getPngDimensions:()=>ms,getSelectPageIndex:()=>yt,getTerminalColorMode:()=>ps,getWebpDimensions:()=>Lr,hyperlink:()=>xs,imageFallback:()=>bs,indexedColor:()=>es,isAppleTerminalSession:()=>jr,isFocusable:()=>hi,isKeyRelease:()=>bt,isKeyRepeat:()=>to,isKittyProtocolActive:()=>Zn,isViewportTUI:()=>tl,matchesKey:()=>ue,mixColors:()=>Vs,okhslColor:()=>De,oklabToOkhslLightness:()=>ht,oklchColor:()=>dt,parseColor:()=>Se,parseKey:()=>ro,parseTerminalColorSchemeReport:()=>Js,renderFakeCursor:()=>Pe,renderImage:()=>li,renderLatex:()=>Cs,replaceControlCharacters:()=>at,resetCapabilitiesCache:()=>qo,rgbColor:()=>he,setCapabilities:()=>gs,setCapabilityOverrides:()=>Uo,setCellDimensions:()=>ei,setImageTranscoder:()=>xl,setKeybindings:()=>no,setKittyProtocolActive:()=>xt,sliceByColumn:()=>H,stripTerminalSequences:()=>_e,styleText:()=>Gn,styleTextWithAnsi:()=>ts,truncateToWidth:()=>D,visibleWidth:()=>S,wrapTextWithAnsi:()=>ne});function hr(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var He=hr();function po(s){He=s}var We={exec:()=>null};function wt(s){let e=[];return t=>{let i=Math.max(0,Math.min(3,t-1)),r=e[i];return r||(r=s(i),e[i]=r),r}}function $(s,e=""){let t=typeof s=="string"?s:s.source,i={replace:(r,n)=>{let o=typeof n=="string"?n:n.source;return o=o.replace(j.caret,"$1"),t=t.replace(r,o),i},getRegex:()=>new RegExp(t,e)};return i}var Oh=((s="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+s)}catch{return!1}})(),j={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:s=>new RegExp(`^( {0,3}${s})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:wt(s=>new RegExp(`^ {0,${s}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:wt(s=>new RegExp(`^ {0,${s}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:wt(s=>new RegExp(`^ {0,${s}}(?:\`\`\`|~~~)`)),headingBeginRegex:wt(s=>new RegExp(`^ {0,${s}}#`)),htmlBeginRegex:wt(s=>new RegExp(`^ {0,${s}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:wt(s=>new RegExp(`^ {0,${s}}>`))},Bh=/^(?:[ \t]*(?:\n|$))+/,Dh=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Nh=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hs=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Wh=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ur=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,go=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,mo=$(go).replace(/bull/g,ur).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Fh=$(go).replace(/bull/g,ur).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),dr=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Hh=/^[^\n]+/,fr=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Kh=$(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",fr).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Vh=$(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ur).getRegex(),Qs="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",pr=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,qh=$("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",pr).replace("tag",Qs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),xo=s=>$(dr).replace("hr",hs).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",s).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qs).getRegex(),Uh=xo(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),zh=xo(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),jh=$(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",zh).getRegex(),gr={blockquote:jh,code:Dh,def:Kh,fences:Nh,heading:Wh,hr:hs,html:qh,lheading:mo,list:Vh,newline:Bh,paragraph:Uh,table:We,text:Hh},oo=$("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",hs).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qs).getRegex(),Gh={...gr,lheading:Fh,table:oo,paragraph:$(dr).replace("hr",hs).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",oo).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qs).getRegex()},Yh={...gr,html:$(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",pr).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:We,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:$(dr).replace("hr",hs).replace("heading",` *#{1,6} *[^
9
+ ]`).replace("lheading",mo).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Qh=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Xh=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,bo=/^( {2,}|\\)\n(?!\s*$)/,Zh=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ce=/[\p{P}\p{S}]/u,St=/[\s\p{P}\p{S}]/u,us=/[^\s\p{P}\p{S}]/u,Jh=$(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,St).getRegex(),eu=/[\p{Pi}\p{Ps}"']/u,yo=/(?!~)[\p{P}\p{S}]/u,tu=/(?!~)[\s\p{P}\p{S}]/u,su=/(?:[^\s\p{P}\p{S}]|~)/u,iu=$(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Oh?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),wo=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,ru=$(wo,"u").replace(/punct/g,Ce).getRegex(),nu=$(wo,"u").replace(/punct/g,yo).getRegex(),ou=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,lu=$(ou,"u").replace(/openQuote/g,eu).replace(/punct/g,Ce).getRegex(),ko="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",au=$(ko,"gu").replace(/notPunctSpace/g,us).replace(/punctSpace/g,St).replace(/punct/g,Ce).getRegex(),cu=$(ko,"gu").replace(/notPunctSpace/g,su).replace(/punctSpace/g,tu).replace(/punct/g,yo).getRegex(),hu="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",uu=$(hu,"gu").replace(/notPunctSpace/g,us).replace(/punctSpace/g,St).replace(/punct/g,Ce).getRegex(),du=$("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,us).replace(/punctSpace/g,St).replace(/punct/g,Ce).getRegex(),fu="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",pu=$(fu,"gu").replace(/notPunctSpace/g,us).replace(/punctSpace/g,St).replace(/punct/g,Ce).getRegex(),gu=$(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ce).getRegex(),mu="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",xu=$(mu,"gu").replace(/notPunctSpace/g,us).replace(/punctSpace/g,St).replace(/punct/g,Ce).getRegex(),bu=$(/\\(punct)/,"gu").replace(/punct/g,Ce).getRegex(),yu=$(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),wu=$(pr).replace("(?:-->|$)","-->").getRegex(),ku=$("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",wu).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Gs=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Su=$(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Gs).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),So=$(/^!?\[(label)\]\[(ref)\]/).replace("label",Gs).replace("ref",fr).getRegex(),Co=$(/^!?\[(ref)\](?:\[\])?/).replace("ref",fr).getRegex(),Cu=$("reflink|nolink(?!\\()","g").replace("reflink",So).replace("nolink",Co).getRegex(),lo=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,mr={_backpedal:We,anyPunctuation:bu,autolink:yu,blockSkip:iu,br:bo,code:Xh,del:We,delLDelim:We,delRDelim:We,emStrongLDelim:ru,emStrongRDelimAst:au,emStrongRDelimUnd:du,escape:Qh,link:Su,nolink:Co,punctuation:Jh,reflink:So,reflinkSearch:Cu,tag:ku,text:Zh,url:We},Tu={...mr,emStrongLDelim:lu,emStrongRDelimAst:uu,emStrongRDelimUnd:pu,link:$(/^!?\[(label)\]\((.*?)\)/).replace("label",Gs).getRegex(),reflink:$(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Gs).getRegex()},lr={...mr,emStrongRDelimAst:cu,emStrongLDelim:nu,delLDelim:gu,delRDelim:xu,url:$(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",lo).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:$(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",lo).getRegex()},vu={...lr,br:$(bo).replace("{2,}","*").getRegex(),text:$(lr.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},js={normal:gr,gfm:Gh,pedantic:Yh},as={normal:mr,gfm:lr,breaks:vu,pedantic:Tu},Mu={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ao=s=>Mu[s];function be(s,e){if(e){if(j.escapeTest.test(s))return s.replace(j.escapeReplace,ao)}else if(j.escapeTestNoEncode.test(s))return s.replace(j.escapeReplaceNoEncode,ao);return s}function co(s){try{s=encodeURI(s).replace(j.percentDecode,"%")}catch{return null}return s}function ho(s,e){let t=s.replace(j.findPipe,(n,o,l)=>{let a=!1,c=o;for(;--c>=0&&l[c]==="\\";)a=!a;return a?"|":" |"}),i=t.split(j.splitPipe),r=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),e)if(i.length>e)i.splice(e);else for(;i.length<e;)i.push("");for(;r<i.length;r++)i[r]=i[r].trim().replace(j.slashPipe,"|");return i}function Le(s,e,t){let i=s.length;if(i===0)return"";let r=0;for(;r<i;){let n=s.charAt(i-r-1);if(n===e&&!t)r++;else if(n!==e&&t)r++;else break}return s.slice(0,i-r)}function uo(s){let e=s.split(`
10
+ `),t=e.length-1;for(;t>=0&&j.blankLine.test(e[t]);)t--;return e.length-t<=2?s:e.slice(0,t+1).join(`
11
+ `)}function Iu(s,e){if(s.indexOf(e[1])===-1)return-1;let t=0;for(let i=0;i<s.length;i++)if(s[i]==="\\")i++;else if(s[i]===e[0])t++;else if(s[i]===e[1]&&(t--,t<0))return i;return t>0?-2:-1}function Ru(s,e=0){let t=e,i="";for(let r of s)if(r===" "){let n=4-t%4;i+=" ".repeat(n),t+=n}else i+=r,t++;return i}function fo(s,e,t,i,r){let n=e.href,o=e.title||null,l=s[1].replace(r.other.outputLinkReplace,"$1"),a=s[0].charAt(0)==="!";i.state.inLink=!0;let c=i.state.linkEmitted,h=i.state.inRawBlock;i.state.linkEmitted=!1;let u=i.inlineTokens(l),d=i.state.linkEmitted;if(i.state.linkEmitted=c,i.state.inLink=!1,!a){if(d){i.state.inRawBlock=h;return}i.state.linkEmitted=!0}return{type:a?"image":"link",raw:t,href:n,title:o,text:l,tokens:u}}function Au(s,e,t){let i=s.match(t.other.indentCodeCompensation);if(i===null)return e;let r=i[1];return e.split(`
12
+ `).map(n=>{let o=n.match(t.other.beginningSpace);if(o===null)return n;let[l]=o;return l.length>=r.length?n.slice(r.length):n}).join(`
13
+ `)}var kt=class{options;rules;lexer;constructor(s){this.options=s||He}space(s){let e=this.rules.block.newline.exec(s);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(s){let e=this.rules.block.code.exec(s);if(e){let t=this.options.pedantic?e[0]:uo(e[0]),i=t.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t,codeBlockStyle:"indented",text:i}}}fences(s){let e=this.rules.block.fences.exec(s);if(e){let t=e[0],i=Au(t,e[3]||"",this.rules);return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:i}}}heading(s){let e=this.rules.block.heading.exec(s);if(e){let t=e[2].trim();if(this.rules.other.endingHash.test(t)){let i=Le(t,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(t=i.trim())}return{type:"heading",raw:Le(e[0],`
14
+ `),depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(s){let e=this.rules.block.hr.exec(s);if(e)return{type:"hr",raw:Le(e[0],`
15
+ `)}}blockquote(s){let e=this.rules.block.blockquote.exec(s);if(e){let t=Le(e[0],`
16
+ `).split(`
17
+ `),i="",r="",n=[];for(;t.length>0;){let o=!1,l=[],a;for(a=0;a<t.length;a++)if(this.rules.other.blockquoteStart.test(t[a]))l.push(t[a]),o=!0;else if(!o)l.push(t[a]);else break;t=t.slice(a);let c=l.join(`
18
+ `),h=c.replace(this.rules.other.blockquoteSetextReplace,`
19
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
20
+ ${c}`:c,r=r?`${r}
21
+ ${h}`:h;let u=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(h,n,!0),this.lexer.state.top=u,t.length===0)break;let d=n.at(-1);if(d?.type==="code")break;if(d?.type==="blockquote"){let f=d,p=t.join(`
22
+ `),g=f.raw+`
23
+ `+p.replace(this.rules.other.blockquoteSetextReplace2,""),x=this.blockquote(g);n[n.length-1]=x,i=`${i}
24
+ ${p}`,r=r.substring(0,r.length-f.text.length)+x.text;break}else if(d?.type==="list"){let f=d,p=f.raw+`
25
+ `+t.join(`
26
+ `),g=this.list(p);n[n.length-1]=g,i=i.substring(0,i.length-d.raw.length)+g.raw,r=r.substring(0,r.length-f.raw.length)+g.raw,t=p.substring(n.at(-1).raw.length).split(`
27
+ `);continue}}return{type:"blockquote",raw:i,tokens:n,text:r}}}list(s){let e=this.rules.block.list.exec(s);if(e){let t=e[1].trim(),i=t.length>1,r={type:"list",raw:"",ordered:i,start:i?+t.slice(0,-1):"",loose:!1,items:[]};t=i?`\\d{1,9}\\${t.slice(-1)}`:`\\${t}`,this.options.pedantic&&(t=i?t:"[*+-]");let n=this.rules.other.listItemRegex(t),o=!1;for(;s;){let a=!1,c="",h="";if(!(e=n.exec(s))||this.rules.block.hr.test(s))break;c=e[0],s=s.substring(c.length);let u=Ru(e[2].split(`
28
+ `,1)[0],e[1].length),d=s.split(`
29
+ `,1)[0],f=!u.trim(),p=0;if(this.options.pedantic?(p=2,h=u.trimStart()):f?p=e[1].length+1:(p=u.search(this.rules.other.nonSpaceChar),p=p>4?1:p,h=u.slice(p),p+=e[1].length),f&&this.rules.other.blankLine.test(d)&&(c+=d+`
30
+ `,s=s.substring(d.length+1),a=!0),!a){let g=this.rules.other.nextBulletRegex(p),x=this.rules.other.hrRegex(p),m=this.rules.other.fencesBeginRegex(p),w=this.rules.other.headingBeginRegex(p),b=this.rules.other.htmlBeginRegex(p),k=this.rules.other.blockquoteBeginRegex(p);for(;s;){let v=s.split(`
31
+ `,1)[0],y;if(d=v,this.options.pedantic?(d=d.replace(this.rules.other.listReplaceNesting," "),y=d):y=d.replace(this.rules.other.tabCharGlobal," "),m.test(d)||w.test(d)||b.test(d)||k.test(d)||g.test(d)||x.test(d))break;if(y.search(this.rules.other.nonSpaceChar)>=p||!d.trim())h+=`
32
+ `+y.slice(p);else{if(f||u.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||m.test(u)||w.test(u)||x.test(u))break;h+=`
33
+ `+d}f=!d.trim(),c+=v+`
34
+ `,s=s.substring(v.length+1),u=y.slice(p)}}r.loose||(o?r.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),r.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]}),r.raw+=c}let l=r.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let a of r.items)if(this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]),!r.loose){let c=a.tokens.filter(u=>u.type==="space"),h=c.length>0&&c.some(u=>this.rules.other.anyLine.test(u.raw));r.loose=h}for(let a of r.items){let c=a.tokens[0];if(a.task&&(c?.type==="text"||c?.type==="paragraph")){a.text=a.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let u=this.lexer.inlineQueue.length-1;u>=0;u--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[u].src)){this.lexer.inlineQueue[u].src=this.lexer.inlineQueue[u].src.replace(this.rules.other.listReplaceTask,"");break}let h=this.rules.other.listTaskCheckbox.exec(a.raw);if(h){let u={type:"checkbox",raw:h[0]+" ",checked:h[0]!=="[ ]"};a.checked=u.checked,r.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=u.raw+a.tokens[0].raw,a.tokens[0].text=u.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(u)):a.tokens.unshift({type:"paragraph",raw:u.raw,text:u.raw,tokens:[u]}):a.tokens.unshift(u)}}else a.task&&(a.task=!1)}if(r.loose)for(let a of r.items){a.loose=!0;for(let c of a.tokens)c.type==="text"&&(c.type="paragraph")}return r}}html(s){let e=this.rules.block.html.exec(s);if(e){let t=uo(e[0]);return{type:"html",block:!0,raw:t,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:t}}}def(s){let e=this.rules.block.def.exec(s);if(e){let t=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:t,raw:Le(e[0],`
35
+ `),href:i,title:r}}}table(s){let e=this.rules.block.table.exec(s);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let t=ho(e[1]),i=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
36
+ `):[],n={type:"table",raw:Le(e[0],`
37
+ `),header:[],align:[],rows:[]};if(t.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?n.align.push("right"):this.rules.other.tableAlignCenter.test(o)?n.align.push("center"):this.rules.other.tableAlignLeft.test(o)?n.align.push("left"):n.align.push(null);for(let o=0;o<t.length;o++)n.header.push({text:t[o],tokens:this.lexer.inline(t[o]),header:!0,align:n.align[o]});for(let o of r)n.rows.push(ho(o,n.header.length).map((l,a)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:n.align[a]})));return n}}lheading(s){let e=this.rules.block.lheading.exec(s);if(e){let t=e[1].trim();return{type:"heading",raw:Le(e[0],`
38
+ `),depth:e[2].charAt(0)==="="?1:2,text:t,tokens:this.lexer.inline(t)}}}paragraph(s){let e=this.rules.block.paragraph.exec(s);if(e){let t=e[1].charAt(e[1].length-1)===`
39
+ `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(s){let e=this.rules.block.text.exec(s);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(s){let e=this.rules.inline.escape.exec(s);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(s){let e=this.rules.inline.tag.exec(s);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(s){let e=this.rules.inline.link.exec(s);if(e){let t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let n=Le(t.slice(0,-1),"\\");if((t.length-n.length)%2===0)return}else{let n=Iu(e[2],"()");if(n===-2)return;if(n>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+n;e[2]=e[2].substring(0,n),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let i=e[2],r="";if(this.options.pedantic){let n=this.rules.other.pedanticHrefTitle.exec(i);n&&(i=n[1],r=n[3])}else r=e[3]?e[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?i=i.slice(1):i=i.slice(1,-1)),fo(e,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(s,e){let t;if((t=this.rules.inline.reflink.exec(s))||(t=this.rules.inline.nolink.exec(s))){let i=(t[2]||t[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=e[i.toLowerCase()];if(!r){let n=t[0].charAt(0);return{type:"text",raw:n,text:n}}return fo(t,r,t[0],this.lexer,this.rules)}}emStrong(s,e,t=""){let i=this.rules.inline.emStrongLDelim.exec(s);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&t.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!t||this.rules.inline.punctuation.exec(t))){let r=[...i[0]].length-1,n,o,l=r,a=0,c=i[0][0],h=t===c,u=c==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,e=e.slice(-1*s.length+r);(i=u.exec(e))!==null;){if(n=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!n)continue;if(o=[...n].length,i[3]||i[4]){l+=o;continue}else if(i[5]||i[6]){if(r%3&&!((r+o)%3)){a+=o;continue}if(h)break}if(l-=o,l>0)continue;o=Math.min(o,o+l+a);let d=[...i[0]][0].length,f=s.slice(0,r+i.index+d+o);if(Math.min(r,o)%2){let g=f.slice(1,-1);return{type:"em",raw:f,text:g,tokens:this.lexer.inlineTokens(g)}}let p=f.slice(2,-2);return{type:"strong",raw:f,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(s){let e=this.rules.inline.code.exec(s);if(e){let t=e[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(t),r=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return i&&r&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:e[0],text:t}}}br(s){let e=this.rules.inline.br.exec(s);if(e)return{type:"br",raw:e[0]}}del(s,e,t=""){let i=this.rules.inline.delLDelim.exec(s);if(i&&(!i[1]||!t||this.rules.inline.punctuation.exec(t))){let r=[...i[0]].length-1,n,o,l=r,a=this.rules.inline.delRDelim;for(a.lastIndex=0,e=e.slice(-1*s.length+r);(i=a.exec(e))!==null;){if(n=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!n||(o=[...n].length,o!==r))continue;if(i[3]||i[4]){l+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l);let c=[...i[0]][0].length,h=s.slice(0,r+i.index+c+o),u=h.slice(r,-r);return{type:"del",raw:h,text:u,tokens:this.lexer.inlineTokens(u)}}}}autolink(s){let e=this.rules.inline.autolink.exec(s);if(e){let t,i;return e[2]==="@"?(t=e[1],i="mailto:"+t):(t=e[1],i=t),{type:"link",raw:e[0],text:t,href:i,tokens:[{type:"text",raw:t,text:t}]}}}url(s){let e;if(e=this.rules.inline.url.exec(s)){let t,i;if(e[2]==="@")t=e[0],i="mailto:"+t;else{let r;do r=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(r!==e[0]);t=e[0],e[1]==="www."?i="http://"+e[0]:i=e[0]}return{type:"link",raw:e[0],text:t,href:i,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(s){let e=this.rules.inline.text.exec(s);if(e){let t=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:t}}}},de=class ar{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||He,this.options.tokenizer=this.options.tokenizer||new kt,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let t={other:j,block:js.normal,inline:as.normal};this.options.pedantic?(t.block=js.pedantic,t.inline=as.pedantic):this.options.gfm&&(t.block=js.gfm,this.options.breaks?t.inline=as.breaks:t.inline=as.gfm),this.tokenizer.rules=t}static get rules(){return{block:js,inline:as}}static lex(e,t){return new ar(t).lex(e)}static lexInline(e,t){return new ar(t).inlineTokens(e)}lex(e){e=e.replace(j.carriageReturn,`
40
+ `),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let i=this.inlineQueue[t];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(j.tabCharGlobal," ").replace(j.spaceLine,""));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let n;if(this.options.extensions?.block?.some(l=>(n=l.call({lexer:this},e,t))?(e=e.substring(n.raw.length),t.push(n),!0):!1))continue;if(n=this.tokenizer.space(e)){e=e.substring(n.raw.length);let l=t.at(-1);n.raw.length===1&&l!==void 0?l.raw+=`
41
+ `:t.push(n);continue}if(n=this.tokenizer.code(e)){e=e.substring(n.raw.length);let l=t.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`
42
+ `)?"":`
43
+ `)+n.raw,l.text+=`
44
+ `+n.text,this.inlineQueue.at(-1).src=l.text):t.push(n);continue}if(n=this.tokenizer.fences(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.heading(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.hr(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.blockquote(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.list(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.html(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.def(e)){e=e.substring(n.raw.length);let l=t.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`
45
+ `)?"":`
46
+ `)+n.raw,l.text+=`
47
+ `+n.raw,this.inlineQueue.at(-1).src=l.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title},t.push(n));continue}if(n=this.tokenizer.table(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.lheading(e)){e=e.substring(n.raw.length),t.push(n);continue}let o=e;if(this.options.extensions?.startBlock){let l=1/0,a=e.slice(1),c;this.options.extensions.startBlock.forEach(h=>{c=h.call({lexer:this},a),typeof c=="number"&&c>=0&&(l=Math.min(l,c))}),l<1/0&&l>=0&&(o=e.substring(0,l+1))}if(this.state.top&&(n=this.tokenizer.paragraph(o))){let l=t.at(-1);i&&l?.type==="paragraph"?(l.raw+=(l.raw.endsWith(`
48
+ `)?"":`
49
+ `)+n.raw,l.text+=`
50
+ `+n.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):t.push(n),i=o.length!==e.length,e=e.substring(n.raw.length);continue}if(n=this.tokenizer.text(e)){e=e.substring(n.raw.length);let l=t.at(-1);l?.type==="text"?(l.raw+=(l.raw.endsWith(`
51
+ `)?"":`
52
+ `)+n.raw,l.text+=`
53
+ `+n.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):t.push(n);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes("["))return!1;let t=this.tokenizer.rules.inline.link;for(let i of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(i[0])&&e.charAt(i.index-1)!=="!")return!0;for(let i of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let r=i[0],n=r.lastIndexOf("[");if(!(r.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,r.slice(n+1,-1)))&&!(n>1&&this.linkInText(r.slice(1,n-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let i=e;if(this.tokens.links&&e.includes("[")){let l=this.tokenizer.rules.inline.reflinkSearch,a=c=>{let h=c.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,c.slice(h+1,-1)))return c;if(h>1&&c.charAt(0)!=="!"){let u=c.slice(1,h-1);if(this.linkInText(u))return"["+u.replace(l,a)+"]["+"a".repeat(c.length-h-2)+"]"}return"["+"a".repeat(c.length-2)+"]"};i=i.replace(l,a)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,l=>"+".repeat(l.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(l,a,c)=>{let h=c?c.length:0;return l.slice(0,h)+"["+"a".repeat(l.length-h-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let r=!1,n="",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}r||(n=""),r=!1;let l;if(this.options.extensions?.inline?.some(c=>(l=c.call({lexer:this},e,t))?(e=e.substring(l.raw.length),t.push(l),!0):!1))continue;if(l=this.tokenizer.escape(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.tag(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.link(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(l.raw.length);let c=t.at(-1);l.type==="text"&&c?.type==="text"?(c.raw+=l.raw,c.text+=l.text):t.push(l);continue}if(l=this.tokenizer.emStrong(e,i,n)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.codespan(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.br(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.del(e,i,n)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.autolink(e)){e=e.substring(l.raw.length),t.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(e))){e=e.substring(l.raw.length),t.push(l);continue}let a=e;if(this.options.extensions?.startInline){let c=1/0,h=e.slice(1),u;this.options.extensions.startInline.forEach(d=>{u=d.call({lexer:this},h),typeof u=="number"&&u>=0&&(c=Math.min(c,u))}),c<1/0&&c>=0&&(a=e.substring(0,c+1))}if(l=this.tokenizer.inlineText(a)){e=e.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(n=l.raw.slice(-1)),r=!0;let c=t.at(-1);c?.type==="text"?(c.raw+=l.raw,c.text+=l.text):t.push(l);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},Ys=class{options;parser;constructor(s){this.options=s||He}space(s){return""}code({text:s,lang:e,escaped:t}){let i=(e||"").match(j.notSpaceStart)?.[0],r=s.replace(j.endingNewline,"")+`
54
+ `;return i?'<pre><code class="language-'+be(i)+'">'+(t?r:be(r,!0))+`</code></pre>
55
+ `:"<pre><code>"+(t?r:be(r,!0))+`</code></pre>
56
+ `}blockquote({tokens:s}){return`<blockquote>
57
+ ${this.parser.parse(s)}</blockquote>
58
+ `}html({text:s}){return s}def(s){return""}heading({tokens:s,depth:e}){return`<h${e}>${this.parser.parseInline(s)}</h${e}>
59
+ `}hr(s){return`<hr>
60
+ `}list(s){let e=s.ordered,t=s.start,i="";for(let o=0;o<s.items.length;o++){let l=s.items[o];i+=this.listitem(l)}let r=e?"ol":"ul",n=e&&t!==1?' start="'+t+'"':"";return"<"+r+n+`>
61
+ `+i+"</"+r+`>
62
+ `}listitem(s){return`<li>${this.parser.parse(s.tokens)}</li>
63
+ `}checkbox({checked:s}){return"<input "+(s?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:s}){return`<p>${this.parser.parseInline(s)}</p>
64
+ `}table(s){let e="",t="";for(let r=0;r<s.header.length;r++)t+=this.tablecell(s.header[r]);e+=this.tablerow({text:t});let i="";for(let r=0;r<s.rows.length;r++){let n=s.rows[r];t="";for(let o=0;o<n.length;o++)t+=this.tablecell(n[o]);i+=this.tablerow({text:t})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
65
+ <thead>
66
+ `+e+`</thead>
67
+ `+i+`</table>
68
+ `}tablerow({text:s}){return`<tr>
69
+ ${s}</tr>
70
+ `}tablecell(s){let e=this.parser.parseInline(s.tokens),t=s.header?"th":"td";return(s.align?`<${t} align="${s.align}">`:`<${t}>`)+e+`</${t}>
71
+ `}strong({tokens:s}){return`<strong>${this.parser.parseInline(s)}</strong>`}em({tokens:s}){return`<em>${this.parser.parseInline(s)}</em>`}codespan({text:s}){return`<code>${be(s,!0)}</code>`}br(s){return"<br>"}del({tokens:s}){return`<del>${this.parser.parseInline(s)}</del>`}link({href:s,title:e,tokens:t}){let i=this.parser.parseInline(t),r=co(s);if(r===null)return i;s=r;let n='<a href="'+s+'"';return e&&(n+=' title="'+be(e)+'"'),n+=">"+i+"</a>",n}image({href:s,title:e,text:t,tokens:i}){i&&(t=this.parser.parseInline(i,this.parser.textRenderer));let r=co(s);if(r===null)return be(t);s=r;let n=`<img src="${s}" alt="${be(t)}"`;return e&&(n+=` title="${be(e)}"`),n+=">",n}text(s){return"tokens"in s&&s.tokens?this.parser.parseInline(s.tokens):"escaped"in s&&s.escaped?s.text:be(s.text)}},xr=class{strong({text:s}){return s}em({text:s}){return s}codespan({text:s}){return s}del({text:s}){return s}html({text:s}){return s}text({text:s}){return s}link({text:s}){return""+s}image({text:s}){return""+s}br(){return""}checkbox({raw:s}){return s}},fe=class cr{options;renderer;textRenderer;constructor(e){this.options=e||He,this.options.renderer=this.options.renderer||new Ys,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new xr}static parse(e,t){return new cr(t).parse(e)}static parseInline(e,t){return new cr(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let i=0;i<e.length;i++){let r=e[i];if(this.options.extensions?.renderers?.[r.type]){let o=r,l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){t+=l||"";continue}}let n=r;switch(n.type){case"space":{t+=this.renderer.space(n);break}case"hr":{t+=this.renderer.hr(n);break}case"heading":{t+=this.renderer.heading(n);break}case"code":{t+=this.renderer.code(n);break}case"table":{t+=this.renderer.table(n);break}case"blockquote":{t+=this.renderer.blockquote(n);break}case"list":{t+=this.renderer.list(n);break}case"checkbox":{t+=this.renderer.checkbox(n);break}case"html":{t+=this.renderer.html(n);break}case"def":{t+=this.renderer.def(n);break}case"paragraph":{t+=this.renderer.paragraph(n);break}case"text":{t+=this.renderer.text(n);break}default:{let o='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let i="";for(let r=0;r<e.length;r++){let n=e[r];if(this.options.extensions?.renderers?.[n.type]){let l=this.options.extensions.renderers[n.type].call({parser:this},n);if(l!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(n.type)){i+=l||"";continue}}let o=n;switch(o.type){case"escape":{i+=t.text(o);break}case"html":{i+=t.html(o);break}case"link":{i+=t.link(o);break}case"image":{i+=t.image(o);break}case"checkbox":{i+=t.checkbox(o);break}case"strong":{i+=t.strong(o);break}case"em":{i+=t.em(o);break}case"codespan":{i+=t.codespan(o);break}case"br":{i+=t.br(o);break}case"del":{i+=t.del(o);break}case"text":{i+=t.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return i}},cs=class{options;block;constructor(s){this.options=s||He}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(s){return s}postprocess(s){return s}processAllTokens(s){return s}emStrongMask(s){return s}provideLexer(s=this.block){return s?de.lex:de.lexInline}provideParser(s=this.block){return s?fe.parse:fe.parseInline}},ds=class{defaults=hr();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=fe;Renderer=Ys;TextRenderer=xr;Lexer=de;Tokenizer=kt;Hooks=cs;constructor(...s){this.use(...s)}walkTokens(s,e){let t=[];for(let i of s)switch(t=t.concat(e.call(this,i)),i.type){case"table":{let r=i;for(let n of r.header)t=t.concat(this.walkTokens(n.tokens,e));for(let n of r.rows)for(let o of n)t=t.concat(this.walkTokens(o.tokens,e));break}case"list":{let r=i;t=t.concat(this.walkTokens(r.items,e));break}default:{let r=i;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(n=>{let o=r[n].flat(1/0);t=t.concat(this.walkTokens(o,e))}):r.tokens&&(t=t.concat(this.walkTokens(r.tokens,e)))}}return t}use(...s){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return s.forEach(t=>{let i={...t};if(i.async=this.defaults.async||i.async||!1,t.extensions&&(t.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let n=e.renderers[r.name];n?e.renderers[r.name]=function(...o){let l=r.renderer.apply(this,o);return l===!1&&(l=n.apply(this,o)),l}:e.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let n=e[r.level];n?n.unshift(r.tokenizer):e[r.level]=[r.tokenizer],r.start&&(r.level==="block"?e.startBlock?e.startBlock.push(r.start):e.startBlock=[r.start]:r.level==="inline"&&(e.startInline?e.startInline.push(r.start):e.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(e.childTokens[r.name]=r.childTokens)}),i.extensions=e),t.renderer){let r=this.defaults.renderer||new Ys(this.defaults);for(let n in t.renderer){if(!(n in r))throw new Error(`renderer '${n}' does not exist`);if(["options","parser"].includes(n))continue;let o=n,l=t.renderer[o],a=r[o];r[o]=(...c)=>{let h=l.apply(r,c);return h===!1&&(h=a.apply(r,c)),h||""}}i.renderer=r}if(t.tokenizer){let r=this.defaults.tokenizer||new kt(this.defaults);for(let n in t.tokenizer){if(!(n in r))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;let o=n,l=t.tokenizer[o],a=r[o];r[o]=(...c)=>{let h=l.apply(r,c);return h===!1&&(h=a.apply(r,c)),h}}i.tokenizer=r}if(t.hooks){let r=this.defaults.hooks||new cs;for(let n in t.hooks){if(!(n in r))throw new Error(`hook '${n}' does not exist`);if(["options","block"].includes(n))continue;let o=n,l=t.hooks[o],a=r[o];cs.passThroughHooks.has(n)?r[o]=c=>{if(this.defaults.async&&cs.passThroughHooksRespectAsync.has(n))return(async()=>{let u=await l.call(r,c);return a.call(r,u)})();let h=l.call(r,c);return a.call(r,h)}:r[o]=(...c)=>{if(this.defaults.async)return(async()=>{let u=await l.apply(r,c);return u===!1&&(u=await a.apply(r,c)),u})();let h=l.apply(r,c);return h===!1&&(h=a.apply(r,c)),h}}i.hooks=r}if(t.walkTokens){let r=this.defaults.walkTokens,n=t.walkTokens;i.walkTokens=function(o){let l=[];return l.push(n.call(this,o)),r&&(l=l.concat(r.call(this,o))),l}}this.defaults={...this.defaults,...i}}),this}setOptions(s){return this.defaults={...this.defaults,...s},this}lexer(s,e){return de.lex(s,e??this.defaults)}parser(s,e){return fe.parse(s,e??this.defaults)}parseMarkdown(s){return(e,t)=>{let i={...t},r={...this.defaults,...i},n=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&i.async===!1)return n(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return n(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return n(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=s),r.async)return(async()=>{let o=r.hooks?await r.hooks.preprocess(e):e,l=await(r.hooks?await r.hooks.provideLexer(s):s?de.lex:de.lexInline)(o,r),a=r.hooks?await r.hooks.processAllTokens(l):l;r.walkTokens&&await Promise.all(this.walkTokens(a,r.walkTokens));let c=await(r.hooks?await r.hooks.provideParser(s):s?fe.parse:fe.parseInline)(a,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(n);try{r.hooks&&(e=r.hooks.preprocess(e));let o=(r.hooks?r.hooks.provideLexer(s):s?de.lex:de.lexInline)(e,r);r.hooks&&(o=r.hooks.processAllTokens(o)),r.walkTokens&&this.walkTokens(o,r.walkTokens);let l=(r.hooks?r.hooks.provideParser(s):s?fe.parse:fe.parseInline)(o,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(o){return n(o)}}}onError(s,e){return t=>{if(t.message+=`
72
+ Please report this to https://github.com/markedjs/marked.`,s){let i="<p>An error occurred:</p><pre>"+be(t.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(t);throw t}}},Fe=new ds;function N(s,e){return Fe.parse(s,e)}N.options=N.setOptions=function(s){return Fe.setOptions(s),N.defaults=Fe.defaults,po(N.defaults),N};N.getDefaults=hr;N.defaults=He;function Lu(...s){return Fe.use(...s),N.defaults=Fe.defaults,po(N.defaults),N}N.use=Lu;N.walkTokens=function(s,e){return Fe.walkTokens(s,e)};N.parseInline=Fe.parseInline;N.Parser=fe;N.parser=fe.parse;N.Renderer=Ys;N.TextRenderer=xr;N.Lexer=de;N.lexer=de.lex;N.Tokenizer=kt;N.Hooks=cs;N.parse=N;var fg=N.options,pg=N.setOptions,gg=N.walkTokens,mg=N.parseInline;var xg=fe.parse,bg=de.lex;import{spawn as Eu}from"child_process";import{readdirSync as Pu,statSync as Mo}from"fs";import{homedir as Io}from"os";import{basename as yr,dirname as Xs,join as Ee}from"path";function To(s,e){let t=0,i=-1,r=0;for(let n of e)i===n-1?(r++,t-=r*5):(r=0,i>=0&&(t+=(n-i-1)*2)),(n===0||/[\s\-_./:]/.test(s[n-1]))&&(t-=10),t+=n*.1,i=n;return t}function vo(s,e){if(s.length===0)return{matches:!0,score:0};if(s.length>e.length)return{matches:!1,score:0};let t=[],i=-1;for(let n=0;n<s.length;n++){let o=e.indexOf(s[n],i+1);if(o===-1)return{matches:!1,score:0};t.push(o),i=o}let r=To(e,t);for(let n=e.indexOf(s);n!==-1;n=e.indexOf(s,n+1)){for(let o=0;o<t.length;o++)t[o]=n+o;r=Math.min(r,To(e,t))}return s===e&&(r-=100),{matches:!0,score:r}}function br(s,e){let t=s.toLowerCase(),i=e.toLowerCase(),r=vo(t,i);if(r.matches)return r;let n=t.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/),o=t.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/),l=n?`${n.groups?.digits??""}${n.groups?.letters??""}`:o?`${o.groups?.letters??""}${o.groups?.digits??""}`:"";if(!l)return r;let a=vo(l,i);return a.matches?{matches:!0,score:a.score+5}:r}function Ke(s,e,t){if(!e.trim())return s;let i=e.trim().split(/[\s/]+/).filter(n=>n.length>0);if(i.length===0)return s;let r=[];for(let n of s){let o=t(n),l=0,a=!0;for(let c of i){let h=br(c,o);if(h.matches)l+=h.score;else{a=!1;break}}a&&r.push({item:n,totalScore:l})}return r.sort((n,o)=>n.totalScore-o.totalScore),r.map(n=>n.item)}var Bo=new Set([" "," ",'"',"'","="]),Do=new RegExp(`${$s.source}$`,"u"),No={"(":")","[":"]","{":"}","<":">","`":"`"};function Te(s){return s.replace(/\\/g,"/")}function Ro(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $u(s){let e=Te(s);if(!e.includes("/"))return Ro(e);let t=e.endsWith("/"),i=e.replace(/^\/+|\/+$/g,"");if(!i)return e;let r="[\\\\/]",o=i.split("/").filter(Boolean).map(l=>Ro(l)).join(r);return t&&(o+=r),o}function Ao(s){let e=-1,t=0;for(let i of s)t+=i.length,(Bo.has(i)||lt.test(i))&&(e=t-1);return e}function Lo(s){let e=s;for(;e.length>0;){let t=No[e[0]];if(!t||e.includes(t,1))break;e=e.slice(1)}return e}function _u(s){let e=!1,t=-1;for(let i=0;i<s.length;i+=1)s[i]==='"'&&(e=!e,e&&(t=i));return e?t:null}function Eo(s,e){let t=e;for(;t>0&&No[s[t-1]];)t-=1;return Bo.has(s[t-1]??"")||Do.test(s.slice(0,t))}function Po(s){let e=_u(s);return e===null?null:e>0&&s[e-1]==="@"?Eo(s,e-1)?s.slice(e-1):null:Eo(s,e)?s.slice(e):null}function $o(s){return s.startsWith('@"')?{rawPrefix:s.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:s.startsWith('"')?{rawPrefix:s.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:s.startsWith("@")?{rawPrefix:s.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:s,isAtPrefix:!1,isQuotedPrefix:!1}}function _o(s,e){let t=e.isQuotedPrefix||lt.test(s),i=e.isAtPrefix?"@":"";return t?`${`${i}"`}${s}"`:`${i}${s}`}async function Oo(s,e,t,i,r,n){let o=["--base-directory",s,"--max-results",String(i),"--type","f","--type","d","--follow","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];return n!==void 0&&o.push("--max-depth",String(n)),Te(t).includes("/")&&o.push("--full-path"),t&&o.push($u(t)),await new Promise(l=>{if(r.aborted){l([]);return}let a=Eu(e,o,{stdio:["ignore","pipe","pipe"]}),c="",h=!1,u=f=>{h||(h=!0,r.removeEventListener("abort",d),l(f))},d=()=>{a.exitCode===null&&a.kill("SIGKILL")};r.addEventListener("abort",d,{once:!0}),a.stdout.setEncoding("utf-8"),a.stdout.on("data",f=>{c+=f}),a.on("error",()=>{u([])}),a.on("close",f=>{if(r.aborted||f!==0||!c){u([]);return}let p=c.trim().split(`
73
+ `).filter(Boolean),g=[];for(let x of p){let m=Te(x),w=m.endsWith("/"),b=w?m.slice(0,-1):m;b===".git"||b.startsWith(".git/")||b.includes("/.git/")||g.push({path:m,isDirectory:w})}u(g)})})}var Zs=class{commands;basePath;fdPath;constructor(e=[],t,i=null){this.commands=e,this.basePath=t,this.fdPath=i}async getSuggestions(e,t,i,r){let o=(e[t]||"").slice(0,i),l=this.extractAtPrefix(o);if(l){let{rawPrefix:u,isQuotedPrefix:d}=$o(l),f=await this.getFuzzyFileSuggestions(u,{isQuotedPrefix:d,signal:r.signal});return f.length===0?null:{items:f,prefix:l}}let a=o.trimStart();if(!r.force&&a.startsWith("/")){let u=a.indexOf(" ");if(u===-1){let x=a.slice(1),m=this.commands.map(y=>{let C="name"in y?y.name:y.value,I="argumentHint"in y&&y.argumentHint?y.argumentHint:void 0,A=y.description??"",T=I?A?`${I} \u2014 ${A}`:I:A;return{name:C,label:C,description:T||void 0}}),w=Ke(m,x,y=>y.name.startsWith("skill:")?y.name.slice(6):y.name),b=new Set(w),k=Ke(m.filter(y=>y.name.startsWith("skill:")&&!b.has(y)),x,y=>y.name),v=[...w,...k].map(y=>({value:y.name,label:y.label,...y.description&&{description:y.description}}));return v.length===0?null:{items:v,prefix:a}}let d=a.slice(1,u),f=a.slice(u+1),p=this.commands.find(x=>("name"in x?x.name:x.value)===d);if(!p||!("getArgumentCompletions"in p)||!p.getArgumentCompletions)return null;let g=await p.getArgumentCompletions(f);return!Array.isArray(g)||g.length===0?null:{items:g,prefix:f}}let c=this.extractPathPrefix(o,r.force??!1);if(c===null)return null;let h=this.getFileSuggestions(c);return h.length===0?null:{items:h,prefix:c}}applyCompletion(e,t,i,r,n){let o=e[t]||"",l=o.slice(0,i-n.length),a=o.slice(i),c=n.startsWith('"')||n.startsWith('@"'),h=a.startsWith('"'),u=r.value.endsWith('"'),d=c&&u&&h?a.slice(1):a;if(n.startsWith("/")&&l.trim()===""&&!n.slice(1).includes("/")){let k=`${l}/${r.value} ${d}`,v=[...e];return v[t]=k,{lines:v,cursorLine:t,cursorCol:l.length+r.value.length+2}}if(n.startsWith("@")){let k=r.label.endsWith("/"),v=k?"":" ",y=`${l+r.value}${v}${d}`,C=[...e];C[t]=y;let I=r.value.endsWith('"'),A=k&&I?r.value.length-1:r.value.length;return{lines:C,cursorLine:t,cursorCol:l.length+A+v.length}}let p=o.slice(0,i);if(p.includes("/")&&p.includes(" ")){let k=l+r.value+d,v=[...e];v[t]=k;let y=r.label.endsWith("/"),C=r.value.endsWith('"'),I=y&&C?r.value.length-1:r.value.length;return{lines:v,cursorLine:t,cursorCol:l.length+I}}let g=l+r.value+d,x=[...e];x[t]=g;let m=r.label.endsWith("/"),w=r.value.endsWith('"'),b=m&&w?r.value.length-1:r.value.length;return{lines:x,cursorLine:t,cursorCol:l.length+b}}extractAtPrefix(e){let t=Po(e);if(t?.startsWith('@"'))return t;let i=Ao(e),r=Lo(i===-1?e:e.slice(i+1));return r.startsWith("@")?r:null}extractPathPrefix(e,t=!1){let i=Po(e);if(i)return i;let r=Ao(e),n=Lo(r===-1?e:e.slice(r+1));return t||n.includes("/")||n.startsWith(".")||n.startsWith("~/")||n===""&&e!==""&&Do.test(e)?n:null}expandHomePath(e){if(e.startsWith("~/")){let t=Ee(Io(),e.slice(2));return e.endsWith("/")&&!t.endsWith("/")?`${t}/`:t}else if(e==="~")return Io();return e}resolveScopedFuzzyQuery(e){let t=Te(e),i=t.lastIndexOf("/");if(i===-1)return null;let r=t.slice(0,i+1),n=t.slice(i+1),o;r.startsWith("~/")?o=this.expandHomePath(r):r.startsWith("/")?o=r:o=Ee(this.basePath,r);try{if(!Mo(o).isDirectory())return null}catch{return null}return{baseDir:o,query:n,displayBase:r}}scopedPathForDisplay(e,t){let i=Te(t);return e==="/"?`/${i}`:`${Te(e)}${i}`}getFileSuggestions(e){try{let t,i,{rawPrefix:r,isAtPrefix:n,isQuotedPrefix:o}=$o(e),l=r;if(l.startsWith("~")&&(l=this.expandHomePath(l)),r===""||r==="./"||r==="../"||r==="~"||r==="~/"||r==="/"||n&&r==="")r.startsWith("~")||l.startsWith("/")?t=l:t=Ee(this.basePath,l),i="";else if(r.endsWith("/"))r.startsWith("~")||l.startsWith("/")?t=l:t=Ee(this.basePath,l),i="";else{let u=Xs(l),d=yr(l);r.startsWith("~")||l.startsWith("/")?t=u:t=Ee(this.basePath,u),i=d}let c=Pu(t,{withFileTypes:!0}),h=[];for(let u of c){if(!u.name.toLowerCase().startsWith(i.toLowerCase()))continue;let d=u.isDirectory();if(!d&&u.isSymbolicLink())try{let w=Ee(t,u.name);d=Mo(w).isDirectory()}catch{}let f,p=u.name,g=r;if(g.endsWith("/"))f=g+p;else if(g.includes("/")||g.includes("\\"))if(g.startsWith("~/")){let w=g.slice(2),b=Xs(w);f=`~/${b==="."?p:Ee(b,p)}`}else if(g.startsWith("/")){let w=Xs(g);w==="/"?f=`/${p}`:f=`${w}/${p}`}else f=Ee(Xs(g),p),g.startsWith("./")&&!f.startsWith("./")&&(f=`./${f}`);else g.startsWith("~")?f=`~/${p}`:f=p;f=Te(f);let x=d?`${f}/`:f,m=_o(x,{isDirectory:d,isAtPrefix:n,isQuotedPrefix:o});h.push({value:m,label:p+(d?"/":"")})}return h.sort((u,d)=>{let f=u.label.endsWith("/"),p=d.label.endsWith("/");return f&&!p?-1:!f&&p?1:u.label.localeCompare(d.label)}),h}catch{return[]}}scoreEntry(e,t,i){let n=yr(e).toLowerCase(),o=t.toLowerCase(),l=0;return n===o?l=100:n.startsWith(o)?l=80:n.includes(o)?l=50:e.toLowerCase().includes(o)&&(l=30),i&&l>0&&(l+=10),l}async getBaseDirSuggestions(e,t,i){return!this.fdPath||i.aborted?[]:await Oo(e,this.fdPath,t,100,i,1)}async getFuzzyFileSuggestions(e,t){if(!this.fdPath||t.signal.aborted)return[];try{let i=this.resolveScopedFuzzyQuery(e),r=i?.baseDir??this.basePath,n=i?.query??e,o=await this.getBaseDirSuggestions(r,n,t.signal),l=await Oo(r,this.fdPath,n,100,t.signal),a=new Set(o.map(f=>f.path)),c=[...o,...l.filter(f=>a.has(f.path)?!1:(a.add(f.path),!0))];if(t.signal.aborted)return[];let h=c.map(f=>({...f,score:n?this.scoreEntry(f.path,n,f.isDirectory):1})).filter(f=>f.score>0);h.sort((f,p)=>{let g=p.score-f.score;if(g!==0)return g;let x=Te(f.path).split("/").filter(Boolean).length,m=Te(p.path).split("/").filter(Boolean).length,w=x-m;if(w!==0)return w;let b=f.path.length-p.path.length;return b!==0?b:f.path.localeCompare(p.path)});let u=h.slice(0,20),d=[];for(let{path:f,isDirectory:p}of u){let g=p?f.slice(0,-1):f,x=i?this.scopedPathForDisplay(i.displayBase,g):g,m=yr(g),w=p?`${x}/`:x,b=_o(w,{isDirectory:p,isAtPrefix:!0,isQuotedPrefix:t.isQuotedPrefix});d.push({value:b,label:m+(p?"/":""),description:x})}return d}catch{return[]}}shouldTriggerFileCompletion(e,t,i){let n=(e[t]||"").slice(0,i);return!(n.trim().startsWith("/")&&!n.trim().includes(" "))}};import{performance as ai}from"node:perf_hooks";function Ou(s){let e=s.startsWith("#")?s.slice(1):s,t=parseInt(e.slice(0,2),16),i=parseInt(e.slice(2,4),16),r=parseInt(e.slice(4,6),16);return{r:t,g:i,b:r}}function Ct(s){if(!/^[0-9a-f]+$/i.test(s))return;let e=16**s.length-1;if(!(e<=0))return Math.round(parseInt(s,16)/e*255)}var Bu=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,Du=/^(?:\x1b\[\?997;(1|2)n)+$/;function Wo(s){let e=s.match(Bu);return e?{target:e[1]==="10"?"foreground":e[1]==="11"?"background":Number.parseInt(e[2],10),rgb:Nu(e[3])}:void 0}function Nu(s){let e=s.trim();if(e.startsWith("#")){let c=e.slice(1);if(/^[0-9a-f]{6}$/i.test(c))return Ou(e);if(/^[0-9a-f]{12}$/i.test(c)){let h=Ct(c.slice(0,4)),u=Ct(c.slice(4,8)),d=Ct(c.slice(8,12));return h!==void 0&&u!==void 0&&d!==void 0?{r:h,g:u,b:d}:void 0}return}let t=e.replace(/^rgba?:/i,""),[i,r,n]=t.split("/");if(i===void 0||r===void 0||n===void 0)return;let o=Ct(i),l=Ct(r),a=Ct(n);return o!==void 0&&l!==void 0&&a!==void 0?{r:o,g:l,b:a}:void 0}function Js(s){let e=s.match(Du);if(e)return e[1]==="2"?"light":"dark"}import{execSync as Wu}from"node:child_process";import{homedir as Fu}from"node:os";import{isAbsolute as Hu}from"node:path";import{pathToFileURL as Ku}from"node:url";var Mt=null,vt={},Vo={widthPx:9,heightPx:18};function fs(){return Vo}function ei(s){Vo=s}function Vu(){try{return Wu("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",timeout:250,stdio:["ignore","pipe","ignore"]}).split(",").map(e=>e.trim()).includes("hyperlinks")}catch{return!1}}function qu(s){let e=process.env.TERM_PROGRAM?.toLowerCase()||"",t=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",i=process.env.TERM?.toLowerCase()||"",r=process.env.COLORTERM?.toLowerCase()||"",n=r==="truecolor"||r==="24bit"||i.endsWith("-direct"),o=process.platform==="win32";return process.env.TMUX||i.startsWith("tmux")?{images:null,trueColor:n,hyperlinks:s()}:i.startsWith("screen")?{images:null,trueColor:n,hyperlinks:!1}:e==="herdr"?{images:"kitty",trueColor:n,hyperlinks:!0}:e==="rex"?{images:"kitty",trueColor:!0,hyperlinks:!0}:e==="orca"&&process.env.ORCA_IMAGE_PROTOCOL==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.KITTY_WINDOW_ID||e==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:e==="ghostty"||i.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||e==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:e==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||e==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:e==="alacritty"||i.startsWith("alacritty")||process.env.ALACRITTY_WINDOW_ID||e==="vscode"||e==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:t==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:o?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:n,hyperlinks:!1}}function Fo(s){return s==="1"?!0:s==="0"?!1:void 0}function Sr(s=Vu){let e=Fo(process.env.PI_HYPERLINKS),t=qu(e===void 0?s:()=>e),i=process.env.PI_IMAGE_PROTOCOL?.toLowerCase(),r=i==="kitty"||i==="iterm2"?i:i==="none"||i==="0"?null:void 0,n=Fo(process.env.PI_TRUE_COLOR);return{...t,...r!==void 0?{images:r}:{},...n!==void 0?{trueColor:n}:{},...e!==void 0?{hyperlinks:e}:{}}}function se(){if(!Mt){let s=vt.hyperlinks;Mt={...Sr(s===void 0?void 0:()=>s),...vt}}return Mt}function ps(s=se()){return s.trueColor?"truecolor":"256color"}function qo(){Mt=null}function Uo(s){vt.images===s.images&&vt.trueColor===s.trueColor&&vt.hyperlinks===s.hyperlinks||(vt={...s},Mt=null)}function gs(s){Mt=s}var Ve="\x1B_G",wr="\x1B]1337;File=";function W(s){return s.startsWith(Ve)||s.startsWith(wr)?!0:s.includes(Ve)||s.includes(wr)}function zo(s){let e=s.indexOf(Ve);if(e!==-1){let l=/\x1b_G([^;]*);/.exec(s)?.[1]??"",a=/(?:^|,)c=(\d+)(?:,|$)/.exec(l)?.[1],c=a===void 0?ri(l)?.columns:Number.parseInt(a,10),h=S(s.slice(0,e));return{firstRow:0,lastRow:(Mr(s)??1)-1,startCol:h,endCol:h+(c??1/0)}}let t=s.indexOf(wr);if(t===-1)return;let i=s.slice(0,t),r=/\x1b\[(\d+)A$/.exec(i),n=/[;=]width=(\d+)[;:]/.exec(s.slice(t))?.[1],o=S(r?i.slice(0,r.index):i);return{firstRow:r?-Number.parseInt(r[1],10):0,lastRow:0,startCol:o,endCol:o+(n===void 0?1/0:Number.parseInt(n,10))}}function jo(s){return s.replace(/\x1b_G[^\x1b]*\x1b\\/g,"").replace(/(?:\x1b\[\d+A)?\x1b\]1337;File=[^\x07]*\x07/g,"")}function ti(){return Math.floor(Math.random()*4294967294)+1}function Cr(s,e={}){let i=["a=T","f=100","q=2"];if(e.moveCursor===!1&&i.push("C=1"),e.columns&&i.push(`c=${e.columns}`),e.rows&&i.push(`r=${e.rows}`),e.imageId&&i.push(`i=${e.imageId}`),s.length<=4096)return`\x1B_G${i.join(",")};${s}\x1B\\`;let r=[],n=0,o=!0;for(;n<s.length;){let l=s.slice(n,n+4096),a=n+4096>=s.length;o?(r.push(`\x1B_G${i.join(",")},m=1;${l}\x1B\\`),o=!1):a?r.push(`\x1B_Gm=0;${l}\x1B\\`):r.push(`\x1B_Gm=1;${l}\x1B\\`),n+=4096}return r.join("")}function It(s){return`\x1B_Ga=d,d=I,i=${s},q=2\x1B\\`}function si(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}function Tr(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function vr(s,e={}){let t=[`inline=${e.inline!==!1?1:0}`,`size=${Buffer.byteLength(s,"base64")}`];if(e.width!==void 0&&t.push(`width=${e.width}`),e.height!==void 0&&t.push(`height=${e.height}`),e.name){let i=Buffer.from(e.name).toString("base64");t.push(`name=${i}`)}return e.preserveAspectRatio===!1&&t.push("preserveAspectRatio=0"),`\x1B]1337;File=${t.join(";")}:${s}\x07`}var Tt=new Map,Ho=0,kr=0;function Uu(s){if(Ho+=1,kr=Math.max(kr,s.rows),Tt.delete(s.imageId),Tt.set(s.imageId,{...s,transmissionGeneration:Ho}),Tt.size>1e3){let e=Tt.keys().next().value;e!==void 0&&Tt.delete(e)}}function ii(){return kr}function ri(s){let e=/(?:^|,)i=(\d+)(?:,|$)/.exec(s)?.[1];return e===void 0?void 0:Tt.get(Number.parseInt(e,10))}function zu(s){let e=/\x1b_G([^;]*);/.exec(s)?.[1];return e===void 0?void 0:ri(e)}function Go(s){let e=/(?:^|,)r=(\d+)(?:,|$)/.exec(s)?.[1];if(e===void 0)return;let t=Number.parseInt(e,10);return t>0?t:void 0}function ju(s,e){return Go(s)??e}function ni(s){let e=zu(s);if(e)return{imageId:e.imageId,columns:e.columns,rows:e.rows,widthPx:e.widthPx,heightPx:e.heightPx}}var Gu=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function Mr(s){let e=/\x1b_G([^;]*);/.exec(s)?.[1];if(e===void 0)return;let t=Go(e);return t!==void 0?t:ri(e)?.rows}function Yo(s){let e=/\x1b_G([^;]*);/.exec(s);if(!e)return;let t=ri(e[1]);if(!t)return;let i=e.index,r=e[1],n;for(;;){let a=s.indexOf("\x1B\\",i+Ve.length);if(a===-1)return;if(n=a+2,!/(?:^|,)m=1(?:,|$)/.test(r))break;if(i=n,!s.startsWith(Ve,i))return;let c=s.indexOf(";",i+Ve.length);if(c===-1)return;r=s.slice(i+Ve.length,c)}let l=`\x1B_Ga=p,q=2,${e[1].split(",").filter(a=>Gu.has(a.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:t.imageId,transmissionGeneration:t.transmissionGeneration,transmissionBytes:n-e.index,estimatedDecodedBytes:t.widthPx*t.heightPx*4,rows:ju(e[1],t.rows),sequence:l,replacementLine:`${s.slice(0,e.index)}${l}${s.slice(n)}`}}function Ir(s,e,t){let i=ni(s),r=/\x1b_G([^;]*);/.exec(s);if(!i||!r||e<0||e>=i.rows||t<=0)return s;let n=Math.min(t,i.rows-e);if(e===0&&n===i.rows)return s;let o=Math.floor(i.heightPx*e/i.rows),l=Math.ceil(i.heightPx*(e+n)/i.rows),a=Math.max(1,Math.min(i.heightPx,l)-o),c=r[1].split(",").filter(h=>!/^[yhr]=/.test(h));return c.push(`y=${o}`,`h=${a}`,`r=${n}`),`${s.slice(0,r.index)}\x1B_G${c.join(",")};${s.slice(r.index+r[0].length)}`}function Ko(s,e){if(s<=1)return s;let t=s-1,i=Math.max(s/e,e/s);return Math.max(t/e,e/t)<i?t:s}function Qo(s,e,t,i={widthPx:9,heightPx:18},r=!1){let n=Math.max(1,Math.floor(e)),o=t===void 0?void 0:Math.max(1,Math.floor(t)),l=Math.max(1,s.widthPx),a=Math.max(1,s.heightPx),c=n*i.widthPx/l,h=o===void 0?c:o*i.heightPx/a,u=Math.min(c,h),d=l*u,f=a*u,p=Math.max(1,Math.min(n,Math.ceil(d/i.widthPx))),g=f/i.heightPx,x=Math.max(1,Math.ceil(g));if(o!==void 0&&(x=Math.min(o,x)),!r)return{columns:p,rows:x};if(c<=h){let m=p*i.widthPx*a/(l*i.heightPx);x=Ko(x,m)}else{let m=x*i.heightPx*l/(a*i.widthPx);p=Ko(p,m)}return{columns:p,rows:x}}function Xo(s,e,t={widthPx:9,heightPx:18}){return Qo(s,e,void 0,t).rows}function ms(s){try{let e=Buffer.from(s,"base64");if(e.length<24||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return null;let t=e.readUInt32BE(16),i=e.readUInt32BE(20);return{widthPx:t,heightPx:i}}catch{return null}}function Rr(s){try{let e=Buffer.from(s,"base64");if(e.length<2||e[0]!==255||e[1]!==216)return null;let t=2;for(;t<e.length-9;){if(e[t]!==255){t++;continue}let i=e[t+1];if(i>=192&&i<=194){let n=e.readUInt16BE(t+5);return{widthPx:e.readUInt16BE(t+7),heightPx:n}}if(t+3>=e.length)return null;let r=e.readUInt16BE(t+2);if(r<2)return null;t+=2+r}return null}catch{return null}}function Ar(s){try{let e=Buffer.from(s,"base64");if(e.length<10)return null;let t=e.slice(0,6).toString("ascii");if(t!=="GIF87a"&&t!=="GIF89a")return null;let i=e.readUInt16LE(6),r=e.readUInt16LE(8);return{widthPx:i,heightPx:r}}catch{return null}}function Lr(s){try{let e=Buffer.from(s,"base64");if(e.length<30)return null;let t=e.slice(0,4).toString("ascii"),i=e.slice(8,12).toString("ascii");if(t!=="RIFF"||i!=="WEBP")return null;let r=e.slice(12,16).toString("ascii");if(r==="VP8 "){if(e.length<30)return null;let n=e.readUInt16LE(26)&16383,o=e.readUInt16LE(28)&16383;return{widthPx:n,heightPx:o}}else if(r==="VP8L"){if(e.length<25)return null;let n=e.readUInt32LE(21),o=(n&16383)+1,l=(n>>14&16383)+1;return{widthPx:o,heightPx:l}}else if(r==="VP8X"){if(e.length<30)return null;let n=(e[24]|e[25]<<8|e[26]<<16)+1,o=(e[27]|e[28]<<8|e[29]<<16)+1;return{widthPx:n,heightPx:o}}return null}catch{return null}}function oi(s,e){return e==="image/png"?ms(s):e==="image/jpeg"?Rr(s):e==="image/gif"?Ar(s):e==="image/webp"?Lr(s):null}function li(s,e,t={}){let i=se();if(!i.images)return null;let r=t.maxWidthCells??80,n=Qo(e,r,t.maxHeightCells,fs(),i.images==="kitty");return i.images==="kitty"?(t.imageId!==void 0&&Uu({imageId:t.imageId,columns:n.columns,rows:n.rows,widthPx:e.widthPx,heightPx:e.heightPx}),{sequence:Cr(s,{columns:n.columns,rows:n.rows,imageId:t.imageId,moveCursor:t.moveCursor}),columns:n.columns,rows:n.rows,imageId:t.imageId}):i.images==="iterm2"?{sequence:vr(s,{width:n.columns,height:"auto",preserveAspectRatio:t.preserveAspectRatio??!0}),columns:n.columns,rows:n.rows}:null}function xs(s,e){return`\x1B]8;;${e}\x1B\\${s}\x1B]8;;\x1B\\`}function Yu(s){let e=Fu();return e&&(s===e||s.startsWith(`${e}/`)||s.startsWith(`${e}\\`))?`~${s.slice(e.length)}`:s}function bs(s,e,t){let i=[];if(t){let r=Yu(t);se().hyperlinks&&Hu(t)?i.push(xs(r,Ku(t).href)):i.push(r)}return i.push(`[${s}]`),e&&i.push(`${e.widthPx}x${e.heightPx}`),`[Image: ${i.join(" ")}]`}function qe(s,e){let t=s.handleMouse?.(e);if(t){if("target"in t){let i=t;return i.focus&&s.handleInput?{...i,focusTarget:s}:i}if(!(!t.handled&&!t.capture&&!t.focus))return{...t,handled:!0,...t.focus?{focusTarget:s}:{},target:{component:s,originX:e.screenX-e.x,originY:e.screenY-e.y,width:e.width,height:e.height}}}}function Jo(s,e){return{...s,x:s.screenX-e.originX,y:s.screenY-e.originY,width:e.width,height:e.height}}var ci=16,Qu=2+ci,Xu=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:ci},(s,e)=>`\x1B]4;${e};?\x07`).join("")}\x1B[c`,Zu=/^\x1b\[\?[\d;]*c$/;function hi(s){return s!==null&&"focused"in s}var Z="\x1B_pi:c\x07",Er="\x1B_pi:fc\x07",el="\x1B_pi:/fc\x07",Ju=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function Pe(s){return`${Er}${s}${el}`}function Zo(s,e){if(s===void 0)return;if(typeof s=="number")return s;let t=s.match(/^(\d+(?:\.\d+)?)%$/);if(t)return Math.floor(e*parseFloat(t[1])/100)}function ed(s,e){if(s===e)return!0;if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]!==e[t])return!1;return!0}function ys(s,e,t){let i=s.map(n=>n.render(e));if(t?.width===e&&t.children.length===s.length&&s.every((n,o)=>n===t.children[o]&&ed(i[o],t.parts[o])))return t;let r=[];for(let n of i)for(let o of n)r.push(o);return{width:e,children:[...s],parts:i,lines:r}}function $r(s,e){let t=0;for(let i=0;i<s.children.length;i++){let r=s.parts[i].length;if(e.y>=t&&e.y<t+r)return qe(s.children[i],{...e,y:e.y-t,height:r});t+=r}}var ae=class{children=[];childLines;addChild(e){this.children.push(e)}removeChild(e){let t=this.children.indexOf(e);t!==-1&&this.children.splice(t,1)}clear(){this.children=[]}invalidate(){for(let e of this.children)e.invalidate?.()}handleMouse(e){if(e.y<0||e.y>=e.height)return;let t=this.childLines?.width===e.width?this.childLines:ys(this.children,e.width,void 0),i=$r(t,e);return i?.focus&&this.handleInput?{...i,focusTarget:this}:i}render(e){return this.childLines=ys(this.children,e,this.childLines),this.childLines.lines}},Pr="\x1B[0m\x1B]8;;\x07";function ye(s,e,t,i,r){if(W(s))return s;let n=t+i,o=Nn(s,t,n,r-n,!0),l=er(e,0,i,!0),a=Math.max(0,t-o.beforeWidth),c=Math.max(0,i-l.width),h=Math.max(t,o.beforeWidth),u=Math.max(i,l.width),d=Math.max(0,r-h-u),f=Math.max(0,d-o.afterWidth),p=o.before+" ".repeat(a)+Pr+l.text+" ".repeat(c)+Pr+o.after+" ".repeat(f);return S(p)<=r?p:H(p,0,r,!0)}function td(s,e,t){if(e.height!==0)for(let i=Math.max(0,t-ii());i<s.length;i++){let r=s[i],n=zo(r);if(!n)continue;let o=i+n.firstRow-t,l=i+n.lastRow-t;o<e.row+e.height&&l>=e.row&&n.startCol<e.col+e.width&&n.endCol>e.col&&(s[i]=jo(r))}}var _r=Symbol.for("@earendil-works/pi-tui/viewport");function tl(s){return s[_r]===!0}var Rt=class s extends ae{terminal;focusedComponent=null;inputListeners=new Set;onDebug;suspendSignalHandler;suspendSignalListener=()=>this.suspendSignalHandler?.();ownsTerminal=!1;suspendSignalListening=!1;renderRequested=!1;contentChanged=!0;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(e,t,i){super(),this.terminal=e,this.logDirectory=i,t!==void 0&&(this.showHardwareCursor=t)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(e){}afterTerminalStop(e){}getExitRestorePrefix(){return`${this.terminalColorSchemeNotificationsEnabled?"\x1B[?2031l":""}\x1B[?25h`}getExitRestoreSuffix(){return""}exitRestoreHandler=()=>{if(!this.stopped)try{this.terminal.restoreOnExit?.(this.getExitRestorePrefix(),this.getExitRestoreSuffix())}catch{}};get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(e){this.showHardwareCursor!==e&&(this.showHardwareCursor=e,e||this.hideTerminalCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(e){this.clearOnShrink=e}getFocusedComponent(){return this.focusedComponent}setFocus(e){this.setFocusInternal({component:e,overlayFocusRestore:"clear"})}setFocusInternal({component:e,overlayFocusRestore:t}){this.contentChanged=!0;let i=this.focusedComponent,r=e,n=i?this.overlayStack.find(c=>c.component===i&&this.isOverlayVisible(c)):void 0,o=r?this.overlayStack.some(c=>c.component===r):!1,l=this.getVisibleOverlayFocusRestore();r&&!o?l.status==="blocked"&&l.blockedBy===i?l.resume.status==="focus-target"||!this.isComponentMounted(l.blockedBy)?r=this.resolveBlockedOverlayFocusResume(l):this.overlayFocusRestore={status:"blocked",overlay:l.overlay,blockedBy:r,resume:l.resume}:n&&l.status!=="inactive"&&l.overlay===n&&!this.isOverlayFocusAncestor(n,r)&&(this.overlayFocusRestore={status:"blocked",overlay:n,blockedBy:r,resume:{status:"restore-overlay"}}):r===null&&(l.status==="blocked"&&l.blockedBy===i?r=this.resolveBlockedOverlayFocusResume(l):t==="clear"&&this.clearOverlayFocusRestore()),hi(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=r,hi(r)&&(r.focused=!0);let a=r?this.overlayStack.find(c=>c.component===r&&this.isOverlayVisible(c)):void 0;a&&(this.overlayFocusRestore={status:"eligible",overlay:a})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"}}clearOverlayFocusRestoreFor(e){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===e&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(e){return e.resume.status==="restore-overlay"?e.overlay.component:(this.clearOverlayFocusRestore(),e.resume.target)}getVisibleOverlayFocusRestore(){let e=this.overlayFocusRestore;return e.status==="inactive"?e:!this.overlayStack.includes(e.overlay)||!this.isOverlayVisible(e.overlay)?{status:"inactive"}:e}isOverlayFocusAncestor(e,t){let i=new Set,r=e.preFocus;for(;r&&!i.has(r);){if(i.add(r),r===t)return!0;r=this.overlayStack.find(n=>n.component===r)?.preFocus??null}return!1}retargetOverlayPreFocus(e){for(let t of this.overlayStack)t!==e&&t.preFocus===e.component&&(t.preFocus=e.preFocus)}getMountedRoots(){return this.children}isComponentMounted(e){return this.getMountedRoots().some(t=>this.containsComponent(t,e))}containsComponent(e,t){return e===t?!0:e instanceof ae?e.children.some(i=>this.containsComponent(i,t)):!1}showOverlay(e,t){let i={component:e,...t===void 0?{}:{options:t},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(i),!t?.nonCapturing&&this.isOverlayVisible(i)&&this.setFocus(e),this.hideTerminalCursor(),this.requestRender(),{hide:()=>{let r=this.overlayStack.indexOf(i);if(r!==-1){if(this.clearOverlayFocusRestoreFor(i),this.retargetOverlayPreFocus(i),this.overlayStack.splice(r,1),this.focusedComponent===e){let n=this.getTopmostVisibleOverlay();this.setFocus(n?.component??i.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}},setHidden:r=>{if(i.hidden!==r){if(i.hidden=r,r){if(this.clearOverlayFocusRestoreFor(i),this.focusedComponent===e){let n=this.getTopmostVisibleOverlay();this.setFocus(n?.component??i.preFocus)}}else!t?.nonCapturing&&this.isOverlayVisible(i)&&(i.focusOrder=++this.focusOrderCounter,this.setFocus(e));this.requestRender()}},isHidden:()=>i.hidden,focus:()=>{!this.overlayStack.includes(i)||!this.isOverlayVisible(i)||(i.focusOrder=++this.focusOrderCounter,this.setFocus(e),this.requestRender())},unfocus:r=>{let n=this.focusedComponent===e,o=this.overlayFocusRestore,l=o.status!=="inactive"&&o.overlay===i;if(!(!n&&!l)){if(o.status==="blocked"&&o.overlay===i&&this.focusedComponent===o.blockedBy){r?this.overlayFocusRestore={status:"blocked",overlay:i,blockedBy:o.blockedBy,resume:{status:"focus-target",target:r.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(i),n||r){let a=this.getTopmostVisibleOverlay(),c=a&&a!==i?a.component:i.preFocus;this.setFocus(r?r.target:c)}this.requestRender()}},isFocused:()=>this.focusedComponent===e,getBounds:()=>{if(!(!this.overlayStack.includes(i)||!this.isOverlayVisible(i)||!i.bounds))return{...i.bounds}}}}hideOverlay(){let e=this.overlayStack[this.overlayStack.length-1];if(e){if(this.clearOverlayFocusRestoreFor(e),this.retargetOverlayPreFocus(e),this.overlayStack.pop(),this.focusedComponent===e.component){let t=this.getTopmostVisibleOverlay();this.setFocus(t?.component??e.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor()}hasOverlay(){return this.overlayStack.some(e=>this.isOverlayVisible(e))}isOverlayFocused(){return this.overlayStack.some(e=>e.component===this.focusedComponent&&this.isOverlayVisible(e))}resolveMouseFocusTarget(e){for(let t=this.overlayStack.length-1;t>=0;t--){let i=this.overlayStack[t];if(this.isOverlayVisible(i)&&this.containsComponent(i.component,e))return i.component}return e}dispatchMouseToOverlay(e){for(let t=this.renderedOverlayLayouts.length-1;t>=0;t--){let i=this.renderedOverlayLayouts[t];if(e.screenX<i.col||e.screenX>=i.col+i.width||e.screenY<i.row||e.screenY>=i.row+i.height)continue;let r=qe(i.entry.component,{...e,x:e.screenX-i.col,y:e.screenY-i.row,width:i.width,height:i.height});return r?{hit:!0,result:r.focus?{...r,focusTarget:i.entry.component}:r}:{hit:!0}}return{hit:!1}}isOverlayVisible(e){return e.hidden?!1:e.options?.visible?e.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let e;for(let t of this.overlayStack)t.options?.nonCapturing||!this.isOverlayVisible(t)||(!e||t.focusOrder>e.focusOrder)&&(e=t);return e}invalidate(){for(let e of this.getMountedRoots())e.invalidate();for(let e of this.overlayStack)e.component.invalidate()}start(){this.stopped=!1,process.off("exit",this.exitRestoreHandler),process.on("exit",this.exitRestoreHandler),this.ownsTerminal=!0,this.updateSuspendSignalListener(),this.beforeTerminalStart(),this.terminal.start(e=>this.handleTerminalInput(e),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.requestRender()}addInputListener(e){return this.inputListeners.add(e),()=>{this.inputListeners.delete(e)}}removeInputListener(e){this.inputListeners.delete(e)}onTerminalColorSchemeChange(e){return this.terminalColorSchemeListeners.add(e),()=>{this.terminalColorSchemeListeners.delete(e)}}setTerminalColorSchemeNotifications(e){this.terminalColorSchemeNotificationsEnabled!==e&&(this.terminalColorSchemeNotificationsEnabled=e,this.stopped||this.terminal.write(e?"\x1B[?2031h":"\x1B[?2031l"))}setSuspendSignalHandler(e){this.suspendSignalHandler=e,this.updateSuspendSignalListener()}updateSuspendSignalListener(){let e=this.ownsTerminal&&this.suspendSignalHandler!==void 0;e!==this.suspendSignalListening&&(this.suspendSignalListening=e,e?process.on("SIGTSTP",this.suspendSignalListener):process.off("SIGTSTP",this.suspendSignalListener))}queryCellSize(){se().images&&this.terminal.write("\x1B[16t")}stop(e={}){this.stopped=!0,process.off("exit",this.exitRestoreHandler),this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(e),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(e),this.ownsTerminal=!1,this.updateSuspendSignalListener()}renderNow(e=!1){e&&this.resetRenderState(),this.contentChanged=!0,this.renderRequested=!1,this.cancelRenderTimer(),this.lastRenderAt=ai.now(),this.doRender()}requestRender(e=!1){if(e){this.resetRenderState(),this.requestImmediateRender();return}this.contentChanged=!0,this.requestViewRender()}requestViewRender(){this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){this.contentChanged=!0,this.cancelRenderTimer(),this.renderRequested=!0,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=!0,process.nextTick(()=>{this.immediateRenderScheduled=!1,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),this.renderRequested=!1,this.lastRenderAt=ai.now(),this.doRender())}))}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let e=ai.now()-this.lastRenderAt,t=Math.max(0,s.MIN_RENDER_INTERVAL_MS-e);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=ai.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},t)}handleTerminalInput(e){if(this.consumeTerminalColorResponse(e)||this.consumeTerminalColorSchemeReport(e))return;if(this.inputListeners.size>0){let r=e;for(let n of this.inputListeners){let o=n(r);if(o?.consume)return;o?.data!==void 0&&(r=o.data)}if(r.length===0)return;e=r}if(this.consumeCellSizeResponse(e))return;if(ue(e,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let t=this.overlayStack.find(r=>r.component===this.focusedComponent);if(t&&!this.isOverlayVisible(t)){let r=this.getTopmostVisibleOverlay();r?this.setFocus(r.component):this.setFocusInternal({component:t.preFocus,overlayFocusRestore:"preserve"})}if(!this.overlayStack.some(r=>r.component===this.focusedComponent)){let r=this.getVisibleOverlayFocusRestore();r.status==="eligible"?this.setFocus(r.overlay.component):r.status==="blocked"&&r.blockedBy!==this.focusedComponent&&(r.resume.status==="restore-overlay"?this.setFocus(r.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(r.resume.target)))}if(this.focusedComponent?.handleInput){if(bt(e)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(e),this.requestImmediateRender()}}consumeTerminalColorResponse(e){let t=this.pendingTerminalColorQueries[0];if(!t)return!1;if(Zu.test(e))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(t),!0;let i=Wo(e);if(!i)return!1;let{target:r,rgb:n}=i,o=String(r);return!t.deliver||t.replied.has(o)||(t.replied.add(o),r==="foreground"?t.foreground=n:r==="background"?t.background=n:r<ci&&(t.palette[r]=n),t.replied.size===Qu&&this.completeTerminalColorQuery(t)),!0}terminalColorQueryResult(e){let t=e.palette.every(i=>i!==void 0)?e.palette:void 0;return{foreground:e.foreground,background:e.background,palette:t}}completeTerminalColorQuery(e){let t=e.deliver;e.deliver=void 0,clearTimeout(e.timer),t?.(this.terminalColorQueryResult(e))}consumeTerminalColorSchemeReport(e){let t=Js(e);if(!t)return!1;for(let i of this.terminalColorSchemeListeners)i(t);return!0}consumeCellSizeResponse(e){let t=e.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!t)return!1;let i=parseInt(t[1],10),r=parseInt(t[2],10);return i<=0||r<=0||(ei({widthPx:r,heightPx:i}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(e,t,i,r){let n=e??{},o=typeof n.margin=="number"?{top:n.margin,right:n.margin,bottom:n.margin,left:n.margin}:n.margin??{},l=Math.max(0,o.top??0),a=Math.max(0,o.right??0),c=Math.max(0,o.bottom??0),h=Math.max(0,o.left??0),u=Math.max(1,i-h-a),d=Math.max(1,r-l-c),f=Zo(n.width,i)??Math.min(80,u);n.minWidth!==void 0&&(f=Math.max(f,n.minWidth)),f=Math.max(1,Math.min(f,u));let p=Zo(n.maxHeight,r);p!==void 0&&(p=Math.max(1,Math.min(p,d)));let g=p!==void 0?Math.min(t,p):t,x,m;if(n.row!==void 0)if(typeof n.row=="string"){let w=n.row.match(/^(\d+(?:\.\d+)?)%$/);if(w){let b=Math.max(0,d-g),k=parseFloat(w[1])/100;x=l+Math.floor(b*k)}else x=this.resolveAnchorRow("center",g,d,l)}else x=n.row;else{let w=n.anchor??"center";x=this.resolveAnchorRow(w,g,d,l)}if(n.col!==void 0)if(typeof n.col=="string"){let w=n.col.match(/^(\d+(?:\.\d+)?)%$/);if(w){let b=Math.max(0,u-f),k=parseFloat(w[1])/100;m=h+Math.floor(b*k)}else m=this.resolveAnchorCol("center",f,u,h)}else m=n.col;else{let w=n.anchor??"center";m=this.resolveAnchorCol(w,f,u,h)}return n.offsetY!==void 0&&(x+=n.offsetY),n.offsetX!==void 0&&(m+=n.offsetX),x=Math.max(l,Math.min(x,r-c-g)),m=Math.max(h,Math.min(m,i-a-f)),{width:f,row:x,col:m,maxHeight:p}}resolveAnchorRow(e,t,i,r){switch(e){case"top-left":case"top-center":case"top-right":return r;case"bottom-left":case"bottom-center":case"bottom-right":return r+i-t;case"left-center":case"center":case"right-center":return r+Math.floor((i-t)/2)}}resolveAnchorCol(e,t,i,r){switch(e){case"top-left":case"left-center":case"bottom-left":return r;case"top-right":case"right-center":case"bottom-right":return r+i-t;case"top-center":case"center":case"bottom-center":return r+Math.floor((i-t)/2)}}compositeOverlays(e,t,i){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],e;let r=[...e];for(let h of this.overlayStack)h.bounds=void 0;let n=[],o=r.length,l=this.overlayStack.filter(h=>this.isOverlayVisible(h));l.sort((h,u)=>h.focusOrder-u.focusOrder);for(let h of l){let{component:u,options:d}=h,{width:f,maxHeight:p}=this.resolveOverlayLayout(d,0,t,i),g=this.resolveFakeCursors(u.render(f));p!==void 0&&g.length>p&&(g=g.slice(0,p));let{row:x,col:m}=this.resolveOverlayLayout(d,g.length,t,i);h.bounds={row:x,col:m,width:f,height:g.length},n.push({entry:h,overlayLines:g,row:x,col:m,w:f}),o=Math.max(o,x+g.length)}this.renderedOverlayLayouts=n.map(({entry:h,row:u,col:d,w:f,overlayLines:p})=>({entry:h,row:u,col:d,width:f,height:p.length}));let a=Math.max(r.length,i,o);for(;r.length<a;)r.push("");let c=Math.max(0,a-i);for(let{overlayLines:h,row:u,col:d,w:f}of n){td(r,{row:u,col:d,width:f,height:h.length},c);for(let p=0;p<h.length;p++){let g=c+u+p;if(g>=0&&g<r.length){let x=S(h[p])>f?H(h[p],0,f,!0):h[p];r[g]=this.compositeLineAt(r[g],x,d,f,t)}}}return r}applyLineResets(e){let t=Pr;for(let i=0;i<e.length;i++){let r=e[i];W(r)||(e[i]=_n(r.replaceAll(Z,""))+t)}return e}compositeLineAt(e,t,i,r,n){return ye(e,t,i,r,n)}extractCursorPosition(e,t){let i=Math.max(0,e.length-t);for(let r=e.length-1;r>=i;r--){let n=e[r],o=n.indexOf(Z);if(o!==-1){let l=n.slice(0,o),a=S(l);return e[r]=n.replaceAll(Z,""),{row:r,col:a}}}return null}resolveFakeCursors(e){return e.map(t=>t.includes(Er)?(this.showHardwareCursor?t.replace(Ju,"$1$2"):t).replaceAll(Er,"\x1B[7m").replaceAll(el,"\x1B[27m"):t)}queryTerminalColors({timeoutMs:e,onLateReply:t}){return new Promise(i=>{let r={palette:Array.from({length:ci},()=>{}),replied:new Set,deliver:i,timer:void 0};r.timer=setTimeout(()=>{r.deliver=t,i(this.terminalColorQueryResult(r))},e),this.pendingTerminalColorQueries.push(r),this.terminal.write(Xu)})}};var ui=class{children=[];paddingX;paddingY;bgFn;cache;childLines;constructor(e=1,t=1,i){this.paddingX=e,this.paddingY=t,this.bgFn=i}addChild(e){this.children.push(e),this.invalidateCache()}removeChild(e){let t=this.children.indexOf(e);t!==-1&&(this.children.splice(t,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(e){this.bgFn=e}setPaddingX(e){this.paddingX=e,this.invalidateCache()}invalidateCache(){this.cache=void 0,this.childLines=void 0}invalidate(){this.invalidateCache();for(let e of this.children)e.invalidate?.()}handleMouse(e){let t=Math.max(1,e.width-this.paddingX*2),i=e.y-this.paddingY,r=e.x-this.paddingX;if(i<0||r<0||r>=t)return;let n=this.childLines?.width===t?this.childLines:ys(this.children,t,void 0);return $r(n,{...e,x:r,y:i,width:t})}render(e){if(this.children.length===0)return[];let t=Math.max(1,e-this.paddingX*2),i=" ".repeat(this.paddingX);this.childLines=ys(this.children,t,this.childLines);let r=this.childLines.lines;if(r.length===0)return[];let n=this.bgFn?this.bgFn("test"):void 0,o=this.cache;if(o?.childLines===r&&o.width===e&&o.bgSample===n)return o.lines;let l=[];for(let a=0;a<this.paddingY;a++)l.push(this.applyBg("",e));for(let a of r)l.push(this.applyBg(i+a,e));for(let a=0;a<this.paddingY;a++)l.push(this.applyBg("",e));return Be(l),this.cache={childLines:r,width:e,bgSample:n,lines:l},l}applyBg(e,t){let i=S(e),r=Math.max(0,t-i),n=e+" ".repeat(r);return this.bgFn?this.bgFn(n):n}};var At=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(e="",t=1,i=1,r){this.text=e,this.paddingX=t,this.paddingY=i,this.customBgFn=r}setText(e){e!==this.text&&(this.text=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0)}setCustomBgFn(e){this.customBgFn=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setPaddingX(e){this.paddingX=e,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;if(!this.text||this.text.trim()===""){let d=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=d,d}let t=this.text.replace(/\t/g," "),i=Math.min(this.paddingX,Math.max(0,Math.floor((e-1)/2))),r=Math.max(1,e-i*2),n=ne(t,r),o=" ".repeat(i),l=" ".repeat(i),a=[];for(let d of n){let f=o+d+l;if(this.customBgFn)a.push(ct(f,e,this.customBgFn));else{let p=S(f),g=Math.max(0,e-p);a.push(f+" ".repeat(g))}}let c=" ".repeat(e),h=[];for(let d=0;d<this.paddingY;d++){let f=this.customBgFn?ct(c,e,this.customBgFn):c;h.push(f)}let u=[...h,...a,...h];return Be(u),this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=u,u.length>0?u:[""]}};var sl=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],il=80,Lt=class extends At{frames=[...sl];intervalMs=il;currentFrame=0;intervalId=null;ui=null;renderIndicatorVerbatim=!1;spinnerColorFn;messageColorFn;message="Loading...";constructor(e,t,i,r="Loading...",n){super("",1,0),this.ui=e,this.spinnerColorFn=t,this.messageColorFn=i,this.message=r,this.setIndicator(n)}render(e){return["",...super.render(e)]}start(){this.updateDisplay(),this.restartAnimation()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}setMessage(e){this.message=e,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}setIndicator(e){this.renderIndicatorVerbatim=e!==void 0,this.frames=e?.frames!==void 0?[...e.frames]:[...sl],this.intervalMs=e?.intervalMs&&e.intervalMs>0?e.intervalMs:il,this.currentFrame=0,this.start()}restartAnimation(){this.stop(),!(this.frames.length<=1)&&(this.intervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},this.intervalMs))}getRenderedIndicator(){let e=this.frames[this.currentFrame]??"";return this.renderIndicatorVerbatim?e:this.spinnerColorFn(e)}updateDisplay(){let e=this.getRenderedIndicator(),t=e.length>0?`${e} `:"";this.setText(`${t}${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender()}};var di=class extends Lt{abortController=new AbortController;onAbort;get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(e){U().matches(e,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var Et=class{ring=[];push(e,t){if(e)if(t.accumulate&&this.ring.length>0){let i=this.ring.pop();this.ring.push(t.prepend?e+i:i+e)}else this.ring.push(e)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let e=this.ring.pop();this.ring.unshift(e)}}get length(){return this.ring.length}};var Pt=class{stack=[];push(e){this.stack.push(structuredClone(e))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};var rl=nt();function fi(s,e,t){if(e<=0)return 0;let i=s.slice(0,e),r=t?.segment,n=t?.isAtomicSegment,o=r?[...r(i)]:[...rl.segment(i)],l=e;for(;o.length>0&&!n?.(o[o.length-1]?.segment||"")&&ee(o[o.length-1]?.segment||"");)l-=o.pop()?.segment.length||0;if(o.length===0)return l;let a=o[o.length-1];if(n?.(a.segment))l-=a.segment.length;else if(a.isWordLike){let c=a.segment,h=[...c.matchAll(new RegExp(Ji,"g"))];if(h.length<=0)l-=c.length;else{let u=h[h.length-1];l-=c.length-(u.index+u[0].length)}}else for(;o.length>0&&!n?.(o[o.length-1]?.segment||"")&&!o[o.length-1]?.isWordLike&&!ee(o[o.length-1]?.segment||"");)l-=o.pop()?.segment.length||0;return l}function pi(s,e,t){if(e>=s.length)return s.length;let i=s.slice(e),r=t?.segment,n=t?.isAtomicSegment,l=(r?r(i):rl.segment(i))[Symbol.iterator](),a=l.next(),c=e;for(;!a.done&&!n?.(a.value.segment)&&ee(a.value.segment);)c+=a.value.segment.length,a=l.next();if(a.done)return c;if(n?.(a.value.segment))c+=a.value.segment.length;else if(a.value.isWordLike)c+=Ji.exec(a.value.segment)?.index??a.value.segment.length;else for(;!a.done&&!n?.(a.value.segment)&&!a.value.isWordLike&&!ee(a.value.segment);)c+=a.value.segment.length,a=l.next();return c}var nl=32,ol=2,sd=10,id=s=>s.replace(/[\r\n]+/g," ").trim(),rd=(s,e,t)=>Math.max(e,Math.min(s,t)),$t=class{capturesViewportInput=!0;items=[];filteredItems=[];selectedIndex=0;mousePressedIndex;maxVisible=5;theme;layout;onSelect;onCancel;onSelectionChange;constructor(e,t,i,r={}){this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=i,this.layout=r}setFilter(e){this.filteredItems=this.items.filter(t=>t.value.toLowerCase().startsWith(e.toLowerCase())),this.selectedIndex=0}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1))}invalidate(){}render(e){let t=[];if(this.filteredItems.length===0)return t.push(this.theme.noMatch(" No matching commands")),t;let i=this.getPrimaryColumnWidth(),{startIndex:r,endIndex:n}=this.getVisibleRange();for(let o=r;o<n;o++){let l=this.filteredItems[o];if(!l)continue;let a=o===this.selectedIndex,c=l.description?id(l.description):void 0;t.push(this.renderItem(l,a,e,c,i))}if(r>0||n<this.filteredItems.length){let o=` (${this.selectedIndex+1}/${this.filteredItems.length})`;t.push(this.theme.scrollInfo(D(o,e-2,"")))}return t}handleMouse(e){if(this.filteredItems.length===0)return;if(e.type==="wheel"&&e.wheelDelta){let n=e.wheelDelta<0?-1:1,o=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+n)),this.selectedIndex!==o&&this.notifySelectionChange(),{handled:!0,render:this.selectedIndex!==o}}if(e.button!=="left"||e.type!=="press"&&e.type!=="click")return;let{startIndex:t,endIndex:i}=this.getVisibleRange(),r=t+e.y;if(!(r<t||r>=i)){if(e.type==="press")return this.mousePressedIndex=r,this.selectedIndex!==r&&(this.selectedIndex=r,this.notifySelectionChange()),{handled:!0,focus:!0};if(e.type==="click"){let n=this.mousePressedIndex??r;this.mousePressedIndex=void 0;let o=this.selectedIndex!==n;this.selectedIndex=n,o&&this.notifySelectionChange();let l=this.filteredItems[this.selectedIndex];return l&&this.onSelect?.(l),{handled:!0}}}}handleInput(e){let t=U(),i=yt(t,e,this.selectedIndex,this.filteredItems.length,this.maxVisible);if(t.matches(e,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(t.matches(e,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(i!==void 0){if(this.filteredItems.length===0||i===this.selectedIndex)return;this.selectedIndex=i,this.notifySelectionChange()}else if(t.matches(e,"tui.select.confirm")){let r=this.filteredItems[this.selectedIndex];r&&this.onSelect&&this.onSelect(r)}else t.matches(e,"tui.select.cancel")&&this.onCancel&&this.onCancel()}getVisibleRange(){let e=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex:e,endIndex:Math.min(e+this.maxVisible,this.filteredItems.length)}}renderItem(e,t,i,r,n){let o=t?"\u2192 ":" ",l=S(o);if(r&&i>40){let h=Math.max(1,Math.min(n,i-l-4)),u=Math.max(1,h-ol),d=this.truncatePrimary(e,t,u,h),f=S(d),p=" ".repeat(Math.max(1,h-f)),g=l+f+p.length,x=i-g-2;if(x>sd){let m=D(r,x,"");if(t)return this.theme.selectedText(`${o}${d}${p}${m}`);let w=this.theme.description(p+m);return o+d+w}}let a=i-l-2,c=this.truncatePrimary(e,t,a,a);return t?this.theme.selectedText(`${o}${c}`):o+c}getPrimaryColumnWidth(){let{min:e,max:t}=this.getPrimaryColumnBounds(),i=this.filteredItems.reduce((r,n)=>Math.max(r,S(this.getDisplayValue(n))+ol),0);return rd(i,e,t)}getPrimaryColumnBounds(){let e=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??nl,t=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??nl;return{min:Math.max(1,Math.min(e,t)),max:Math.max(1,Math.max(e,t))}}truncatePrimary(e,t,i,r){let n=this.getDisplayValue(e),o=this.layout.truncatePrimary?this.layout.truncatePrimary({text:n,maxWidth:i,columnWidth:r,item:e,isSelected:t}):D(n,i,"");return D(o,i,"")}getDisplayValue(e){return e.label||e.value}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};var ul=rt(),nd=nt(),dl=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,fl=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function _t(s){return s.length>=10&&fl.test(s)}function od(s,e,t){if(t.size===0||!s.includes("[paste #"))return e.segment(s);let i=[];for(let l of s.matchAll(dl)){let a=Number.parseInt(l[1],10);t.has(a)&&i.push({start:l.index,end:l.index+l[0].length})}if(i.length===0)return e.segment(s);let r=e.segment(s),n=[],o=0;for(let l of r){for(;o<i.length&&i[o].end<=l.index;)o++;let a=o<i.length?i[o]:null;if(a&&l.index>=a.start&&l.index<a.end){if(l.index===a.start){let c=s.slice(a.start,a.end);n.push({segment:c,index:a.start,input:s})}}else n.push(l)}return n}function Or(s,e,t){if(!s||e<=0)return[{text:"",startIndex:0,endIndex:0}];if(S(s)<=e)return[{text:s,startIndex:0,endIndex:s.length}];let r=[],n=t??[...ul.segment(s)],o=0,l=0,a=-1,c=0;for(let h=0;h<n.length;h++){let u=n[h],d=u.segment,f=S(d),p=u.index,g=!_t(d)&&ee(d);if(o+f>e&&(a>=0&&o-c+f<=e?(r.push({text:s.slice(l,a),startIndex:l,endIndex:a}),l=a,o-=c):l<p&&(r.push({text:s.slice(l,p),startIndex:l,endIndex:p}),l=p,o=0),a=-1),f>e){let m=Or(d,e);for(let b=0;b<m.length-1;b++){let k=m[b];r.push({text:k.text,startIndex:p+k.startIndex,endIndex:p+k.endIndex})}let w=m[m.length-1];l=p+w.startIndex,o=S(w.text),a=-1;continue}o+=f;let x=n[h+1];if(g&&x&&(_t(x.segment)||!ee(x.segment)))a=x.index,c=o;else if(!g&&x&&!ee(x.segment)){let m=!_t(d)&&ot.test(d),w=!_t(x.segment)&&ot.test(x.segment);(m||w)&&(a=x.index,c=o)}}return r.push({text:s.slice(l),startIndex:l,endIndex:s.length}),r}var ld={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ad=20,ll=["@","#"],Br=new RegExp(`(?:(?!${lt.source}).)*`,"u"),pl=`${$s.source}[([{<\`]*`;function gl(s){return s.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function al(s){return new RegExp(`${pl}(?:@"[^"]*|[${s.map(gl).join("")}]${Br.source})$`,"u")}function cl(s){let e=s.filter(t=>t!=="@").map(gl);return new RegExp(`${pl}(?:@(?:"[^"]*|${Br.source})|[${e.join("")}]${Br.source})$`,"u")}function hl(s,e,t){let i=Math.max(0,t),r=` ${s} ${e} more `,n=S(r);if(n+2<=i){let h=Math.floor((i-n)/2);return"\u2500".repeat(h)+r+"\u2500".repeat(i-h-n)}let o=`\u2500\u2500\u2500 ${s} ${e} more `,l=i-S(o);if(l>=0)return o+"\u2500".repeat(l);let a="...".slice(0,i),c=i-S(a);return H(o,0,c,!0)+a}var gi=class{state={lines:[""],cursorLine:0,cursorCol:0};focused=!1;get capturesViewportInput(){return this.autocompleteState!==null}tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[...ll];autocompleteTriggerPattern=al(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=cl(this.autocompleteTriggerCharacters);autocompleteList;autocompleteState=null;autocompletePrefix="";autocompleteMaxVisible=5;autocompleteAbort;autocompleteDebounceTimer;autocompleteRequestTask=Promise.resolve();autocompleteStartToken=0;autocompleteRequestId=0;pastes=new Map;pasteCounter=0;pasteBuffer="";isInPaste=!1;history=[];historyIndex=-1;historyDraft=null;killRing=new Et;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new Pt;onSubmit;onChange;disableSubmit=!1;constructor(e,t,i={}){this.tui=e,this.theme=t,this.borderColor=t.borderColor;let r=i.paddingX??0;this.paddingX=Number.isFinite(r)?Math.max(0,Math.floor(r)):0;let n=i.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(n)?Math.max(3,Math.min(20,Math.floor(n))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(e,t){return od(e,t==="word"?nd:ul,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;this.paddingX!==t&&(this.paddingX=t,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(e){let t=Number.isFinite(e)?Math.max(3,Math.min(20,Math.floor(e))):5;this.autocompleteMaxVisible!==t&&(this.autocompleteMaxVisible=t,this.tui.requestRender())}setAutocompleteProvider(e){this.cancelAutocomplete(),this.autocompleteProvider=e,this.setAutocompleteTriggerCharacters(e.triggerCharacters??[])}addToHistory(e){let t=e.trim();t&&(this.history.length>0&&this.history[0]===t||(this.history.unshift(t),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===0}isOnLastVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===e.length-1}navigateHistory(e){if(this.lastAction=null,this.history.length===0)return;let t=this.historyIndex-e;if(!(t<-1||t>=this.history.length))if(this.historyIndex===-1&&t>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=t,this.historyIndex===-1){let i=this.historyDraft;this.historyDraft=null,i?(this.state=i,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("")}else this.setTextInternal(this.history[this.historyIndex]||"",e===-1?"start":"end")}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(e,t="end"){let i=e.split(`
74
+ `);this.state.lines=i.length===0?[""]:i,this.state.cursorLine=t==="start"?0:this.state.lines.length-1,this.setCursorCol(t==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}renderTopBorder(e,t){let i=t>0?hl("\u2191",t,e):"\u2500".repeat(e);return this.borderColor(i)}renderBottomBorder(e,t){let i=t>0?hl("\u2193",t,e):"\u2500".repeat(e);return this.borderColor(i)}render(e){let t=Math.max(0,Math.floor((e-1)/2)),i=Math.min(this.paddingX,t),r=Math.max(1,e-i*2),n=Math.max(1,r-(i?0:1));this.lastWidth=n;let o=this.layoutText(n),l=this.tui.terminal.rows,a=Math.max(5,Math.floor(l*.3)),c=o.findIndex(m=>m.hasCursor);c===-1&&(c=0),c<this.scrollOffset?this.scrollOffset=c:c>=this.scrollOffset+a&&(this.scrollOffset=c-a+1);let h=Math.max(0,o.length-a);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,h));let u=o.slice(this.scrollOffset,this.scrollOffset+a);this.renderedVisibleLineCount=u.length;let d=[],f=" ".repeat(i),p=f;d.push(this.renderTopBorder(e,this.scrollOffset));let g=this.focused;for(let m of u){let w=m.text,b=S(m.text),k=!1;if(m.hasCursor&&m.cursorPos!==void 0){let C=w.slice(0,m.cursorPos),I=w.slice(m.cursorPos),A=g?Z:"";if(I.length>0){let M=[...this.segment(I,"grapheme")][0]?.segment||"",P=I.slice(M.length),B=Pe(M);w=C+A+B+P}else{let T=Pe(" ");w=C+A+T,b=b+1,b>r&&i>0&&(k=!0)}}let v=" ".repeat(Math.max(0,r-b)),y=k?p.slice(1):p;d.push(`${f}${w}${v}${y}`)}let x=o.length-(this.scrollOffset+u.length);if(d.push(this.renderBottomBorder(e,x)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let m=this.autocompleteList.render(r);this.renderedAutocompleteHeight=m.length;for(let w of m){let b=S(w),k=" ".repeat(Math.max(0,r-b));d.push(`${f}${w}${k}${p}`)}}return d}handleMouse(e){let t=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&e.y>=t&&e.y<t+this.renderedAutocompleteHeight){let x=Math.max(0,Math.floor((e.width-1)/2)),m=Math.min(this.paddingX,x),w=Math.max(1,e.width-m*2),b=this.autocompleteList.handleMouse?.({...e,x:e.x-m,y:e.y-t,width:w,height:this.renderedAutocompleteHeight});return b?{...b,focus:!0}:void 0}if(e.type!=="click"||e.button!=="left")return;if(e.y<=0||e.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let i=this.buildVisualLineMap(this.lastWidth),r=this.scrollOffset+e.y-1,n=i[r];if(!n)return{handled:!0,focus:!0};let o=this.state.lines[n.logicalLine]??"",l=n.startCol+n.length,a=o.slice(n.startCol,l),c=Math.max(0,Math.floor((e.width-1)/2)),h=Math.min(this.paddingX,c),u=Math.max(0,e.x-h),d=0,f=a.length,p=0;for(let x of this.segment(a,"grapheme")){let m=d+S(x.segment);if(p=x.index,u<m){f=x.index;break}d=m}return!(r===i.length-1||i[r+1]?.logicalLine!==n.logicalLine)&&f===a.length&&a.length>0&&(f=p),this.state.cursorLine=n.logicalLine,this.setCursorCol(n.startCol+f),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:!0,focus:!0}}handleInput(e){let t=U();if(this.jumpMode!==null){if(t.matches(e,"tui.editor.jumpForward")||t.matches(e,"tui.editor.jumpBackward")){this.jumpMode=null;return}let r=rr(e)??(e.charCodeAt(0)>=32?e:void 0);if(r!==void 0){let n=this.jumpMode;this.jumpMode=null,this.jumpToChar(r,n);return}this.jumpMode=null}if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let r=this.pasteBuffer.indexOf("\x1B[201~");if(r!==-1){let n=this.pasteBuffer.substring(0,r);n.length>0&&this.handlePaste(n),this.isInPaste=!1;let o=this.pasteBuffer.substring(r+6);this.pasteBuffer="",o.length>0&&this.handleInput(o);return}return}if(t.matches(e,"tui.input.copy"))return;if(t.matches(e,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(t.matches(e,"tui.select.cancel")){this.cancelAutocomplete();return}if(t.matches(e,"tui.select.up")||t.matches(e,"tui.select.down")||t.matches(e,"tui.select.pageUp")||t.matches(e,"tui.select.pageDown")){this.autocompleteList.handleInput(e);return}if(t.matches(e,"tui.input.tab")){let r=this.autocompleteList.getSelectedItem();if(r&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let n=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,r,this.autocompletePrefix);this.state.lines=n.lines,this.state.cursorLine=n.cursorLine,this.setCursorCol(n.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(t.matches(e,"tui.select.confirm")){let r=this.autocompleteList.getSelectedItem();if(r&&this.autocompleteProvider){let n=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol),o=this.autocompletePrefix.startsWith("/")&&this.isInSlashCommandNameContext(n);this.pushUndoSnapshot(),this.lastAction=null;let l=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,r,this.autocompletePrefix);if(this.state.lines=l.lines,this.state.cursorLine=l.cursorLine,this.setCursorCol(l.cursorCol),o)this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(t.matches(e,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(t.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(t.matches(e,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(t.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(t.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(t.matches(e,"tui.editor.deleteCharBackward")||ue(e,"shift+backspace")){this.handleBackspace();return}if(t.matches(e,"tui.editor.deleteCharForward")||ue(e,"shift+delete")){this.handleForwardDelete();return}if(t.matches(e,"tui.editor.yank")){this.yank();return}if(t.matches(e,"tui.editor.yankPop")){this.yankPop();return}if(t.matches(e,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(t.matches(e,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(t.matches(e,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(t.matches(e,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(t.matches(e,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(t.matches(e,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(t.matches(e,"tui.input.newLine")||e.charCodeAt(0)===10&&e.length>1||e==="\x1B\r"||e==="\x1B[13;2~"||e.length>1&&e.includes("\x1B")&&e.includes("\r")||e===`
75
+ `&&e.length===1){if(this.shouldSubmitOnBackslashEnter(e,t)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(t.matches(e,"tui.input.submit")){if(this.disableSubmit)return;let r=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&r[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(t.matches(e,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(t.matches(e,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(t.matches(e,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(t.matches(e,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(t.matches(e,"tui.editor.pageUp")){this.pageScroll(-1);return}if(t.matches(e,"tui.editor.pageDown")){this.pageScroll(1);return}if(t.matches(e,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(t.matches(e,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(ue(e,"shift+space")){this.insertCharacter(" ");return}let i=rr(e);if(i!==void 0){this.insertCharacter(i);return}e.charCodeAt(0)>=32&&this.insertCharacter(e)}layoutText(e){let t=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return t.push({text:"",hasCursor:!0,cursorPos:0}),t;for(let i=0;i<this.state.lines.length;i++){let r=this.state.lines[i]||"",n=i===this.state.cursorLine;if(S(r)<=e)n?t.push({text:r,hasCursor:!0,cursorPos:this.state.cursorCol}):t.push({text:r,hasCursor:!1});else{let l=Or(r,e,[...this.segment(r,"grapheme")]);for(let a=0;a<l.length;a++){let c=l[a];if(!c)continue;let h=this.state.cursorCol,u=a===l.length-1,d=!1,f=0;n&&(u?(d=h>=c.startIndex,f=h-c.startIndex):(d=h>=c.startIndex&&h<c.endIndex,d&&(f=h-c.startIndex,f>c.text.length&&(f=c.text.length)))),d?t.push({text:c.text,hasCursor:!0,cursorPos:f}):t.push({text:c.text,hasCursor:!1})}}}return t}getText(){return this.state.lines.join(`
76
+ `)}expandPasteMarkers(e){let t=e;for(let[i,r]of this.pastes){let n=new RegExp(`\\[paste #${i}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");t=t.replace(n,()=>r)}return t}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(`
77
+ `))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(e){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let t=this.normalizeText(e);this.getText()!==t&&this.pushUndoSnapshot(),this.pastes.clear(),this.pasteCounter=0,this.setTextInternal(t)}insertTextAtCursor(e){e&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing(),this.insertTextAtCursorInternal(e))}normalizeText(e){return e.replace(/\r\n/g,`
78
+ `).replace(/\r/g,`
79
+ `).replace(/\t/g," ")}insertTextAtCursorInternal(e){if(!e)return;let t=this.normalizeText(e),i=t.split(`
80
+ `),r=this.state.lines[this.state.cursorLine]||"",n=r.slice(0,this.state.cursorCol),o=r.slice(this.state.cursorCol);i.length===1?(this.state.lines[this.state.cursorLine]=n+t+o,this.setCursorCol(this.state.cursorCol+t.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),n+i[0],...i.slice(1,-1),i[i.length-1]+o,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=i.length-1,this.setCursorCol((i[i.length-1]||"").length)),this.onChange&&this.onChange(this.getText())}insertCharacter(e,t){this.exitHistoryBrowsing(),t||((ee(e)||this.lastAction!=="type-word")&&this.pushUndoSnapshot(),this.lastAction="type-word");let i=this.state.lines[this.state.cursorLine]||"",r=i.slice(0,this.state.cursorCol),n=i.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=r+e+n,this.setCursorCol(this.state.cursorCol+e.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(e==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(e)){let l=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.autocompleteTriggerPattern.test(l)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(e)||ot.test(e)){let l=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(l)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(l)&&this.tryTriggerAutocomplete()}}handlePaste(e){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let t=e.replace(/\x1b\[(\d+);5u/g,(l,a)=>{let c=Number(a);return c>=97&&c<=122?String.fromCharCode(c-96):c>=65&&c<=90?String.fromCharCode(c-64):l}),r=this.normalizeText(t).split("").filter(l=>l===`
81
+ `||l.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(r)){let l=this.state.lines[this.state.cursorLine]||"",a=this.state.cursorCol>0?l[this.state.cursorCol-1]:"";a&&/\w/.test(a)&&(r=` ${r}`)}let n=r.split(`
82
+ `),o=r.length;if(n.length>10||o>1e3){this.pasteCounter++;let l=this.pasteCounter;this.pastes.set(l,r);let a=n.length>10?`[paste #${l} +${n.length} lines]`:`[paste #${l} ${o} chars]`;this.insertTextAtCursorInternal(a);return}if(n.length===1){this.insertTextAtCursorInternal(r);return}this.insertTextAtCursorInternal(r)}addNewLine(){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=e.slice(0,this.state.cursorCol),i=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=t,this.state.lines.splice(this.state.cursorLine+1,0,i),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(e,t){if(this.disableSubmit||!ue(e,"enter"))return!1;let i=t.getKeys("tui.input.submit");if(!(i.includes("shift+enter")||i.includes("shift+return")))return!1;let n=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&n[this.state.cursorCol-1]==="\\"}submitValue(){this.cancelAutocomplete();let e=this.expandPasteMarkers(this.state.lines.join(`
83
+ `)).trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(e)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=e.slice(0,this.state.cursorCol),i=[...this.segment(t,"grapheme")],r=i[i.length-1],n=r?r.segment.length:1,o=fl.exec(r.segment);if(o){let c=Number(o[1]);this.pastes.delete(c),this.pasteCounter--;let h=[...this.pastes.keys()].filter(u=>u>c).sort((u,d)=>u-d);for(let u of h)this.pastes.set(u-1,this.pastes.get(u)),this.pastes.delete(u);this.state.lines=this.state.lines.map(u=>u.replace(dl,(d,f,p)=>{let g=Number(f);return g<=c?d:`[paste #${g-1}${p??""}]`}))}e=this.state.lines[this.state.cursorLine]||"";let l=e.slice(0,this.state.cursorCol-n),a=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=l+a,this.setCursorCol(this.state.cursorCol-n)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(t)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(t)&&this.tryTriggerAutocomplete()}}setCursorCol(e){this.state.cursorCol=e,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(e,t,i){let r=e[t],n=e[i];if(!(r&&n))return;let o;if(this.snappedFromCursorCol!==null){let g=this.findVisualLineAt(e,r.logicalLine,this.snappedFromCursorCol);o=this.snappedFromCursorCol-e[g].startCol}else o=this.state.cursorCol-r.startCol;let a=t===e.length-1||e[t+1]?.logicalLine!==r.logicalLine?r.length:Math.max(0,r.length-1),h=i===e.length-1||e[i+1]?.logicalLine!==n.logicalLine?n.length:Math.max(0,n.length-1),u=this.computeVerticalMoveColumn(o,a,h);this.state.cursorLine=n.logicalLine;let d=n.startCol+u,f=this.state.lines[n.logicalLine]||"";this.state.cursorCol=Math.min(d,f.length);let p=[...this.segment(f,"grapheme")];for(let g of p){if(g.index>this.state.cursorCol)break;if(!(g.segment.length<=1)&&this.state.cursorCol<g.index+g.segment.length){let x=g.index<n.startCol,m=i>t;if(x&&m){let w=g.index+g.segment.length,b=i+1;for(;b<e.length&&e[b].logicalLine===n.logicalLine&&e[b].startCol<w;)b++;if(b<e.length){this.moveToVisualLine(e,t,b);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=g.index;return}}this.snappedFromCursorCol=null}computeVerticalMoveColumn(e,t,i){let r=this.preferredVisualCol!==null,n=e<t,o=i<e;if(!r||n)return o?(this.preferredVisualCol=e,i):(this.preferredVisualCol=null,e);let l=i<this.preferredVisualCol;if(o||l)return i;let a=this.preferredVisualCol;return this.preferredVisualCol=null,a}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(e.length)}deleteToStartOfLine(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let t=e.slice(0,this.state.cursorCol);this.killRing.push(t,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
84
+ `,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let t=e.slice(this.state.cursorCol);this.killRing.push(t,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
85
+ `,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
86
+ `,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}}else{this.pushUndoSnapshot();let t=this.lastAction==="kill",i=this.state.cursorCol;this.moveWordBackwards();let r=this.state.cursorCol;this.setCursorCol(i);let n=e.slice(r,this.state.cursorCol);this.killRing.push(n,{prepend:!0,accumulate:t}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,r)+e.slice(this.state.cursorCol),this.setCursorCol(r)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=e.length){if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
87
+ `,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let t=this.lastAction==="kill",i=this.state.cursorCol;this.moveWordForwards();let r=this.state.cursorCol;this.setCursorCol(i);let n=e.slice(this.state.cursorCol,r);this.killRing.push(n,{prepend:!1,accumulate:t}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)+e.slice(r)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let t=e.slice(this.state.cursorCol),r=[...this.segment(t,"grapheme")][0],n=r?r.segment.length:1,o=e.slice(0,this.state.cursorCol),l=e.slice(this.state.cursorCol+n);this.state.lines[this.state.cursorLine]=o+l}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let i=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(i)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(i)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(e){let t=[];for(let i=0;i<this.state.lines.length;i++){let r=this.state.lines[i]||"",n=S(r);if(r.length===0)t.push({logicalLine:i,startCol:0,length:0});else if(n<=e)t.push({logicalLine:i,startCol:0,length:r.length});else{let o=Or(r,e,[...this.segment(r,"grapheme")]);for(let l of o)t.push({logicalLine:i,startCol:l.startIndex,length:l.endIndex-l.startIndex})}}return t}findVisualLineAt(e,t,i){for(let r=0;r<e.length;r++){let n=e[r];if(!n||n.logicalLine!==t)continue;let o=i-n.startCol,l=r===e.length-1||e[r+1]?.logicalLine!==n.logicalLine;if(o>=0&&(o<n.length||l&&o===n.length))return r}return e.length-1}findCurrentVisualLine(e){return this.findVisualLineAt(e,this.state.cursorLine,this.state.cursorCol)}moveCursor(e,t){this.lastAction=null;let i=this.buildVisualLineMap(this.lastWidth),r=this.findCurrentVisualLine(i);if(e!==0){let n=r+e;n>=0&&n<i.length&&this.moveToVisualLine(i,r,n)}if(t!==0){let n=this.state.lines[this.state.cursorLine]||"";if(t>0)if(this.state.cursorCol<n.length){let o=n.slice(this.state.cursorCol),a=[...this.segment(o,"grapheme")][0];this.setCursorCol(this.state.cursorCol+(a?a.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let o=i[r];o&&(this.preferredVisualCol=this.state.cursorCol-o.startCol)}else if(this.state.cursorCol>0){let o=n.slice(0,this.state.cursorCol),l=[...this.segment(o,"grapheme")],a=l[l.length-1];this.setCursorCol(this.state.cursorCol-(a?a.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let o=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(o.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(e){this.lastAction=null;let t=this.tui.terminal.rows,i=Math.max(5,Math.floor(t*.3)),r=this.buildVisualLineMap(this.lastWidth),n=this.findCurrentVisualLine(r),o=Math.max(0,Math.min(r.length-1,n+e*i));this.moveToVisualLine(r,n,o)}moveWordBackwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let t=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(t.length)}return}this.setCursorCol(fi(e,this.state.cursorCol,{segment:t=>this.segment(t,"word"),isAtomicSegment:_t}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction="yank"}insertYankedText(e){this.exitHistoryBrowsing();let t=e.split(`
88
+ `);if(t.length===1){let i=this.state.lines[this.state.cursorLine]||"",r=i.slice(0,this.state.cursorCol),n=i.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=r+e+n,this.setCursorCol(this.state.cursorCol+e.length)}else{let i=this.state.lines[this.state.cursorLine]||"",r=i.slice(0,this.state.cursorCol),n=i.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=r+(t[0]||"");for(let l=1;l<t.length-1;l++)this.state.lines.splice(this.state.cursorLine+l,0,t[l]||"");let o=this.state.cursorLine+t.length-1;this.state.lines.splice(o,0,(t[t.length-1]||"")+n),this.state.cursorLine=o,this.setCursorCol((t[t.length-1]||"").length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){let e=this.killRing.peek();if(!e)return;let t=e.split(`
89
+ `);if(t.length===1){let i=this.state.lines[this.state.cursorLine]||"",r=e.length,n=i.slice(0,this.state.cursorCol-r),o=i.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n+o,this.setCursorCol(this.state.cursorCol-r)}else{let i=this.state.cursorLine-(t.length-1),r=(this.state.lines[i]||"").length-(t[0]||"").length,n=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),o=(this.state.lines[i]||"").slice(0,r);this.state.lines.splice(i,t.length,o+n),this.state.cursorLine=i,this.setCursorCol(r)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let e=this.undoStack.pop();e&&(Object.assign(this.state,e.state),this.pastes=e.pastes,this.pasteCounter=e.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(e,t){this.lastAction=null;let i=t==="forward",r=this.state.lines,n=i?r.length:-1,o=i?1:-1;for(let l=this.state.cursorLine;l!==n;l+=o){let a=r[l]||"",h=l===this.state.cursorLine?i?this.state.cursorCol+1:this.state.cursorCol-1:void 0,u=i?a.indexOf(e,h):a.lastIndexOf(e,h);if(u!==-1){this.state.cursorLine=l,this.setCursorCol(u);return}}}moveWordForwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=e.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(pi(e,this.state.cursorCol,{segment:t=>this.segment(t,"word"),isAtomicSegment:_t}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return t.trim()===""||t.trim()==="/"}isInSlashCommandContext(e){return this.isSlashMenuAllowed()&&e.trimStart().startsWith("/")}isInSlashCommandNameContext(e){return this.isInSlashCommandContext(e)&&!e.trimStart().includes(" ")}getBestAutocompleteMatchIndex(e,t){if(!t)return-1;let i=-1;for(let r=0;r<e.length;r++){let n=e[r].value;if(n===t)return r;i===-1&&n.startsWith(t)&&(i=r)}return i}createAutocompleteList(e,t){let i=e.startsWith("/")?ld:void 0,r=new $t(t,this.autocompleteMaxVisible,this.theme.selectList,i);return r.onSelect=n=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let o=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,n,this.autocompletePrefix);this.state.lines=o.lines,this.state.cursorLine=o.cursorLine,this.setCursorCol(o.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},r}tryTriggerAutocomplete(e=!1){this.requestAutocomplete({force:!1,explicitTab:e})}handleTabCompletion(){if(!this.autocompleteProvider)return;let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandNameContext(t)?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(e=!1){this.requestAutocomplete({force:!0,explicitTab:e})}requestAutocomplete(e){if(!this.autocompleteProvider||e.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let t=++this.autocompleteStartToken,i=this.getAutocompleteDebounceMs(e);if(i>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(t,e)},i);return}this.startAutocompleteRequest(t,e)}async startAutocompleteRequest(e,t){let i=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await i,e!==this.autocompleteStartToken||!this.autocompleteProvider)return;let r=new AbortController;this.autocompleteAbort=r;let n=++this.autocompleteRequestId,o=this.getText(),l=this.state.cursorLine,a=this.state.cursorCol;await this.runAutocompleteRequest(n,r,o,l,a,t)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(e){let t=[...ll];for(let i of e)i.length!==1||i==="/"||ee(i)||t.includes(i)||t.push(i);this.autocompleteTriggerCharacters=t,this.autocompleteTriggerPattern=al(t),this.autocompleteDebouncePattern=cl(t)}getAutocompleteDebounceMs(e){if(e.explicitTab||e.force)return 0;let i=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(i)?ad:0}async runAutocompleteRequest(e,t,i,r,n,o){if(!this.autocompleteProvider)return;let l=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:t.signal,force:o.force});if(this.isAutocompleteRequestCurrent(e,t,i,r,n)){if(this.autocompleteAbort=void 0,!l||!Array.isArray(l.items)||l.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(o.force&&o.explicitTab&&l.items.length===1){let a=l.items[0];this.pushUndoSnapshot(),this.lastAction=null;let c=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,a,l.prefix);this.state.lines=c.lines,this.state.cursorLine=c.cursorLine,this.setCursorCol(c.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(l,o.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(e,t,i,r,n){return!t.signal.aborted&&e===this.autocompleteRequestId&&this.getText()===i&&this.state.cursorLine===r&&this.state.cursorCol===n}applyAutocompleteSuggestions(e,t){this.autocompletePrefix=e.prefix,this.autocompleteList=this.createAutocompleteList(e.prefix,e.items);let i=this.getBestAutocompleteMatchIndex(e.items,e.prefix);i>=0&&this.autocompleteList.setSelectedIndex(i),this.autocompleteState=t}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var Ot=Symbol.for("@earendil-works/pi-tui/layout-node");function mi(s){let e=s;return typeof e[Ot]=="function"?e[Ot]():void 0}function cd(s){return!("render"in s)}function ws(s,e){return s===void 0||!Number.isFinite(s)?e:Math.max(0,Math.floor(s))}var Bt=class extends ae{entries=[];gap;align;constructor(e=[],t={}){super(),this.gap=ws(t.gap,0),this.align=t.align??"stretch";for(let i of e)cd(i)?this.addChild(i.component,i):this.addChild(i)}addChild(e,t={}){super.addChild(e),this.entries.push({component:e,...t.basis===void 0?{}:{basis:t.basis},...t.grow===void 0?{}:{grow:ws(t.grow,0)},...t.shrink===void 0?{}:{shrink:ws(t.shrink,1)},...t.minSize===void 0?{}:{minSize:ws(t.minSize,0)},...t.maxSize===void 0?{}:{maxSize:ws(t.maxSize,Number.MAX_SAFE_INTEGER)},...t.visible===void 0?{}:{visible:t.visible}})}removeChild(e){super.removeChild(e);let t=this.entries.findIndex(i=>i.component===e);t!==-1&&this.entries.splice(t,1)}clear(){super.clear(),this.entries.length=0}[Ot](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function Dt(s,e){return s.filter(t=>t.visible?.(e)??!0)}function hd(s,e){let t=Math.max(0,Math.floor(e.minSize??0)),i=Math.max(t,Math.floor(e.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(t,Math.min(i,Math.max(0,Math.floor(s))))}function ml(s,e,t,i){let r=t;for(;r>0;){let n=e.map((a,c)=>({entry:a,index:c})).filter(({entry:a,index:c})=>i==="grow"?(a.grow??0)>0&&s[c]<(a.maxSize??Number.MAX_SAFE_INTEGER):(a.shrink??1)>0&&s[c]>(a.minSize??0));if(n.length===0)return;let o=n.reduce((a,{entry:c,index:h})=>a+(i==="grow"?c.grow??0:(c.shrink??1)*Math.max(1,s[h])),0),l=0;for(let{entry:a,index:c}of n){if(r<=0)break;let h=i==="grow"?a.grow??0:(a.shrink??1)*Math.max(1,s[c]),u=Math.max(1,Math.floor(r*h/o)),d=i==="grow"?(a.maxSize??Number.MAX_SAFE_INTEGER)-s[c]:s[c]-(a.minSize??0),f=Math.min(r,u,d);f<=0||(s[c]=s[c]+(i==="grow"?f:-f),r-=f,l+=f)}if(l===0)return}}function Ue(s,e,t,i){let r=s.map((l,a)=>hd(l.basis===void 0||l.basis==="auto"?e[a]??0:l.basis,l));if(t===void 0)return r;let n=Math.max(0,Math.floor(t)-Math.max(0,s.length-1)*i),o=r.reduce((l,a)=>l+a,0);return o<n?ml(r,s,n-o,"grow"):o>n&&ml(r,s,o-n,"shrink"),r}var xi=class extends Bt{layoutType="hstack";constructor(e=[],t={}){super(e,t)}render(e){let t=Math.max(1,e),i={width:t,height:Number.MAX_SAFE_INTEGER},r=Dt(this.entries,i);if(r.length===0)return[];let n=r.map(u=>u.component.render(t).reduce((f,p)=>Math.max(f,S(p)),0)),o=Ue(r,n,t,this.gap),l=r.map((u,d)=>o[d]===0?[]:u.component.render(o[d])),a=l.reduce((u,d)=>Math.max(u,d.length),0),c=Array.from({length:a},()=>""),h=0;for(let u=0;u<l.length;u++){let d=l[u],f=o[u],p=0;this.align==="center"?p=Math.floor((a-d.length)/2):this.align==="end"&&(p=a-d.length);for(let g=0;g<d.length;g++){let x=g+p;x<0||x>=c.length||(c[x]=ye(c[x],d[g],h,f,t))}h+=f+this.gap}return c}};var Dr,ze=new Map;function xl(s){Dr=s,ze.clear()}function ud(s,e){if(!Dr)return null;let t=ze.get(s),i=t===void 0?Dr(s,e):t;return ze.delete(s),ze.set(s,i),ze.size>32&&ze.delete(ze.keys().next().value),i}var bi=class{base64Data;mimeType;dimensions;theme;options;imageId;pngData;cachedLines;cachedWidth;constructor(e,t,i,r={},n){this.base64Data=e,this.mimeType=t,this.theme=i,this.options=r,this.dimensions=n||oi(e,t)||{widthPx:800,heightPx:600},this.imageId=r.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,Math.min(e-2,this.options.maxWidthCells??60)),i=fs(),r=Math.max(1,Math.ceil(t*i.widthPx/i.heightPx)),n=this.options.maxHeightCells??r,o=se(),l=this.base64Data,a=this.dimensions;o.images==="kitty"&&this.mimeType!=="image/png"&&(this.pngData??=ud(this.base64Data,this.mimeType)??void 0,l=this.pngData??null,l&&(a=ms(l)??a));let c;if(o.images&&l){o.images==="kitty"&&this.imageId===void 0&&(this.imageId=ti());let h=li(l,a,{maxWidthCells:t,maxHeightCells:n,imageId:this.imageId,moveCursor:!1});if(h)if(h.imageId&&(this.imageId=h.imageId),o.images==="kitty"){c=[h.sequence];for(let u=0;u<h.rows-1;u++)c.push("")}else{c=[];for(let f=0;f<h.rows-1;f++)c.push("");let u=h.rows-1,d=u>0?`\x1B[${u}A`:"";c.push(d+h.sequence)}else{let u=bs(this.mimeType,this.dimensions,this.options.filename);c=[D(this.theme.fallbackColor(u),e)]}}else{let h=bs(this.mimeType,this.dimensions,this.options.filename);c=[D(this.theme.fallbackColor(h),e)]}return this.cachedLines=c,this.cachedWidth=e,c}};var je=rt(),$e=class{value="";cursor=0;prompt;placeholder;placeholderStyle;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new Et;lastAction=null;undoStack=new Pt;constructor(e={}){this.prompt=e.prompt??"> ",this.placeholder=e.placeholder??"",this.placeholderStyle=e.placeholderStyle??(t=>t)}getValue(){return this.value}setValue(e){this.value=e,this.cursor=Math.min(this.cursor,e.length)}handleInput(e){if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let n=this.pasteBuffer.indexOf("\x1B[201~");if(n!==-1){let o=this.pasteBuffer.substring(0,n);this.handlePaste(o),this.isInPaste=!1;let l=this.pasteBuffer.substring(n+6);this.pasteBuffer="",l&&this.handleInput(l)}return}let t=U();if(t.matches(e,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(t.matches(e,"tui.editor.undo")){this.undo();return}if(t.matches(e,"tui.input.submit")||e===`
90
+ `){this.onSubmit&&this.onSubmit(this.value);return}if(t.matches(e,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(t.matches(e,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(t.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(t.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(t.matches(e,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(t.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToLineEnd();return}if(t.matches(e,"tui.editor.yank")){this.yank();return}if(t.matches(e,"tui.editor.yankPop")){this.yankPop();return}if(t.matches(e,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let n=this.value.slice(0,this.cursor),o=[...je.segment(n)],l=o[o.length-1];this.cursor-=l?l.segment.length:1}return}if(t.matches(e,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let n=this.value.slice(this.cursor),l=[...je.segment(n)][0];this.cursor+=l?l.segment.length:1}return}if(t.matches(e,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(t.matches(e,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(t.matches(e,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(t.matches(e,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let i=os(e);if(i!==void 0){this.insertCharacter(i);return}[...e].some(n=>{let o=n.charCodeAt(0);return o<32||o===127||o>=128&&o<=159})||this.insertCharacter(e)}handleMouse(e){if(e.type!=="press"||e.button!=="left"||e.y!==0)return;let t=Math.max(0,e.x-2),i=this.renderedStartColumn+t,r=0;this.cursor=this.value.length;for(let n of je.segment(this.value)){let o=r+S(n.segment);if(i<o){this.cursor=n.index;break}r=o}return this.lastAction=null,{handled:!0,focus:!0}}insertCharacter(e){(ee(e)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let e=this.value.slice(0,this.cursor),t=[...je.segment(e)],i=t[t.length-1],r=i?i.segment.length:1;this.value=this.value.slice(0,this.cursor-r)+this.value.slice(this.cursor),this.cursor-=r}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let e=this.value.slice(this.cursor),i=[...je.segment(e)][0],r=i?i.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+r)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let e=this.value.slice(0,this.cursor);this.killRing.push(e,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let e=this.value.slice(this.cursor);this.killRing.push(e,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordBackwards();let i=this.cursor;this.cursor=t;let r=this.value.slice(i,this.cursor);this.killRing.push(r,{prepend:!0,accumulate:e}),this.lastAction="kill",this.value=this.value.slice(0,i)+this.value.slice(this.cursor),this.cursor=i}deleteWordForward(){if(this.cursor>=this.value.length)return;let e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordForwards();let i=this.cursor;this.cursor=t;let r=this.value.slice(this.cursor,i);this.killRing.push(r,{prepend:!1,accumulate:e}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(i)}yank(){let e=this.killRing.peek();e&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction="yank")}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let e=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-e.length)+this.value.slice(this.cursor),this.cursor-=e.length,this.killRing.rotate();let t=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let e=this.undoStack.pop();e&&(this.value=e.value,this.cursor=e.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=fi(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=pi(this.value,this.cursor))}handlePaste(e){this.lastAction=null,this.pushUndo();let t=e.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length}invalidate(){}render(e){let t=e-S(this.prompt);if(t<=0)return[D(this.prompt,e,"")];if(this.value.length===0&&this.placeholder){let m=D(this.placeholder,t,""),b=[...je.segment(m)][0]?.segment??" ",k=m.slice(b.length),v=this.focused?Z:"",y=Pe(this.placeholderStyle(b)),C=v+y+this.placeholderStyle(k),I=" ".repeat(Math.max(0,t-S(C)));return[this.prompt+C+I]}let i="",r=this.cursor;this.renderedStartColumn=0;let n=S(this.value);if(n<t)i=this.value;else{let m=this.cursor===this.value.length?t-1:t,w=S(this.value.slice(0,this.cursor));if(m>0){let b=Math.floor(m/2),k=0;w<b?k=0:w>n-b?k=Math.max(0,n-m):k=Math.max(0,w-b),this.renderedStartColumn=k,i=H(this.value,k,m,!0),r=H(this.value,k,Math.max(0,w-k),!0).length}else i="",r=0}let l=[...je.segment(i.slice(r))][0],a=i.slice(0,r),c=l?.segment??" ",h=i.slice(r+c.length),u=this.focused?Z:"",d=Pe(c),f=a+u+d+h,p=S(f),g=" ".repeat(Math.max(0,t-p));return[this.prompt+f+g]}};var pe="\\u1100-\\u11ff\\u20a9\\u2329-\\u232a\\u2630-\\u2637\\u268a-\\u268f\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u2ff0-\\u303e\\u3041-\\u3096\\u3099-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u31e5\\u31ef-\\u321e\\u3220-\\u3247\\u3250-\\ua48c\\ua490-\\ua4c6\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufaff\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe66\\ufe68-\\ufe6b\\uff01-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\uffe0-\\uffe6\\uffe8-\\uffee\\u{16fe0}-\\u{16fe4}\\u{16ff0}-\\u{16ff6}\\u{17000}-\\u{18cda}\\u{18cff}-\\u{18d20}\\u{18d80}-\\u{18df2}\\u{18e00}-\\u{19191}\\u{191a0}-\\u{191d2}\\u{1aff0}-\\u{1aff3}\\u{1aff5}-\\u{1affb}\\u{1affd}-\\u{1affe}\\u{1b000}-\\u{1b128}\\u{1b132}\\u{1b150}-\\u{1b152}\\u{1b155}\\u{1b164}-\\u{1b168}\\u{1b170}-\\u{1b2fb}\\u{1d300}-\\u{1d356}\\u{1d360}-\\u{1d376}\\u{1f1ae}\\u{1f200}\\u{1f202}\\u{1f210}-\\u{1f219}\\u{1f21b}-\\u{1f22e}\\u{1f230}-\\u{1f231}\\u{1f237}\\u{1f23b}\\u{1f240}-\\u{1f248}\\u{1f260}-\\u{1f265}\\u{1f7da}\\u{20000}-\\u{3fffd}",Nt=new RegExp(`[${pe}]`,"u"),dd=new RegExp(`^((?![*_])[\\s\\p{P}\\p{S}${pe}])`,"u");function kl(s,e,t){return new RegExp(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)${s}(\\*+)(?=[\\s]|$)|${t}(\\*+)(?!\\*)(?=${e}|$)|(?!\\*)${e}(\\*+)(?=${t})|[\\s](\\*+)(?!\\*)(?=${s})|(?!\\*)${s}(\\*+)(?!\\*)(?=${s})|${t}(\\*+)(?=${t})`,"gu")}function fd(s,e,t){return new RegExp(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)${s}(_+)(?=[\\s]|$)|${t}(_+)(?!_)(?=${e}|$)|(?!_)${e}(_+)(?=${t})|[\\s](_+)(?!_)(?=${s})|(?!_)${s}(_+)(?!_)(?=${s})`,"gu")}function pd(s,e,t){return new RegExp(`^[^~]+(?=[^~])|(?!~)${s}(~~?)(?=[\\s]|$)|${t}(~~?)(?!~)(?=${e}|$)|(?!~)${e}(~~?)(?=${t})|[\\s](~~?)(?!~)(?=${s})|(?!~)${s}(~~?)(?!~)(?=${s})|${t}(~~?)(?=${t})`,"gu")}var Sl=`[\\p{P}\\p{S}${pe}]`,Cl=`[\\s\\p{P}\\p{S}${pe}]`,Tl=`[^\\s\\p{P}\\p{S}${pe}]`,gd=`(?![*_])[\\p{P}\\p{S}${pe}]`,md=`(?![*_])[\\s\\p{P}\\p{S}${pe}]`,xd=`(?:[^\\s\\p{P}\\p{S}${pe}]|[*_])`,bd=`(?!~)[\\p{P}\\p{S}${pe}]`,yd=`(?!~)[\\s\\p{P}\\p{S}${pe}]`,wd=`(?:[^\\s\\p{P}\\p{S}${pe}]|~)`,kd=kl(Sl,Cl,Tl),Sd=kl(bd,yd,wd),Cd=fd(Sl,Cl,Tl),bl=pd(gd,md,xd);function yl(s,e,t){let i=dd.test(s);if(!i&&s){let r=e.length-t.length;if(r>=1){let n=r-1,o=e.charCodeAt(n);if(o>=65024&&o<=65038&&n>=1&&(n--,o=e.charCodeAt(n)),(o&64512)===56320&&n>=1){let l=e.codePointAt(n-1);l!==void 0&&l>65535&&(l>=917760&&l<=917999?i=!0:i=Nt.test(String.fromCodePoint(l)))}else i=Nt.test(String.fromCharCode(o))}}return i}function wl(s,e){if(!(s[1]||s[2]||s[3]||s[4]))return!1;let t=String.fromCodePoint(s[0].codePointAt(0)),i=s.index+s[0].length,r=i<e.length?String.fromCodePoint(e.codePointAt(i)):"";return Nt.test(t)||Nt.test(r)}function Nr(s){return s.length>=5}function Td(s){return!!(s[1]||s[2]||s[3]||s[4])}function vd(s){return Nr(s)?!!s[4]:!!s[3]}function Md(s){return Nr(s)?s[1]||s[3]||"":s[1]||s[2]||""}function vl(){return{tokenizer:{emStrong(s,e,t=""){let{rules:i}=this,r=i.inline.emStrongLDelim.exec(s);if(!r)return!1;let n=Nr(r);if(n&&!Td(r))return;if(vd(r)&&t.match(i.other.unicodeAlphaNumeric))return!1;let o=Md(r),l=yl(t,e,s);if(!o||!t||i.inline.punctuation.exec(t)||l||Nt.test(o)){let a=[...r[0]].length-1,c,h,u=a,d=0,f=n&&t===r[0][0],p=i.inline.emStrongRDelimAst.source.includes("(?!~)"),g;r[0][0]==="*"?g=p?Sd:kd:g=Cd,g.lastIndex=0;let x=e.slice(-1*s.length+a),m;for(;(m=g.exec(x))!=null;){if(c=m[1]||m[2]||m[3]||m[4]||m[5]||m[6],!c)continue;h=[...c].length;let w=wl(m,x),b=!!(m[3]||m[4]),k=!!(m[5]||m[6]);if(b&&!w){u+=h;continue}if(k||w){if(a%3&&!((a+h)%3)){d+=h;continue}if(f&&k)break}if(u-=h,u>0)continue;h=Math.min(h,h+u+d);let v=m[0].codePointAt(0)>65535?2:1,y=s.slice(0,a+m.index+v+h);if(Math.min(a,h)%2){let I=y.slice(1,-1);return{type:"em",raw:y,text:I,tokens:this.lexer.inlineTokens(I)}}let C=y.slice(2,-2);return{type:"strong",raw:y,text:C,tokens:this.lexer.inlineTokens(C)}}}},del(s,e,t=""){let{rules:i}=this,r=i.inline.delLDelim.exec(s);if(!r)return!1;let n=r[1]||"",o=yl(t,e,s);if(!n||!t||i.inline.punctuation.exec(t)||o||Nt.test(n)){let l=[...r[0]].length-1,a,c,h=l;bl.lastIndex=0;let u=e.slice(-1*s.length+l),d;for(;(d=bl.exec(u))!=null;){if(a=d[1]||d[2]||d[3]||d[4]||d[5]||d[6],!a||(c=[...a].length,c!==l))continue;let f=wl(d,u);if((d[3]||d[4])&&!f){h+=c;continue}if(h-=c,h>0)continue;c=Math.min(c,c+h);let p=d[0].codePointAt(0)>65535?2:1,g=s.slice(0,l+d.index+p+c),x=g.slice(l,-l);return{type:"del",raw:g,text:x,tokens:this.lexer.inlineTokens(x)}}}}}}}var Id={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",varkappa:"\u03F0",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9",pm:"\xB1",mp:"\u2213",times:"\xD7",div:"\xF7",cdot:"\xB7",ast:"\u2217",star:"\u22C6",circ:"\u2218",bullet:"\u2022",oplus:"\u2295",ominus:"\u2296",otimes:"\u2297",oslash:"\u2298",odot:"\u2299",bigcirc:"\u25CB",dagger:"\u2020",ddagger:"\u2021",amalg:"\u2A3F",uplus:"\u228E",sqcap:"\u2293",sqcup:"\u2294",bowtie:"\u22C8",Join:"\u22C8",ltimes:"\u22C9",rtimes:"\u22CA",leftouterjoin:"\u27D5",rightouterjoin:"\u27D6",fullouterjoin:"\u27D7",triangleleft:"\u25C1",triangleright:"\u25B7",wr:"\u2240",cap:"\u2229",cup:"\u222A",bigcap:"\u22C2",bigcup:"\u22C3",bigwedge:"\u22C0",bigvee:"\u22C1",bigsqcup:"\u2A06",biguplus:"\u2A04",bigoplus:"\u2A01",bigotimes:"\u2A02",bigodot:"\u2A00",setminus:"\u2216",in:"\u2208",notin:"\u2209",ni:"\u220B",subset:"\u2282",supset:"\u2283",subseteq:"\u2286",supseteq:"\u2287",sqsubset:"\u228F",sqsupset:"\u2290",sqsubseteq:"\u2291",sqsupseteq:"\u2292",prec:"\u227A",preceq:"\u227C",succ:"\u227B",succeq:"\u227D",ll:"\u226A",gg:"\u226B",le:"\u2264",leq:"\u2264",leqslant:"\u2264",ge:"\u2265",geq:"\u2265",geqslant:"\u2265",ne:"\u2260",neq:"\u2260",equiv:"\u2261",approx:"\u2248",sim:"\u223C",simeq:"\u2243",cong:"\u2245",asymp:"\u224D",doteq:"\u2250",propto:"\u221D",parallel:"\u2225",perp:"\u22A5",mid:"\u2223",vdash:"\u22A2",dashv:"\u22A3",models:"\u22A8",Vdash:"\u22A9",Vvdash:"\u22AA",nvdash:"\u22AC",nvDash:"\u22AD",forall:"\u2200",exists:"\u2203",nexists:"\u2204",neg:"\xAC",land:"\u2227",wedge:"\u2227",lor:"\u2228",vee:"\u2228",to:"\u2192",rightarrow:"\u2192",longrightarrow:"\u2192",leftarrow:"\u2190",longleftarrow:"\u2190",gets:"\u2190",leftrightarrow:"\u2194",longleftrightarrow:"\u2194",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",leftharpoonup:"\u21BC",leftharpoondown:"\u21BD",rightharpoonup:"\u21C0",rightharpoondown:"\u21C1",rightleftharpoons:"\u21CC",leftrightharpoons:"\u21CB",nearrow:"\u2197",searrow:"\u2198",swarrow:"\u2199",nwarrow:"\u2196",rightsquigarrow:"\u21DD",leadsto:"\u21DD",Rightarrow:"\u21D2",Longrightarrow:"\u21D2",Leftarrow:"\u21D0",Longleftarrow:"\u21D0",Leftrightarrow:"\u21D4",Longleftrightarrow:"\u21D4",implies:"\u21D2",iff:"\u21D4",mapsto:"\u21A6",longmapsto:"\u21A6",uparrow:"\u2191",downarrow:"\u2193",partial:"\u2202",nabla:"\u2207",int:"\u222B",iint:"\u222C",iiint:"\u222D",oint:"\u222E",sum:"\u2211",prod:"\u220F",coprod:"\u2210",infty:"\u221E",emptyset:"\u2205",varnothing:"\u2205",angle:"\u2220",therefore:"\u2234",because:"\u2235",aleph:"\u2135",beth:"\u2136",gimel:"\u2137",daleth:"\u2138",top:"\u22A4",bot:"\u22A5",triangle:"\u25B3",square:"\u25A1",lozenge:"\u25CA",checkmark:"\u2713",complement:"\u2201",wp:"\u2118",prime:"\u2032",ldots:"\u2026",dots:"\u2026",cdots:"\u22EF",vdots:"\u22EE",ddots:"\u22F1",ell:"\u2113",hbar:"\u210F",Im:"\u2111",Re:"\u211C",langle:"\u27E8",rangle:"\u27E9",vert:"|",lvert:"|",rvert:"|",Vert:"\u2016",lVert:"\u2016",rVert:"\u2016",lbrace:"{",rbrace:"}",backslash:"\\",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309",colon:":"},Rd=new Set(["arccos","arcsin","arctan","arg","cos","cosh","cot","coth","csc","deg","det","dim","exp","gcd","hom","inf","ker","lg","lim","liminf","limsup","ln","log","max","min","Pr","sec","sin","sinh","sup","tan","tanh"]),Ad=new Set(["argmax","argmin","inf","injlim","lim","liminf","limsup","max","min","projlim","sup"]),Ld=new Set(["bigcap","bigcup","bigodot","bigoplus","bigotimes","bigsqcup","biguplus","bigvee","bigwedge","coprod","int","iint","iiint","oint","prod","sum"]),Ed=new Set(["Leftarrow","Leftrightarrow","Longleftarrow","Longleftrightarrow","Longrightarrow","Rightarrow","Join","Vdash","Vvdash","approx","asymp","bowtie","cong","dashv","fullouterjoin","doteq","downarrow","equiv","ge","geq","geqslant","gets","gg","hookleftarrow","hookrightarrow","iff","implies","in","leadsto","le","leftarrow","leftharpoondown","leftharpoonup","leftrightarrow","leftrightharpoons","leftouterjoin","leq","leqslant","ll","longleftarrow","longleftrightarrow","longmapsto","longrightarrow","ltimes","mapsto","mid","models","ne","nearrow","neq","ni","notin","nvdash","nvDash","nwarrow","parallel","perp","prec","preceq","propto","rightharpoondown","rightharpoonup","rightleftharpoons","rightouterjoin","rightarrow","rightsquigarrow","rtimes","searrow","sim","simeq","sqsubset","sqsubseteq","sqsupset","sqsupseteq","subset","subseteq","succ","succeq","supset","supseteq","swarrow","to","triangleleft","triangleright","twoheadleftarrow","twoheadrightarrow","uparrow","vdash"]),Pd={"<":"\u226E",">":"\u226F","=":"\u2260","\u2208":"\u2209","\u220B":"\u220C","\u2223":"\u2224","\u2225":"\u2226","\u223C":"\u2241","\u2243":"\u2244","\u2245":"\u2247","\u2248":"\u2249","\u2261":"\u2262","\u2264":"\u2270","\u2265":"\u2271","\u227A":"\u2280","\u227B":"\u2281","\u2282":"\u2284","\u2283":"\u2285","\u2286":"\u2288","\u2287":"\u2289","\u22A2":"\u22AC","\u22A8":"\u22AD","\u2194":"\u21AE","\u2190":"\u219A","\u2192":"\u219B","\u21D2":"\u21CF","\u21D0":"\u21CD","\u21D4":"\u21CE","\u227C":"\u22E0","\u227D":"\u22E1"},$d={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},_d={0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},Od={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"},Bd=new Set([",",":",";"," ",">","enspace","enskip","medspace","quad","qquad","thickspace","thinspace"]),Dd=new Set(["!","negmedspace","negthickspace","negthinspace"]),Ml="\0",Nd=new Set(["bf","cal","it","rm","sf","sl","tt"]),Wd=new Set(["displaystyle","limits","nolimits","scriptstyle","scriptscriptstyle","textstyle"]),Fd=new Set(["big","Big","bigg","Bigg","bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr"]),Hd=new Set(["emph","mathcal","mathbf","mathfrak","mathit","mathrm","mathnormal","mathscr","mathsf","mathtt","mathup","mbox","overbrace","pmb","smash","substack","text","textbf","textit","textmd","textnormal","textrm","textsc","textsf","textsl","texttt","textup","underbrace","bm","boldsymbol"]),Kd={acute:"\u0301",bar:"\u0305",breve:"\u0306",check:"\u030C",ddot:"\u0308",dot:"\u0307",grave:"\u0300",hat:"\u0302",mathring:"\u030A",overleftarrow:"\u20D6",overleftrightarrow:"\u20E1",overline:"\u0305",overrightarrow:"\u20D7",tilde:"\u0303",underline:"\u0332",vec:"\u20D7",widehat:"\u0302",widetilde:"\u0303"};function Vd(s,e){let t="";for(let i of s){let r=e[i];if(r===void 0)return;t+=r}return t}function Il(s){return s.trim().replace(/\s*([=+-])\s*/g,"$1")}function Wr(s,e){return Vd(Il(s),e==="sub"?Od:_d)}function Ge(s,e){s=Il(s);let t=Wr(s,e);if(t!==void 0)return t;let i=e==="sub"?"_":"^";return Array.from(s).length===1||e==="sub"&&/^[A-Za-z]+$/.test(s)?`${i}${s}`:`${i}(${s})`}function qd(s,e){s=s.trim(),e=e.trim();let t=/^[\p{L}\p{N}.]+$/u.test(s),i=/^[\p{N}.]+$/u.test(e)||Array.from(e).length===1;return`${t?s:`(${s})`}/${i?e:`(${e})`}`}function yi(s,e="\u221A"){return s=s.trim(),/^[\p{L}\p{N}.]+$/u.test(s)?`${e}${s}`:`${e}(${s})`}var Rl="\u{F0004}",Qe="\u{F0005}",Ud=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,zd=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function Ye(s){return s.replace(Ud," ").replaceAll(Rl,"").replace(zd," ").replaceAll(Qe,"").split(`
91
+ `).map(e=>e.replace(/[ \t]+/g," ").trim()).filter((e,t,i)=>e.length>0||t>0&&t<i.length-1).join(`
92
+ `).trim()}var Wt="\u{F0000}",ks="\u{F0001}",jd=/\u{f0000}(\d+)\u{f0001}/gu,Gd=/\u{f0000}(\d+)\u{f0001}$/u,wi="\u{F0002}";function ve(s,e,t=!1){let i=Math.max(0,e-S(s)),r=t?Math.floor(i/2):0;return`${" ".repeat(r)}${s}${" ".repeat(i-r)}`}function Yd(s){if(s.length===0)return{lines:[""],width:0,baseline:0};let e=Math.max(...s.map(r=>r.baseline)),t=Math.max(...s.map(r=>r.lines.length-r.baseline-1)),i=[];for(let r=0;r<=e+t;r++){let n="";for(let o of s){let l=r-e+o.baseline;n+=l>=0&&l<o.lines.length?ve(o.lines[l]??"",o.width):" ".repeat(o.width)}i.push(n.trimEnd())}return{lines:i,width:s.reduce((r,n)=>r+n.width,0),baseline:e}}function Ss(s,e){let t=[],i=0;for(let r of s.split(`
93
+ `)){let n=[],o=0,l;for(let c of r.matchAll(jd)){let h=c.index,u=e[Number(c[1])];if(u){if(h>o){let d=r.slice(o,h),f=(l?d.trimStart():d).trimEnd(),p=l?.type==="matrix"&&/^\s/.test(d),g=u.type==="matrix"&&/\s$/.test(d),x=f?`${p?" ":""}${f}${g?" ":""}`:p||g?" ":"";n.push({lines:[x],width:S(x),baseline:0})}if(u.type==="fraction"){let d=Ss(u.numerator,e),f=Ss(u.denominator,e),p=Math.max(d.width,f.width,1),g=p+2;n.push({lines:[...d.lines.map(x=>ve(x,g,!0)),` ${"\u2500".repeat(p)} `,...f.lines.map(x=>ve(x,g,!0))],width:g,baseline:d.lines.length})}else if(u.type==="operator"){let d=Math.max(S(u.operator),u.lower===void 0?0:S(u.lower),u.upper===void 0?0:S(u.upper)),f=[];u.upper!==void 0&&f.push(`${ve(u.upper,d,!0)} `),f.push(`${ve(u.operator,d,!0)} `),u.lower!==void 0&&f.push(`${ve(u.lower,d,!0)} `),n.push({lines:f,width:d+1,baseline:u.upper===void 0?0:1})}else if(u.type==="script"){let d=u.upper===void 0?void 0:Ss(u.upper,e),f=u.lower===void 0?void 0:Ss(u.lower,e),p=Math.max(d?.width??0,f?.width??0);n.push({lines:[...d?.lines.map(g=>ve(g,p))??[]," ".repeat(p),...f?.lines.map(g=>ve(g,p))??[]],width:p,baseline:d?.lines.length??0})}else{let d=Math.max(0,...u.lines.map(f=>S(f)));n.push({lines:u.lines.map(f=>ve(f,d)),width:d,baseline:u.baseline})}o=h+c[0].length,l=u}}if(o<r.length){let c=r.slice(o),h=l?c.trimStart():c,u=l?.type==="matrix"&&/^\s/.test(c)?` ${h}`:h;n.push({lines:[u],width:S(u),baseline:0})}let a=Yd(n);t.length===0&&(i=a.baseline),t.push(...a.lines)}return{lines:t,width:Math.max(0,...t.map(r=>S(r))),baseline:i}}var Fr=class s{source;layoutNodes;display;position=0;supported=!0;stackFractions=!0;scriptDepth=0;constructor(e,t,i){this.source=e,this.layoutNodes=t,this.display=i}render(){let e=this.parseSequence();if(!(!this.supported||this.position!==this.source.length))return Ye(e)}parseSequence(e){let t="";for(;this.position<this.source.length;){let i=this.source[this.position];if(e&&i===e)return this.position++,t;if(i==="}")return this.supported=!1,t;if(i==="{"){this.position++,t+=this.parseSequence("}");continue}if(i==="\\"){let r=this.parseCommand();r===Ml?(t=t.trimEnd(),t.endsWith(Qe)&&(t=t.slice(0,-Qe.length))):t+=r;continue}if(i==="^"||i==="_"){this.position++,t=t.trimEnd();let r=this.parseScripts(i);t.endsWith(Qe)?t=`${t.slice(0,-Qe.length)}${r}${Qe}`:t+=r;continue}if(/\s/.test(i)){t+=this.parseWhitespace();continue}if(i==="="||i==="<"||i===">"){t=`${t.trimEnd()} ${i} `,this.position++;continue}if(i==="&"){this.position++;continue}if(i==="~"){this.position++,t+=" ";continue}if(i==="."){let r=Gd.exec(t),n=r?this.layoutNodes[Number(r[1])]:void 0;if(n?.type==="matrix"){let o=n.lines.length-1;n.lines[o]=`${n.lines[o]??""}${i}`,this.position++;continue}}t+=i,this.position++}return e&&(this.supported=!1),t}parseScripts(e){let t={},i=[],r=d=>{let f=d==="_"?"sub":"sup";this.scriptDepth++;try{t[f]=this.parseRequiredArgument(!1)}finally{this.scriptDepth--}i.push(f)};r(e);let n=this.position;for(;n<this.source.length&&/\s/.test(this.source[n]??"");)n++;let o=this.source[n];(o==="^"||o==="_")&&o!==e&&(this.position=n+1,r(o));let l=t.sub===void 0?void 0:Wr(t.sub,"sub"),a=t.sup===void 0?void 0:Wr(t.sup,"sup"),c=![t.sub,t.sup].some(d=>d!==void 0&&(d.includes("/")||!d.includes(Wt)&&Array.from(d).length>1&&!/[A-Z*∗]/.test(d)));if(!(this.display&&c&&(this.scriptDepth>0||t.sub!==void 0&&l===void 0||t.sup!==void 0&&a===void 0)))return i.map(d=>d==="sub"?l??Ge(t.sub??"",d):a??Ge(t.sup??"",d)).join("");let u=this.layoutNodes.push({type:"script",lower:t.sub===void 0?void 0:Ye(t.sub),upper:t.sup===void 0?void 0:Ye(t.sup)})-1;return`${Wt}${u}${ks}`}parseWhitespace(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return" "}parseCommand(){if(this.position++,this.position>=this.source.length)return this.supported=!1,"";let e="",t=this.source[this.position]??"";if(t===`
94
+ `||t==="\r")return this.position++,t==="\r"&&this.source[this.position]===`
95
+ `&&this.position++," ";if(/[A-Za-z]/.test(t)){let n=this.position;for(;this.position<this.source.length&&/[A-Za-z]/.test(this.source[this.position]??"");)this.position++;e=this.source.slice(n,this.position)}else e=t,this.position++;if(e==="\\")return`
96
+ `;if(Bd.has(e))return" ";if(Dd.has(e))return Ml;if(Nd.has(e)){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return""}if(Wd.has(e))return"";if(e==="{"||e==="}"||e==="$"||e==="%"||e==="#"||e==="_"||e==="&")return e;if(e==="|")return"\u2016";if(e==="not"){let n=this.parseRequiredArgument(!1).trim(),o=Pd[n];if(o!==void 0)return` ${o} `;let l=Array.from(n);return l.length===0?(this.supported=!1,""):` ${l[0]}\u0338${l.slice(1).join("")} `}if(Ad.has(e))return this.parseOperator(e,"bracket",!0,!0);let i=Id[e];if(i!==void 0)return Ld.has(e)?this.parseOperator(i,"script",!0):e==="cdot"||e==="times"||Ed.has(e)?` ${i} `:i;if(Rd.has(e))return`${Rl}${e}${Qe}`;if(Fd.has(e))return"";if(e==="left"||e==="middle"||e==="right")return this.source[this.position]==="."&&this.position++,"";if(e==="frac"||e==="dfrac"||e==="tfrac"){let n=this.display&&this.stackFractions&&e!=="tfrac",o=this.parseRequiredArgument(!n),l=this.parseRequiredArgument(!n);if(n){let a=this.layoutNodes.push({type:"fraction",numerator:Ye(o),denominator:Ye(l)})-1;return`${Wt}${a}${ks}`}return qd(o,l)}if(e==="sqrt"){let n=this.parseOptionalArgument()?.trim(),o=this.parseRequiredArgument();return n===void 0||n==="2"?yi(o):n==="3"?yi(o,"\u221B"):n==="4"?yi(o,"\u221C"):`${Ge(n,"sup")}${yi(o)}`}if(e==="boxed"||e==="fbox")return`[${this.parseRequiredArgument().trim()}]`;if(e==="binom"||e==="dbinom"||e==="tbinom")return`(${this.parseRequiredArgument()} choose ${this.parseRequiredArgument()})`;let r=Kd[e];if(r!==void 0){let n=this.parseRequiredArgument();return Array.from(n).length===1?`${n}${r}`:`${e}(${n})`}if(e==="mathbb"){let n=this.parseRequiredArgument();return Array.from(n,o=>$d[o]??o).join("")}if(e==="operatorname"){let n=this.source[this.position]==="*";n&&this.position++;let o=Ye(this.parseRequiredArgument()).trim();return this.parseOperator(o,"bracket",n,!0)}if(e==="mod"||e==="bmod")return" mod ";if(e==="pmod"||e==="pod"){let n=this.parseRequiredArgument().trim();return e==="pmod"?` (mod ${n})`:` (${n})`}if(e==="overset"||e==="stackrel"){let n=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${Ge(n,"sup")}`}if(e==="underset"){let n=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${Ge(n,"sub")}`}if(Hd.has(e)){let n=this.parseRequiredArgument();return e.startsWith("text")||e==="mbox"?n:n.trim()}return e==="begin"?this.parseEnvironment():e==="end"?(this.supported=!1,""):(this.supported=!1,`\\${e}`)}parseOperator(e,t,i,r=!1){let n=i,o=this.position;for(;o<this.source.length&&/[ \t]/.test(this.source[o]??"");)o++;let l=/^\\(limits|nolimits)(?![A-Za-z])/.exec(this.source.slice(o));l&&(n=l[1]==="limits",this.position=o+l[0].length);let a,c;for(;;){let u=this.position;for(;u<this.source.length&&/[ \t]/.test(this.source[u]??"");)u++;let d=this.source[u];if(d!=="_"&&d!=="^")break;this.position=u+1;let f=Ye(this.parseRequiredArgument(!1)).replaceAll(" ","");d==="_"?(a!==void 0&&(this.supported=!1),a=f):(c!==void 0&&(this.supported=!1),c=f)}if(this.display&&n&&(a!==void 0||c!==void 0)){let u=this.layoutNodes.push({type:"operator",operator:e,lower:a,upper:c})-1;return`${Wt}${u}${ks}`}let h=e;return a!==void 0&&(h+=t==="bracket"?`[${a}]`:Ge(a,"sub")),c!==void 0&&(h+=Ge(c,"sup")),r?` ${h} `:h}parseRequiredArgument(e=!0){let t=this.stackFractions;this.stackFractions=t&&e;let i=this.parseRequiredArgumentValue();return this.stackFractions=t,i}parseRequiredArgumentValue(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;if(this.position>=this.source.length)return this.supported=!1,"";if(this.source[this.position]==="{")return this.position++,this.parseSequence("}");if(this.source[this.position]==="\\")return this.parseCommand();let e=this.source[this.position]??"";return this.position++,e}parseOptionalArgument(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="[")return;let e=this.source.indexOf("]",this.position+1);if(e<0){this.supported=!1;return}let t=this.source.slice(this.position+1,e);return this.position=e+1,this.renderNested(t)}readRawGroup(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="{"){this.supported=!1;return}let e=++this.position,t=1;for(;this.position<this.source.length;){let i=this.source[this.position];if(i==="\\"){this.position+=2;continue}if(i==="{"&&t++,i==="}"&&t--,t===0){let r=this.source.slice(e,this.position);return this.position++,r}this.position++}this.supported=!1}splitEnvironmentRows(e){return e.split(/\\\\(?:\[[^\]\n]*\])?/)}parseEnvironment(){let e=this.readRawGroup();if(!e)return"";let t=`\\end{${e}}`,i=this.source.indexOf(t,this.position);if(i<0)return this.supported=!1,"";let r=this.source.slice(this.position,i);if(this.position=i+t.length,e==="equation"||e==="equation*"||e==="displaymath")return this.renderNested(r).trim();if(e==="aligned"||e==="align"||e==="align*"||e==="alignedat"||e==="alignat"||e==="alignat*"||e==="gather"||e==="gathered"||e==="multline"||e==="multline*"||e==="split"){let n=["alignedat","alignat","alignat*"].includes(e),o=n?r.replace(/^\s*\{[^}]*\}/,""):r;return this.splitEnvironmentRows(o).map(l=>{let a=l.split("&"),c=n?Array.from({length:Math.ceil(a.length/2)},(h,u)=>a.slice(u*2,u*2+2).join("")).join(" "):a.join("");return this.renderNested(c).trim()}).filter(Boolean).join(`
97
+ `)}if(e==="cases"||e==="cases*")return this.renderCases(r);if(["array","matrix","smallmatrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix"].includes(e)){let n=e==="array"?r.replace(/^\s*\{[^}]*\}/,""):r;return this.renderMatrix(e,n)}return this.supported=!1,r}renderCases(e){let t=this.splitEnvironmentRows(e).map(c=>c.split("&").map(h=>this.renderNested(h,!1).trim())).filter(c=>c.some(Boolean)),i=Math.max(0,...t.map(c=>S((c[0]??"").replace(/,\s*$/,"")))),r=t.map(c=>{let h=(c[0]??"").replace(/,\s*$/,""),u=c[1]??"";if(!u)return h;let d=/^(?:if|when|for|otherwise)\b/i.test(u)?" ":" if ";return`${h}${wi.repeat(i-S(h))}${d}${u}`});if(r.length<=1)return r.length===0?"":`\u23A7 ${r[0]}`;let n=Math.floor(r.length/2),o=[...r];r.length%2===0&&o.splice(n,0,void 0);let l=o.map((c,h)=>{let u=h===0?"\u23A7":h===o.length-1?"\u23A9":"\u23A8";return c===void 0?u:`${u} ${c}`}),a=this.layoutNodes.push({type:"matrix",lines:l,baseline:n})-1;return`${Wt}${a}${ks}`}renderMatrix(e,t){let i=this.splitEnvironmentRows(t).map(c=>c.split("&").map(h=>this.renderNested(h,!1).trim())).filter(c=>c.some(Boolean)),r=Math.max(0,...i.map(c=>c.length)),n=Array.from({length:r},(c,h)=>Math.max(0,...i.map(u=>S(u[h]??"")))),o=i.map(c=>Array.from({length:r},(h,u)=>{let d=c[u]??"";return`${d}${wi.repeat(Math.max(0,(n[u]??0)-S(d)))}`}).join(" \u2502 ")),l;if(e==="array"||e==="matrix"||e==="smallmatrix")l=o;else{let h={pmatrix:["\u239B","\u239E","\u239C","\u239F","\u239D","\u23A0"],bmatrix:["\u23A1","\u23A4","\u23A2","\u23A5","\u23A3","\u23A6"],Bmatrix:["\u23A7","\u23AB","\u23A8","\u23AC","\u23A9","\u23AD"],vmatrix:["\u2502","\u2502","\u2502","\u2502","\u2502","\u2502"],Vmatrix:["\u2551","\u2551","\u2551","\u2551","\u2551","\u2551"]}[e];if(!h)return this.supported=!1,o.join(`
98
+ `);l=o.map((u,d)=>{let f=d===0?h[0]:d===o.length-1?h[4]:h[2],p=d===0?h[1]:d===o.length-1?h[5]:h[3];return`${f} ${u} ${p}`})}if(l.length<=1)return l[0]??"";let a=this.layoutNodes.push({type:"matrix",lines:l,baseline:0})-1;return`${Wt}${a}${ks}`}renderNested(e,t=!0){let i=new s(e,this.layoutNodes,this.display&&t).render();return i===void 0?(this.supported=!1,e):i}};function Cs(s,e={}){let t=[],i=new Fr(s,t,e.display===!0).render();if(i===void 0)return;if(t.length===0)return i.replaceAll(wi," ");let r=Ss(i,t).lines,n=Math.min(...r.filter(o=>o.trim()).map(o=>o.length-o.trimStart().length));return r.map(o=>o.slice(n).trimEnd()).join(`
99
+ `).trimEnd().replaceAll(wi," ")}var Qd=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,Hr=class extends kt{url(e){let t=super.url(e);if(!t)return;let i=t.raw.search(Zi);return i<0?t:super.url(t.raw.slice(0,i))}del(e){let t=Qd.exec(e);if(!t)return;let i=t[2];return{type:"del",raw:t[0],text:i,tokens:this.lexer.inlineTokens(i)}}};function Xd(s,e){let t=0;for(let i=e-1;i>=0&&s[i]==="\\";i--)t++;return t%2===1}function Zd(s,e,t){let i=s.indexOf(e,t);for(;i>=0&&Xd(s,i);)i=s.indexOf(e,i+e.length);return i}function Al(s){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(s)}function Jd(s){let e="",t="";if(s.startsWith("$$"))e="$$",t="$$";else if(s.startsWith("\\("))e="\\(",t="\\)";else if(s.startsWith("\\["))e="\\[",t="\\]";else if(s.startsWith("$")&&!/^\$\s/.test(s))e="$",t="$";else return;let i=Zd(s,t,e.length);if(i>=0&&e==="$"&&(/\s$/.test(s.slice(e.length,i))||/^\d/.test(s.slice(i+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(s.slice(e.length,i))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(s.slice(i+1))||s.slice(e.length,i).includes("`")))return;if(i<0){let o=s.slice(e.length);return e.startsWith("\\")||Al(o)?{type:"latex",raw:s,text:o,pending:!0}:void 0}let r=s.slice(e.length,i);return!r||r.includes(`
100
+ `)?void 0:{type:"latex",raw:s.slice(0,i+t.length),text:r}}var ef=/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;function ki(s){let e=s.split(`
101
+ `);for(let t=0;t<e.length-1;t++){let i=e[t+1];if((i.includes("|")||e[t].includes("|"))&&ef.test(i))return!0}return!1}function tf(s){let e=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(s);if(e?.[1]&&!ki(e[1]))return{type:"latexBlock",raw:e[0],text:e[1].trim()};let t=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(s);if(t?.[1]&&!ki(t[1]))return{type:"latexBlock",raw:t[0],text:t[1].trim()};let i=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(s);if(i?.[1]&&!ki(i[1]))return{type:"latexBlock",raw:i[0],text:i[1],pending:!0};let r=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(s);if(r?.[1]&&Al(r[1])&&!ki(r[1]))return{type:"latexBlock",raw:r[0],text:r[1],pending:!0}}var sf=[{name:"latexBlock",level:"block",start(s){let e=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(s);return e?e.index+(e[0].startsWith(`
102
+ `)?1:0):void 0},tokenizer:tf},{name:"latex",level:"inline",start(s){let e=[s.indexOf("$"),s.indexOf("\\("),s.indexOf("\\[")].filter(t=>t>=0);return e.length>0?Math.min(...e):void 0},tokenizer:Jd}];function Kr(s){let e=s[s.length-1];if(e?.type==="list"){Kr(e.items[e.items.length-1]?.tokens??[]);return}if(e?.type==="blockquote"){Kr(e.tokens??[]);return}if(e?.type!=="code")return;let t=/^(`{3,}|~{3,})/.exec(e.raw)?.[1],i=e.raw.split(`
103
+ `).pop();!t||!i||i.length>=t.length||i!==t[0]?.repeat(i.length)||(e.text=e.text.slice(0,-i.length).replace(/\n$/,""))}var rf=/<!--[\s\S]*?(?:-->|$)/g;function Ll(s){return s.replace(rf,"")}function Vr(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(t.type==="list")for(let i of t.items)Vr(i.tokens);else t.type==="blockquote"?Vr(t.tokens??[]):t.type==="html"&&Ll(t.raw).trim()===""&&(s.splice(e,1),s[e]?.type==="space"&&(e===0||s[e-1]?.type==="space")?s.splice(e,1):e===s.length&&s[e-1]?.type==="space"&&s.splice(--e,1))}}var qr=new ds;qr.setOptions({tokenizer:new Hr});qr.use({tokenizer:{emStrong:vl().tokenizer?.emStrong},extensions:[...sf]});var Si=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;cachedTokens;blocks;blockHighlightedCode;constructor(e,t,i,r,n,o){this.text=e,this.paddingX=t,this.paddingY=i,this.theme=r,this.defaultTextStyle=n,this.options=o?{...o}:{}}setText(e){this.text=e,this.clearRenderCache()}invalidate(){this.clearRenderCache(),this.blocks=void 0,this.defaultStylePrefix=void 0}clearRenderCache(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,e-this.paddingX*2),i=this.options.transform?.(this.text,t)??this.text;if(!i||i.trim()===""){this.blocks=void 0;let g=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=g,g}let r=i.replace(/\t/g," "),n=this.cachedTokens?.deref(),o=n?.source===r?n.tokens:void 0;o||(o=qr.lexer(r),Kr(o),Vr(o),this.cachedTokens=new WeakRef({source:r,tokens:o}));let l=Object.keys(o.links).length===0,a=this.blocks?.deref(),c=new Map;this.blocks=new WeakRef(c);let h=[];for(let g=0;g<o.length;g++){let x=o[g],m=o[g+1]?.type,b=(l?c.get(x.raw)??a?.get(x.raw):void 0)??{width:-1,nextTokenType:m,lines:[],highlightedCode:new Map};(b.width!==e||b.nextTokenType!==m)&&this.renderBlock(b,x,m,e,t),l&&c.set(x.raw,b);for(let k of b.lines)h.push(k)}let u=this.defaultTextStyle?.bgColor,d=" ".repeat(e),f=[];for(let g=0;g<this.paddingY;g++){let x=u?ct(d,e,u):d;f.push(x)}Be(f);let p=f.concat(h,f);return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=p,p.length>0?p:[""]}renderBlock(e,t,i,r,n){this.blockHighlightedCode=e.highlightedCode;let o=" ".repeat(this.paddingX),l=" ".repeat(this.paddingX),a=this.defaultTextStyle?.bgColor,c=[],h=this.renderToken(t,n,i).flatMap(u=>W(u)?u.split(`
104
+ `):[u]);for(let u of h){if(W(u)){c.push(u);continue}for(let d of ne(u,n)){let f=o+d+l;if(a)c.push(ct(f,r,a));else{let p=Math.max(0,r-S(f));c.push(f+" ".repeat(p))}}}this.blockHighlightedCode=void 0,Be(c),e.lines=c,e.width=r,e.nextTokenType=i}applyDefaultStyle(e){if(!this.defaultTextStyle)return e;let t=e;return this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t)),t}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let e="\0",t=e;this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t));let i=t.indexOf(e);return this.defaultStylePrefix=i>=0?t.slice(0,i):"",this.defaultStylePrefix}getStylePrefix(e){let i=e("\0"),r=i.indexOf("\0");return r>=0?i.slice(0,r):""}getDefaultInlineStyleContext(){return{applyText:e=>this.applyDefaultStyle(e),stylePrefix:this.getDefaultStylePrefix()}}renderToken(e,t,i,r){let n=[];switch(e.type){case"heading":{let o=e.depth,l=`${"#".repeat(o)} `,a;o===1?a=d=>this.theme.heading(this.theme.bold(this.theme.underline(d))):a=d=>this.theme.heading(this.theme.bold(d));let c={applyText:a,stylePrefix:this.getStylePrefix(a)},h=this.renderInlineTokens(e.tokens||[],c),u=o>=3?a(l)+h:h;n.push(u),i&&i!=="space"&&n.push("");break}case"paragraph":{let o=this.renderInlineTokens(e.tokens||[],r);n.push(o),i&&i!=="list"&&i!=="space"&&n.push("");break}case"text":n.push(this.renderInlineTokens([e],r));break;case"latexBlock":{let o=e,l=!o.pending&&this.options.renderLatex!==!1?Cs(o.text,{display:!0}):void 0;(l===void 0||l.split(`
105
+ `).some(a=>S(a)>t))&&(l=o.raw.trim());for(let a of l.split(`
106
+ `))n.push(this.applyDefaultStyle(a));i&&i!=="space"&&n.push("");break}case"code":{let o=this.theme.codeBlockIndent??" ";if(n.push(this.theme.codeBlockBorder(`\`\`\`${e.lang||""}`)),this.theme.highlightCode){let l=`${e.lang??""}\0${e.text}`,a=this.blockHighlightedCode?.get(l);a||(a=this.theme.highlightCode(e.text,e.lang),this.blockHighlightedCode?.set(l,a));for(let c of a)n.push(`${o}${c}`)}else{let l=e.text.split(`
107
+ `);for(let a of l)n.push(`${o}${this.theme.codeBlock(a)}`)}n.push(this.theme.codeBlockBorder("```")),i&&i!=="space"&&n.push("");break}case"list":{let o=this.renderList(e,0,t,r);n.push(...o);break}case"table":{let o=this.renderTable(e,t,i,r);n.push(...o);break}case"blockquote":{let o=f=>this.theme.quote(this.theme.italic(f)),l=this.getStylePrefix(o),a=f=>{if(!l)return o(f);let p=f.replace(/\x1b\[0m/g,`\x1B[0m${l}`);return o(p)};if(t<3){let f=e.tokens||[];for(let p=0;p<f.length;p++)for(let g of this.renderToken(f[p],t,f[p+1]?.type,r))n.push(g);break}let c=t-2,h={applyText:f=>f,stylePrefix:l},u=e.tokens||[],d=[];for(let f=0;f<u.length;f++){let p=u[f],g=u[f+1];for(let x of this.renderToken(p,c,g?.type,h))d.push(x)}for(;d.length>0&&d[d.length-1]==="";)d.pop();for(let f of d){let p=a(f),g=ne(p,c);for(let x of g)n.push(this.theme.quoteBorder("\u2502 ")+x)}i&&i!=="space"&&n.push("");break}case"hr":n.push(this.theme.hr("\u2500".repeat(Math.min(t,80)))),i&&i!=="space"&&n.push("");break;case"html":"raw"in e&&typeof e.raw=="string"&&n.push(this.applyDefaultStyle(Ll(e.raw).trim()));break;case"space":n.push("");break;default:"text"in e&&typeof e.text=="string"&&n.push(e.text)}return n}renderInlineTokens(e,t){let i="",r=t??this.getDefaultInlineStyleContext(),{applyText:n,stylePrefix:o}=r,l=c=>c.split(`
108
+ `).map(u=>n(u)).join(`
109
+ `),a=!1;for(let c=0;c<e.length;c++){let h=e[c];switch(a&&h.type==="text"&&!h.tokens?.length&&/^[ \t]/.test(h.text)&&(h={...h,text:h.text.replace(/^[ \t]+/,"")}),a=!1,h.type){case"latex":{let u=h,d=!u.pending&&this.options.renderLatex!==!1?Cs(u.text)??u.raw:u.raw;i+=l(d);break}case"escape":i+=l(this.options.preserveBackslashEscapes?h.raw:h.text);break;case"text":h.tokens&&h.tokens.length>0?i+=this.renderInlineTokens(h.tokens,r):i+=l(h.text);break;case"paragraph":i+=this.renderInlineTokens(h.tokens||[],r);break;case"strong":{let u=this.renderInlineTokens(h.tokens||[],r);i+=this.theme.bold(u)+o;break}case"em":{let u=this.renderInlineTokens(h.tokens||[],r);i+=this.theme.italic(u)+o;break}case"codespan":i+=this.theme.code(h.text)+o;break;case"link":{let u=this.renderInlineTokens(h.tokens||[],r),d=this.theme.link(this.theme.underline(u));if(se().hyperlinks)i+=xs(d,h.href)+o;else{let f=h.href.startsWith("mailto:")?h.href.slice(7):h.href;h.text===h.href||h.text===f?i+=d+o:i+=d+this.theme.linkUrl(` (${h.href})`)+o}break}case"br":i+=`
110
+ `;break;case"del":{let u=this.renderInlineTokens(h.tokens||[],r);i+=this.theme.strikethrough(u)+o;break}case"html":h.raw.startsWith("<!--")?a=c===0||/[ \t]$/.test(e[c-1].raw):i+=l(h.raw);break;default:"text"in h&&typeof h.text=="string"&&(i+=l(h.text))}}for(;o&&i.endsWith(o);)i=i.slice(0,-o.length);return i}getOrderedListMarker(e){let t=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(e.raw);return t?`${t[1]} `:void 0}getUnorderedListMarker(e){let t=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(e.raw);return t?`${t[1]} `:void 0}renderList(e,t,i,r){let n=[],o=" ".repeat(t),l=typeof e.start=="number"?e.start:1;for(let a=0;a<e.items.length;a++){let c=e.items[a],h=a===e.items.length-1,u=e.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(c)??`${l+a}. `:`${l+a}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(c)??"- ":"- ",d=c.task?`[${c.checked?"x":" "}] `:"",f=u+d,p=o+this.theme.listBullet(f),g=o+" ".repeat(S(f)),x=Math.max(1,i-S(p)),m=!1;for(let w of c.tokens){if(w.type==="list"){n.push(...this.renderList(w,t+1,i,r)),m=!0;continue}let b=this.renderToken(w,x,void 0,r);for(let k of b)for(let v of ne(k,x)){let y=m?g:p;n.push(y+v),m=!0}}m||n.push(p),e.loose&&!h&&n.push("")}return n}getLongestWordWidth(e,t){let i=e.split(/\s+/).filter(n=>n.length>0),r=0;for(let n of i)r=Math.max(r,S(n));return t===void 0?r:Math.min(r,t)}wrapCellText(e,t,i=""){let r=ne(e,Math.max(1,t));return r.map((n,o)=>{let l=o<r.length-1?"\x1B[22;23;24;25;27;28;29;39m":"";return`${n}${l}${i}`})}renderTable(e,t,i,r){let n=[],o=e.header.length;if(o===0)return n;let l=3*o+1,a=t-l;if(a<o){let y=e.raw?ne(e.raw,t):[];return i&&i!=="space"&&y.push(""),y}let c=30,h=[],u=[];for(let y=0;y<o;y++){let C=this.renderInlineTokens(e.header[y].tokens||[],r);h[y]=S(C),u[y]=Math.max(1,this.getLongestWordWidth(C,c))}for(let y of e.rows)for(let C=0;C<y.length;C++){let I=this.renderInlineTokens(y[C].tokens||[],r);h[C]=Math.max(h[C]||0,S(I)),u[C]=Math.max(u[C]||1,this.getLongestWordWidth(I,c))}let d=u,f=d.reduce((y,C)=>y+C,0);if(f>a){d=new Array(o).fill(1);let y=a-o;if(y>0){let C=u.reduce((M,P)=>M+Math.max(0,P-1),0),I=u.map(M=>{let P=Math.max(0,M-1);return C>0?Math.floor(P/C*y):0});for(let M=0;M<o;M++)d[M]+=I[M]??0;let A=I.reduce((M,P)=>M+P,0),T=y-A;for(let M=0;T>0&&M<o;M++)d[M]++,T--}f=d.reduce((C,I)=>C+I,0)}let p=h.reduce((y,C)=>y+C,0)+l,g;if(p<=t)g=h.map((y,C)=>Math.max(y,d[C]));else{let y=h.reduce((T,M,P)=>T+Math.max(0,M-d[P]),0),C=Math.max(0,a-f);g=d.map((T,M)=>{let P=h[M],B=Math.max(0,P-T),F=0;return y>0&&(F=Math.floor(B/y*C)),T+F});let I=g.reduce((T,M)=>T+M,0),A=a-I;for(;A>0;){let T=!1;for(let M=0;M<o&&A>0;M++)g[M]<h[M]&&(g[M]++,A--,T=!0);if(!T)break}}let x=g.map(y=>"\u2500".repeat(y));n.push(`\u250C\u2500${x.join("\u2500\u252C\u2500")}\u2500\u2510`);let m=e.header.map((y,C)=>{let I=this.renderInlineTokens(y.tokens||[],r);return this.wrapCellText(I,g[C],r?.stylePrefix)}),w=Math.max(...m.map(y=>y.length));for(let y=0;y<w;y++){let C=m.map((I,A)=>{let T=I[y]||"",M=T+" ".repeat(Math.max(0,g[A]-S(T)));return this.theme.bold(M)});n.push(`\u2502 ${C.join(" \u2502 ")} \u2502`)}let k=`\u251C\u2500${g.map(y=>"\u2500".repeat(y)).join("\u2500\u253C\u2500")}\u2500\u2524`;n.push(k);for(let y=0;y<e.rows.length;y++){let I=e.rows[y].map((T,M)=>{let P=this.renderInlineTokens(T.tokens||[],r);return this.wrapCellText(P,g[M],r?.stylePrefix)}),A=Math.max(...I.map(T=>T.length));for(let T=0;T<A;T++){let M=I.map((P,B)=>{let F=P[T]||"";return F+" ".repeat(Math.max(0,g[B]-S(F)))});n.push(`\u2502 ${M.join(" \u2502 ")} \u2502`)}y<e.rows.length-1&&n.push(k)}let v=g.map(y=>"\u2500".repeat(y));return n.push(`\u2514\u2500${v.join("\u2500\u2534\u2500")}\u2500\u2518`),i&&i!=="space"&&n.push(""),n}};var Ci=class{child;onMouse;constructor(e,t){this.child=e,this.onMouse=t}render(e){return this.child.render(e)}handleMouse(e){return qe(this.child,e)??this.onMouse(e)}invalidate(){this.child.invalidate()}};var Ft=class extends ae{child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(e,t={}){if(super(),t.axis!==void 0&&t.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${t.axis}`);this.child=e,this.children.push(e),this.followEnd=(t.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=t.primary??!1,this.overscroll=t.overscroll??"chain",this.currentScrollbar=t.scrollbar??"hidden",this.scrollbarTrackStyle=t.scrollbarTrackStyle??(i=>`\x1B[90m${i}\x1B[39m`),this.scrollbarThumbStyle=t.scrollbarThumbStyle??(i=>`\x1B[37m${i}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(t.scrollbarHideDelayMs??1e3))}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get viewportHeight(){return this.currentViewportHeight}get scrollbar(){return this.currentScrollbar}get isScrollbarVisible(){return this.scrollbar==="always"?this.currentViewportHeight>0:this.scrollbar==="auto"&&this.contentHeight>this.currentViewportHeight&&this.transientScrollbarVisible}get isScrollbarActive(){return this.scrollbarActive}setScrollbar(e){e!==this.currentScrollbar&&(this.currentScrollbar=e,e!=="auto"?this.hideTransientScrollbar():this.scrollbarActive&&this.markScrollbarActivity(),this.requestRenderCallback?.())}getContentWidth(e){return this.scrollbar==="always"&&e>1?e-1:e}markScrollbarActivity(){this.scrollbar!=="auto"||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=!0,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=!1,this.requestRenderCallback?.()},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref()))}hideTransientScrollbar(){this.transientScrollbarVisible=!1,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0)}setScrollbarActive(e){e!==this.scrollbarActive&&(this.scrollbarActive=e,this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollTo(e,t={}){let i=Number.isFinite(e)?Math.trunc(e):this.currentScrollTop,r=Math.max(0,this.contentHeight-this.currentViewportHeight),n=Math.max(0,Math.min(r,i)),o=t.disableFollow===!0&&n===r,l=!o&&this.followEnd&&n===r;if(n===this.currentScrollTop&&l===this.followingEnd&&o===this.followSuppressedAtEnd)return;let a=n!==this.currentScrollTop;this.currentScrollTop=n,this.followingEnd=l,this.followSuppressedAtEnd=o,a&&this.markScrollbarActivity(),this.requestRenderCallback?.()}scrollBy(e){let t=Number.isFinite(e)?Math.trunc(e):0;if(t===0)return 0;let i=Math.max(0,this.contentHeight-this.currentViewportHeight),r=this.followingEnd?i:this.currentScrollTop,n=Math.max(0,Math.min(i,r+t)),o=n-r,l=this.followingEnd;return this.currentScrollTop=n,this.followingEnd=this.followEnd&&n===i,this.followSuppressedAtEnd=!1,o!==0&&this.markScrollbarActivity(),(o!==0||this.followingEnd!==l)&&this.requestRenderCallback?.(),t-o}scrollToStart(){let e=this.currentScrollTop!==0||this.followingEnd!==(this.followEnd&&this.contentHeight<=this.currentViewportHeight);this.currentScrollTop=0,this.followingEnd=this.followEnd&&this.contentHeight<=this.currentViewportHeight,this.followSuppressedAtEnd=!1,e&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollToEnd(){let e=Math.max(0,this.contentHeight-this.currentViewportHeight),t=this.currentScrollTop!==e||this.followingEnd!==this.followEnd;this.currentScrollTop=e,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=!1,t&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}updateLayout(e,t,i){this.contentHeight=Math.max(0,Math.floor(e)),this.currentViewportHeight=Math.max(0,Math.floor(t)),this.requestRenderCallback=i;let r=Math.max(0,this.contentHeight-this.currentViewportHeight);this.followingEnd?this.currentScrollTop=r:this.currentScrollTop=Math.max(0,Math.min(this.currentScrollTop,r)),this.currentScrollTop<r&&(this.followSuppressedAtEnd=!1),this.followEnd&&this.currentScrollTop===r&&!this.followSuppressedAtEnd&&(this.followingEnd=!0),this.contentHeight<=this.currentViewportHeight&&this.hideTransientScrollbar()}addChild(e){throw new Error("ScrollView has exactly one child")}removeChild(e){throw new Error("ScrollView child cannot be removed")}clear(){throw new Error("ScrollView child cannot be cleared")}render(e){let t=this.getContentWidth(e),i=this.child.render(t);return t===e?i:i.map(r=>`${r} `)}[Ot](){return{type:"scroll",component:this.child,state:this}}};var Ti=class{capturesViewportInput=!0;items;filteredItems;theme;selectedIndex=0;mousePressedIndex;maxVisible;onChange;onCancel;searchInput;searchEnabled;submenuComponent=null;submenuItemIndex=null;navigateAfterClose=null;constructor(e,t,i,r,n,o={}){this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=i,this.onChange=r,this.onCancel=n,this.searchEnabled=o.enableSearch??!1,this.searchEnabled&&(this.searchInput=new $e)}updateValue(e,t){let i=this.items.find(r=>r.id===e);i&&(i.currentValue=t)}selectItem(e){let i=(this.searchEnabled?this.filteredItems:this.items).findIndex(r=>r.id===e);i!==-1&&(this.selectedIndex=i)}invalidate(){this.submenuComponent?.invalidate?.()}render(e){return this.submenuComponent?this.submenuComponent.render(e):this.renderMainList(e)}renderMainList(e){let t=[];if(this.searchEnabled&&this.searchInput&&(t.push(...this.searchInput.render(e)),t.push("")),this.items.length===0)return t.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(t,e),t;let i=this.getDisplayItems();if(i.length===0)return t.push(D(this.theme.hint(" No matching settings"),e)),this.addHintLine(t,e),t;let{startIndex:r,endIndex:n}=this.getVisibleRange(i),o=Math.min(36,Math.max(...this.items.map(a=>S(a.label))));for(let a=r;a<n;a++){let c=i[a];if(!c)continue;let h=a===this.selectedIndex,u=h?this.theme.cursor:" ",d=S(u),f=c.label+" ".repeat(Math.max(0,o-S(c.label))),p=this.theme.label(f,h),g=" ",x=d+o+S(g),m=e-x-2,w=this.theme.value(D(c.currentValue,m,""),h);t.push(D(u+p+g+w,e))}if(r>0||n<i.length){let a=` (${this.selectedIndex+1}/${i.length})`;t.push(this.theme.hint(D(a,e-2,"")))}let l=i[this.selectedIndex];if(l?.description){t.push("");let a=ne(l.description,e-4);for(let c of a)t.push(this.theme.description(` ${c}`))}return this.addHintLine(t,e),t}handleMouse(e){if(this.submenuComponent){let l=this.submenuComponent.handleMouse?.(e);return l?{...l,focus:!0}:void 0}if(this.searchEnabled&&this.searchInput){if(e.y===0){let l=this.searchInput.handleMouse?.(e);return l?{...l,focus:!0}:void 0}if(e.y===1)return}let t=this.getDisplayItems();if(t.length===0)return;if(e.type==="wheel"&&e.wheelDelta){let l=e.wheelDelta<0?-1:1,a=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(t.length-1,this.selectedIndex+l)),{handled:!0,render:this.selectedIndex!==a}}if(e.button!=="left"||e.type!=="press"&&e.type!=="click")return;let i=this.searchEnabled?2:0,{startIndex:r,endIndex:n}=this.getVisibleRange(t),o=r+e.y-i;if(!(o<r||o>=n)){if(e.type==="press")return this.mousePressedIndex=o,this.selectedIndex=o,{handled:!0,focus:!0};if(e.type==="click")return this.selectedIndex=this.mousePressedIndex??o,this.mousePressedIndex=void 0,this.activateItem(),{handled:!0}}}handleInput(e){if(this.submenuComponent){this.submenuComponent.handleInput?.(e);return}let t=U(),i=this.getDisplayItems(),r=yt(t,e,this.selectedIndex,i.length,this.maxVisible);if(t.matches(e,"tui.select.up")){if(i.length===0)return;this.selectedIndex=this.selectedIndex===0?i.length-1:this.selectedIndex-1}else if(t.matches(e,"tui.select.down")){if(i.length===0)return;this.selectedIndex=this.selectedIndex===i.length-1?0:this.selectedIndex+1}else if(r!==void 0){if(i.length===0)return;this.selectedIndex=r}else if(t.matches(e,"tui.select.confirm")||e===" "&&(!this.searchEnabled||this.searchInput?.getValue().length===0))this.activateItem();else if(t.matches(e,"tui.select.cancel"))this.onCancel();else if(this.searchEnabled&&this.searchInput){let n=this.searchInput.getValue();this.searchInput.handleInput(e);let o=this.searchInput.getValue();o!==n&&this.applyFilter(o)}}getDisplayItems(){return this.searchEnabled?this.filteredItems:this.items}getVisibleRange(e){let t=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),e.length-this.maxVisible));return{startIndex:t,endIndex:Math.min(t+this.maxVisible,e.length)}}activateItem(){let e=this.getDisplayItems()[this.selectedIndex];if(e){if(e.submenu)this.submenuItemIndex=this.selectedIndex,this.submenuComponent=e.submenu(e.currentValue,(t,i)=>{t!==void 0&&(e.currentValue=t,this.onChange(e.id,t)),i?.navigateTo&&(this.navigateAfterClose=i.navigateTo),this.closeSubmenu()});else if(e.values&&e.values.length>0){let i=(e.values.indexOf(e.currentValue)+1)%e.values.length,r=e.values[i];e.currentValue=r,this.onChange(e.id,r)}}}closeSubmenu(){if(this.submenuComponent=null,this.navigateAfterClose!==null){let e=this.navigateAfterClose;this.navigateAfterClose=null,this.submenuItemIndex=null,this.selectItem(e),this.activateItem()}else this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null)}applyFilter(e){this.filteredItems=Ke(this.items,e,t=>t.label),this.selectedIndex=0}addHintLine(e,t){e.push(""),e.push(D(this.theme.hint(this.searchEnabled?" Type to search \xB7 Enter/Space to change \xB7 Esc to cancel":" Enter/Space to change \xB7 Esc to cancel"),t))}};var vi=class{lines;constructor(e=1){this.lines=e}setLines(e){this.lines=e}invalidate(){}render(e){let t=[];for(let i=0;i<this.lines;i++)t.push("");return t}};var Mi=class{text;paddingX;paddingY;constructor(e,t=0,i=0){this.text=e,this.paddingX=t,this.paddingY=i}invalidate(){}render(e){let t=[],i=" ".repeat(e);for(let p=0;p<this.paddingY;p++)t.push(i);let r=Math.max(1,e-this.paddingX*2),n=this.text,o=this.text.indexOf(`
111
+ `);o!==-1&&(n=this.text.substring(0,o));let l=D(n,r),a=" ".repeat(this.paddingX),c=" ".repeat(this.paddingX),h=a+l+c,u=S(h),d=Math.max(0,e-u),f=h+" ".repeat(d);t.push(f);for(let p=0;p<this.paddingY;p++)t.push(i);return t}};var Ii=class extends Bt{layoutType="vstack";constructor(e=[],t={}){super(e,t)}render(e){let t={width:Math.max(1,e),height:Number.MAX_SAFE_INTEGER},i=Dt(this.entries,t),r=i.map(l=>l.component.render(t.width)),n=Ue(i,r.map(l=>l.length),void 0,this.gap),o=[];for(let l=0;l<i.length;l++){if(l>0)for(let c=0;c<this.gap;c++)o.push("");let a=r[l].slice(0,n[l]);o.push(...a);for(let c=a.length;c<n[l];c++)o.push("")}return o}};import{createRequire as cf}from"node:module";import*as Pl from"node:path";import{createRequire as nf}from"node:module";import{dirname as Ur,join as Ri}from"node:path";import{fileURLToPath as of}from"node:url";var lf=nf(import.meta.url),af="@earendil-works/pi-tui";function El(s,e={}){let t=Ur(of(e.moduleUrl??import.meta.url)),i=[];try{let r=(e.resolvePackage??lf.resolve)(af);i.push(Ri(Ur(r),"..",s))}catch{}return i.push(Ri(t,"..",s),Ri(t,s),Ri(Ur(e.execPath??process.execPath),s)),Array.from(new Set(i))}var hf=cf(import.meta.url),Ai=new Map;function $l(s,e=""){let t=process.arch;if(t!=="x64"&&t!=="arm64")return;let i=Pl.join("native",s,"prebuilds",`${s}-${t}`,`${s}-platform${e}.node`);if(Ai.has(i))return Ai.get(i);for(let r of El(i))try{let n=hf(r);if(typeof n?.getText=="function"&&typeof n.getImage=="function")return Ai.set(i,n),n}catch{}Ai.set(i,void 0)}function Ts(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return $l(process.platform)}function _l(){if(process.platform!=="linux")return Ts();if(process.env.DISPLAY)return $l("linux","-x11")}var Ol="\x1B]7501;?\x1B\\";function Bl(s){return/^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(s)}var uf=/^[A-Za-z0-9_.+-]{1,32}$/,df=2048;function ff(s,e){if(Buffer.byteLength(s,"utf8")<=e)return s;let t=0,i=0;for(let r of s){let n=Buffer.byteLength(r,"utf8");if(t+n>e)break;t+=n,i+=r.length}return s.slice(0,i)}function Ht(s){let e=[`state=${s.state}`];s.app!==void 0&&uf.test(s.app)&&e.push(`app=${s.app}`),s.state==="blocked"&&s.kind&&e.push(`kind=${s.kind}`);let t=ff(at(s.message??"").trim(),df);return t&&e.push(`msg=${Buffer.from(t,"utf8").toString("base64")}`),`\x1B]7501;${e.join(":")}\x1B\\`}import{EventEmitter as pf}from"events";var Y="\x1B",gf=50,mf=10,Dl="\x1B[200~",Li="\x1B[201~",Wl=/^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;function Fl(s){return s.startsWith(`${Y}]`)||s.startsWith(`${Y}P`)||s.startsWith(`${Y}_`)}function xf(s){if(!s.startsWith(Y))return"not-escape";if(s.length===1)return"incomplete";let e=s.slice(1);return e.startsWith("[")?e.startsWith("[M")?s.length>=6?"complete":"incomplete":bf(s):e.startsWith("]")?yf(s):e.startsWith("P")?wf(s):e.startsWith("_")?kf(s):e.startsWith("O")?e.length>=2?"complete":"incomplete":(e.length===1,"complete")}function bf(s){if(!s.startsWith(`${Y}[`))return"complete";if(s.length<3)return"incomplete";let e=s.slice(2),t=e[e.length-1],i=t.charCodeAt(0);if(i>=64&&i<=126){if(e.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(e))return"complete";if(t==="M"||t==="m"){let n=e.slice(1,-1).split(";");if(n.length===3&&n.every(o=>/^\d+$/.test(o)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function yf(s){return!s.startsWith(`${Y}]`)||s.endsWith(`${Y}\\`)||s.endsWith("\x07")?"complete":"incomplete"}function wf(s){return!s.startsWith(`${Y}P`)||s.endsWith(`${Y}\\`)?"complete":"incomplete"}function kf(s){return!s.startsWith(`${Y}_`)||s.endsWith(`${Y}\\`)?"complete":"incomplete"}function Sf(s){let e=s.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!e)return;let t=parseInt(e[1],10);return t>=32?t:void 0}function Nl(s){let e=[],t=0;for(;t<s.length;){let i=s.slice(t);if(i.startsWith(Y)){let r=Fl(i)&&Wl.test(i),n=1;for(;n<=i.length;){if(r&&n>2){let a=i[n-1];if(a===""||a===""){t+=n;break}if(a===Y&&n<i.length&&i[n]!=="\\"){t+=n-1;break}}let o=i.slice(0,n),l=xf(o);if(l==="complete"){if(o==="\x1B\x1B"){let a=i[n];if(a==="["||a==="]"||a==="O"||a==="P"||a==="_"){e.push(Y),t+=1;break}}e.push(o),t+=n;break}else if(l==="incomplete")n++;else{e.push(o),t+=n;break}}if(n>i.length)return{sequences:e,remainder:i}}else e.push(i[0]),t++}return{sequences:e,remainder:""}}var Kt=class extends pf{buffer="";timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer="";pendingKittyPrintableCodepoint;constructor(e={}){super(),this.timeoutMs=e.timeout??gf,this.escapeTimeoutMs=e.escapeTimeout??mf}process(e){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let t;if(Buffer.isBuffer(e))if(e.length===1&&e[0]>127){let n=e[0]-128;t=`\x1B${String.fromCharCode(n)}`}else t=e.toString();else t=e;if(t.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=t,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let n=this.pasteBuffer.indexOf(Li);if(n!==-1){let o=this.pasteBuffer.slice(0,n),l=this.pasteBuffer.slice(n+Li.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",o),l.length>0&&this.process(l)}return}let i=this.buffer.indexOf(Dl);if(i!==-1){if(i>0){let o=this.buffer.slice(0,i),l=Nl(o);for(let a of l.sequences)this.emitDataSequence(a)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(i+Dl.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let n=this.pasteBuffer.indexOf(Li);if(n!==-1){let o=this.pasteBuffer.slice(0,n),l=this.pasteBuffer.slice(n+Li.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",o),l.length>0&&this.process(l)}return}let r=Nl(this.buffer);this.buffer=r.remainder;for(let n of r.sequences)this.emitDataSequence(n);if(this.buffer.length>0){if(Wl.test(this.buffer))return;let n=this.buffer===Y?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let o=this.flush();for(let l of o)l.length>2&&Fl(l)?(this.emitDataSequence(l.slice(0,2)),this.process(l.slice(2))):this.emitDataSequence(l)},n)}}emitDataSequence(e){let t=e.length===1?e.codePointAt(0):void 0;if(t!==void 0&&t===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=Sf(e),this.emit("data",e)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let e=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,e}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};import*as Vt from"node:fs";import*as Ul from"node:path";function Hl(s){let e=Ts();if(!e?.isModifierPressed)return!1;try{return e.isModifierPressed(s)===!0}catch{return!1}}var Cf=1e3,Kl="\x1B]9;4;3\x07",zr="\x1B]9;4;0\x07",Tf="\x1B[13;2u",vf=7,Mf=150,If=`\x1B[>${vf}u\x1B[?u`,Rf="\x1B[c";function Vl(s){let e=s.match(/^\x1b\[\?(\d+)u$/);if(e)return{type:"kitty-flags",flags:Number.parseInt(e[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(s))return{type:"device-attributes"}}function ql(s){return s==="\x1B["||/^\x1b\[\?[\d;]*$/.test(s)}function jr(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function Af(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH")}catch{}}function zl(s){return s==="\r"||s==="\x1B\r"}function Lf(s,e,t){return e&&zl(s)&&t?Tf:s}var Ef=10,Pf=100;function $f(s=process.env){let e=Number(s.PI_TUI_ESC_TIMEOUT);return Number.isFinite(e)&&e>0?e:s.SSH_CONNECTION||s.SSH_TTY?Pf:Ef}var Ei=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{let e=process.env.PI_TUI_WRITE_LOG||"";if(!e)return"";try{if(Vt.statSync(e).isDirectory()){let t=new Date,i=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}_${String(t.getHours()).padStart(2,"0")}-${String(t.getMinutes()).padStart(2,"0")}-${String(t.getSeconds()).padStart(2,"0")}`;return Ul.join(e,`tui-${i}-${process.pid}.log`)}}catch{}return e})();get kittyProtocolActive(){return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(e,t){this.inputHandler=e,this.resizeHandler=t,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),Af(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new Kt({escapeTimeout:$f()}),this.stdinBuffer.on("data",e=>{if(Bl(e)){this.programStatusQueryPending&&(this.programStatusQueryPending=!1,this.programStatusSupported=!0,this.writeProgramStatus());return}let t=this.readKeyboardProtocolNegotiationSequence(e);if(t==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}t&&this.handleKeyboardProtocolNegotiationSequence(t.parsed)||this.forwardInputSequence(t?.sequence??e)}),this.stdinBuffer.on("paste",e=>{this.inputHandler&&this.inputHandler(`\x1B[200~${e}\x1B[201~`)}),this.stdinDataHandler=e=>{this.stdinBuffer.process(e)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer();let e=process.env.PI_PROGRAM_STATUS;this.programStatusSupported=e==="1",this.programStatusQueryPending=e!=="1"&&e!=="0";let t=this.programStatusQueryPending?Ol:"";process.stdout.write(`${If}${t}${Rf}`),this.writeProgramStatus()}handleKeyboardProtocolNegotiationSequence(e){if(this.clearKeyboardProtocolNegotiationBuffer(),e.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1,this.pendingKeyboardProtocolDeviceAttributes===0&&(this.programStatusQueryPending=!1)}return e.type==="kitty-flags"?(e.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,xt(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(e){if(this.keyboardProtocolNegotiationBuffer){let i=this.keyboardProtocolNegotiationBuffer+e,r=Vl(i);if(r)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:r,sequence:i};if(ql(i))return this.setKeyboardProtocolNegotiationBuffer(i),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let t=Vl(e);if(t)return{parsed:t,sequence:e};if(ql(e))return this.setKeyboardProtocolNegotiationBuffer(e),"pending"}setKeyboardProtocolNegotiationBuffer(e){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=e}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let e=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(e)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput()},Mf))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(e){if(!this.inputHandler)return;let t=zl(e)&&(jr()||process.platform==="win32"),i=Lf(e,t,t&&Hl("shift"));this.inputHandler(i)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{Ts()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(e=1e3,t=50){let i=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),i&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,xt(!1)),this.disableModifyOtherKeys();let r=this.inputHandler;this.inputHandler=void 0;let n=Date.now(),o=()=>{n=Date.now()};process.stdin.on("data",o);let l=Date.now()+e;try{for(;;){let a=Date.now(),c=l-a;if(c<=0||a-n>=t)break;await new Promise(h=>setTimeout(h,Math.min(t,c)))}}finally{process.stdin.removeListener("data",o),this.inputHandler=r}}stop(){this.clearProgressInterval()&&process.stdout.write(zr),this.programStatusSupported&&this.programStatus&&process.stdout.write(Ht({state:"clear"})),this.programStatusSupported=!1,this.programStatusQueryPending=!1,process.stdout.write("\x1B[?2004l");let e=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),e&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,xt(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw)}restoreOnExit(e,t){let i=e;this.progressInterval&&(i+=zr),i+="\x1B[?2004l",(this.keyboardProtocolPushed||this._kittyProtocolActive)&&(i+="\x1B[<u"),this._modifyOtherKeysActive&&(i+="\x1B[>4;0m"),i+=t;try{Vt.writeSync(process.stdout.fd,i)}catch{}}write(e){if(process.stdout.write(e),this.writeLogPath)try{Vt.appendFileSync(this.writeLogPath,e,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(e){e>0?process.stdout.write(`\x1B[${e}B`):e<0&&process.stdout.write(`\x1B[${-e}A`)}hideCursor(){process.stdout.write("\x1B[?25l")}showCursor(){process.stdout.write("\x1B[?25h")}clearLine(){process.stdout.write("\x1B[K")}clearFromCursor(){process.stdout.write("\x1B[J")}clearScreen(){process.stdout.write("\x1B[2J\x1B[H")}setTitle(e){process.stdout.write(`\x1B]0;${at(e)}\x07`)}setProgramStatus(e){this.programStatus=e.state==="clear"?void 0:e,this.programStatusSupported&&process.stdout.write(Ht(e))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(Ht(this.programStatus))}setProgress(e){e?(process.stdout.write(Kl),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(Kl)},Cf))):(this.clearProgressInterval(),process.stdout.write(zr))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var _f=rt(),Of=/^[\x20-\x7e]*$/;function Bf(s){let e=[],t=[],i=0,r=!1,n=()=>{r&&(e.push(" "),i+=1,r=!1)};for(let o=0;o<s.length;o++){let l=_e(s[o]??""),a=0;if(Of.test(l)){let c=0;for(;c<l.length;){if(l.charCodeAt(c)===32){i>0&&(r=!0),a+=1,c+=1;continue}let h=c+1;for(;h<l.length&&l.charCodeAt(h)!==32;)h+=1;n();let u=l.slice(c,h);e.push(u),t.push({textStart:i,textEnd:i+u.length,row:o,startCol:a,endCol:a+u.length,linearColumns:!0}),i+=u.length,a+=u.length,c=h}}else for(let c of _f.segment(l)){let h=c.segment,u=S(h);if(/^\s+$/u.test(h)){i>0&&(r=!0),a+=u;continue}n(),e.push(h),t.push({textStart:i,textEnd:i+h.length,row:o,startCol:a,endCol:a+u,linearColumns:!1}),i+=h.length,a+=u}i>0&&(r=!0)}return{text:e.join(""),spans:t}}function Df(s){return s.replace(/\s+/gu," ").trim()}function Nf(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wf(s,e){if(!e)return[];let t=new RegExp(Nf(e),"giu"),i=[],r=0;for(let n of s.text.matchAll(t)){let o=n.index,l=o+n[0].length;for(;r<s.spans.length&&s.spans[r].textEnd<=o;)r+=1;let a=[];for(let c=r;c<s.spans.length;c++){let h=s.spans[c];if(h.textStart>=l)break;if(h.textEnd<=o)continue;let u=h.linearColumns?h.startCol+Math.max(o,h.textStart)-h.textStart:h.startCol,d=h.linearColumns?h.startCol+Math.min(l,h.textEnd)-h.textStart:h.endCol,f=a[a.length-1];f&&f.row===h.row&&u<=f.endCol?f.endCol=Math.max(f.endCol,d):a.push({row:h.row,startCol:u,endCol:d})}for(;r<s.spans.length&&s.spans[r].textEnd<=l;)r+=1;a.length>0&&i.push({segments:a})}return i}var Pi=class{sourceLines;corpus;normalizedQuery;matches=[];search(e,t){let i=this.sourceLines?.length!==e.length;if(!i&&this.sourceLines){for(let o=0;o<e.length;o++)if(this.sourceLines[o]!==e[o]){i=!0;break}}(i||!this.corpus)&&(this.sourceLines=Array.from(e),this.corpus=Bf(e));let r=Df(t),n=i||r!==this.normalizedQuery;return n&&(this.normalizedQuery=r,this.matches=Wf(this.corpus,r)),{matches:this.matches,changed:n}}};function Gr(s){let e=s.segments[0],t=s.segments[s.segments.length-1];return e&&t?`${e.row}:${e.startCol}:${t.row}:${t.endCol}`:""}var $i=class{input=new $e({prompt:" ",placeholder:"Find in transcript",placeholderStyle:e=>`\x1B[2m${e}\x1B[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(e,t=i=>i){this.onQueryChange=e,this.navigationButtonStyle=t}get focused(){return this._focused}set focused(e){this._focused=e,this.input.focused=e}setResult(e,t){this.resultIndex=e,this.resultCount=t}getNavigationDirectionAt(e,t){if(e===2){if(t>=this.previousButtonStart&&t<this.previousButtonEnd)return-1;if(t>=this.nextButtonStart&&t<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(e){return e===this.hoveredNavigationDirection?!1:(this.hoveredNavigationDirection=e,!0)}handleInput(e){let t=this.input.getValue();this.input.handleInput(e);let i=this.input.getValue();i!==t&&this.onQueryChange(i)}invalidate(){this.input.invalidate()}render(e){let t=Math.max(1,e),i=Math.max(0,t-2),r=B=>B?B.split("+").map(F=>process.platform==="darwin"&&F.toLowerCase()==="alt"?"Option":F.charAt(0).toUpperCase()+F.slice(1)).join("+"):"Unbound",n=U(),o=r(n.getKeys("tui.altScreen.searchPrevious")[0]),l=r(n.getKeys("tui.altScreen.searchNext")[0]),c=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",h=Math.max(0,i-3),u=D(c,h,""),d=u?`\x1B[2m ${u} \x1B[22m`:"",f=Math.max(0,i-S(d)),p=D(this.input.render(Math.max(1,f))[0]??"",f,""),g=" ".repeat(Math.max(0,f-S(p))),x=`${p}${g}${d}`,m=`\u2191 ${o}`,w=`\u2193 ${l}`,b=" \xB7 ",k=1,v=Math.max(0,i-k*2-1),y=S(m)+S(b)+S(w);y>v&&(m="\u2191",w="\u2193",b=" ",y=S(m)+S(b)+S(w));let C=y<=v,I=C?this.navigationButtonStyle(m,this.hoveredNavigationDirection===-1)+b+this.navigationButtonStyle(w,this.hoveredNavigationDirection===1):"",A=C?k*2:0,T=I&&i>y+A?1:0,M=Math.max(0,i-(C?y:0)-A-T),P=1+M+k;return this.previousButtonStart=C?P:-1,this.previousButtonEnd=C?P+S(m):-1,this.nextButtonStart=C?this.previousButtonEnd+S(b):-1,this.nextButtonEnd=C?this.nextButtonStart+S(w):-1,t===1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(i)}\u2510`,`\u2502${x}\u2502`,`\u2514${"\u2500".repeat(M)}${I?" ":""}${I}${I?" ":""}${"\u2500".repeat(T)}\u2518`]}};var Ff=1e3,_i=class{entries=[];nextId=0;requestRender;constructor(e){this.requestRender=e}flash(e,t=Ff){let i=this.nextId++,r=setTimeout(()=>{let n=this.entries.findIndex(o=>o.id===i);n!==-1&&(this.entries.splice(n,1),this.requestRender())},Math.max(0,t));r.unref(),this.entries.push({id:i,message:e,timer:r}),this.requestRender()}dispose(){for(let e of this.entries)clearTimeout(e.timer);this.entries.length=0}invalidate(){}render(e){return this.entries.map(t=>`\x1B[7m${D(` ${t.message} `,e,"")}\x1B[27m`)}};var Hf=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function vs(s,e){let t=Math.max(s.x,e.x),i=Math.max(s.y,e.y),r=Math.min(s.x+s.width,e.x+e.width),n=Math.min(s.y+s.height,e.y+e.height);return{x:t,y:i,width:Math.max(0,r-t),height:Math.max(0,n-i)}}function Bi(s,e,t){let i=Math.max(1,Math.floor(t)),r=s.renderCache.get(e);r||(r=new Map,s.renderCache.set(e,r));let n=r.get(i);return n||(n=s.reusableOutput?.get(e)?.get(i)??e.render(i),r.set(i,n)),n}function jl(s,e,t){return Bi(s,e,t).length}function Kf(s,e,t){return Bi(s,e,t).reduce((i,r)=>Math.max(i,S(r)),0)}function Gl(s,e){return s.parent=e,s}function Yl(s,e){s.rect.y+=e;for(let t of s.children)Yl(t,e)}function Ql(s,e){s.clip=vs(e,s.rect);for(let t of s.children)Ql(t,s.clip)}function Oi(s,e,t,i,r,n,o){let l=Math.max(1,Math.floor(r)),a=mi(e);if(!a){let w=Bi(s,e,l),b=n===void 0?w.length:Math.max(0,Math.floor(n)),k=0;if(w.length>b&&b>0){let v=w.findIndex(y=>y.includes(Z));v>=b&&(k=v-b+1)}return{component:e,rect:{x:t,y:i,width:l,height:b},clip:vs(o,{x:t,y:i,width:l,height:b}),children:[],lines:w,lineOffset:k,layer:0}}if(a.type==="scroll"){let w=a.state.scrollTop,b=a.state.getContentWidth(l),k=Oi(s,a.component,t,i-w,b,void 0,o),v=k.rect.height,y=n===void 0?v:Math.max(0,Math.floor(n));a.state.updateLayout(v,y,s.requestRender),Yl(k,w-a.state.scrollTop);let C=a.state;(a.state.primary||!s.primaryScrollView)&&(s.primaryScrollView=C);let I={x:t,y:i,width:l,height:y},A=vs(o,I),T={component:e,rect:I,clip:A,children:[k],scrollView:C,scrollContentLines:Bi(s,a.component,b),layer:0};return k.parent=T,Ql(k,A),T}let c=Dt(a.entries,s.viewport),h=Math.max(0,c.length-1)*a.gap;if(a.type==="vstack"){let w=c.map(A=>typeof A.basis=="number"?A.basis:jl(s,A.component,l)),b=Ue(c,w,n,a.gap),k=b.reduce((A,T)=>A+T,0)+h,v=n===void 0?k:Math.max(0,Math.floor(n)),y={x:t,y:i,width:l,height:v},C={component:e,rect:y,clip:vs(o,y),children:[],layer:0},I=i;for(let A=0;A<c.length;A++)C.children.push(Gl(Oi(s,c[A].component,t,I,l,b[A],C.clip),C)),I+=b[A]+a.gap;return C}let u=c.map(w=>typeof w.basis=="number"?w.basis:Kf(s,w.component,l)),d=Ue(c,u,l,a.gap),f=c.map((w,b)=>jl(s,w.component,Math.max(1,d[b]))),p=n===void 0?f.reduce((w,b)=>Math.max(w,b),0):Math.max(0,n),g={x:t,y:i,width:l,height:p},x={component:e,rect:g,clip:vs(o,g),children:[],layer:0},m=t;for(let w=0;w<c.length;w++){let b=f[w],k=a.align==="stretch"?p:Math.min(p,b),v=i;a.align==="center"?v+=Math.floor((p-k)/2):a.align==="end"&&(v+=p-k);let y=d[w];y===0?x.children.push({component:c[w].component,rect:{x:m,y:v,width:0,height:k},clip:{x:m,y:v,width:0,height:0},children:[],parent:x,layer:0}):x.children.push(Gl(Oi(s,c[w].component,m,v,y,k,x.clip),x)),m+=y+a.gap}return x}function Vf(s,e,t,i,r){if(W(s))return s;let n=Jt(s,e),o=n?.start??e,l=n?.end??e+1,a=H(s,0,o,!0),c=H(s,o,l-o,!0),h=H(s,l,Math.max(0,t-l),!0),u="",d=0;for(;d<c.length;){let m=K(c,d);if(!m)break;u+=m.code,d+=m.length}let f=" ".repeat(Math.max(0,o-S(a))),p=" ".repeat(Math.max(0,e-o)),g=" ".repeat(Math.max(0,l-e-1)),x=`\x1B[0m\x1B]8;;\x07${r?Dn(u):""}`;return`${a}${f}${x}${p}${i}${g}${h}`}function qt(s,e=!1){if(!s.scrollView||s.rect.width<=0||s.rect.height<=0)return;let t=s.children[0]?.rect.height??s.scrollContentLines?.length??0,i=s.rect.height,r=e&&s.scrollView.scrollbar==="auto"&&t>i;if(!s.scrollView.isScrollbarVisible&&!r)return;let n=Math.min(2,i),o=Math.max(n,Math.min(i,Math.round(i*i/t))),l=Math.max(0,t-i),a=i-o,c=l===0?0:Math.round(s.scrollView.scrollTop/l*a),h=s.rect.x+s.rect.width-1;if(!(h<s.clip.x||h>=s.clip.x+s.clip.width))return{column:h,trackTop:s.rect.y,trackHeight:i,thumbTop:s.rect.y+c,thumbHeight:o,maxScrollTop:l}}function qf(s,e,t){let i=qt(s);if(!(!i||!s.scrollView))for(let r=0;r<i.trackHeight;r++){let n=i.trackTop+r;if(n<s.clip.y||n>=s.clip.y+s.clip.height||n<0||n>=e.length)continue;let l=n>=i.thumbTop&&n<i.thumbTop+i.thumbHeight?s.scrollView.scrollbarThumbStyle(s.scrollView.isScrollbarActive?"\u2588":"\u2503"):s.scrollView.scrollbarTrackStyle("\u2502");e[n]=Vf(e[n]??"",i.column,t,l,s.scrollView.scrollbar!=="always")}}function Xl(s,e,t){if(s.lines){let i=s.lineOffset??0,r=Math.max(s.rect.y,s.clip.y,0),n=Math.min(s.rect.y+s.rect.height,s.clip.y+s.clip.height,e.length);for(let o=r;o<n;o++){let l=s.lines[i+o-s.rect.y];if(l===void 0)continue;let a=l.replace(Hf,""),c=ni(a);if(c){let h=Math.min(e.length,s.clip.y+s.clip.height),u=Math.min(c.rows,h-o);u<c.rows&&(a=Ir(a,0,u))}s.rect.x===0&&s.rect.width>=t&&(W(a)||!e[o])?e[o]=a:e[o]=ye(e[o]??"",a,s.rect.x,s.rect.width,t)}}for(let i of s.children)Xl(i,e,t);if(s.scrollView&&s.scrollContentLines&&s.scrollView.scrollTop>0&&s.rect.height>0){let i=s.scrollView.scrollTop,r=Math.max(0,i-ii());for(let n=i-1;n>=r;n--){let o=s.scrollContentLines[n]??"";if(!W(o))continue;let l=ni(o);if(!l)continue;let a=i-n;if(a<l.rows){let c=Math.min(s.rect.height,l.rows-a),h=Ir(o,a,c);s.rect.x===0&&s.rect.width>=t&&(e[s.rect.y]=h)}break}}qf(s,e,t)}function Qr(s,e,t,i,r){let n=Math.max(1,Math.floor(e)),o=Math.max(1,Math.floor(t)),l=new Map,a={viewport:{width:n,height:o},renderCache:l,reusableOutput:r,requestRender:i,primaryScrollView:void 0},c=Oi(a,s,0,0,n,o,{x:0,y:0,width:n,height:o}),h=Array.from({length:o},()=>"");return Xl(c,h,n),{root:c,width:n,height:o,lines:h,...a.primaryScrollView===void 0?{}:{primaryScrollView:a.primaryScrollView},renderCache:l}}function Yr(s,e,t){return e>=s.x&&e<s.x+s.width&&t>=s.y&&t<s.y+s.height}function Zl(s,e,t){let i=[],r=(n,o)=>{if(Yr(n.clip,e,t)){i.push({box:n,depth:o});for(let l of n.children)r(l,o+1)}};return r(s.root,0),i.sort((n,o)=>o.box.layer-n.box.layer||o.depth-n.depth),i.map(({box:n})=>n)}function ce(s,e){let t=i=>{if(i.scrollView===e)return i;for(let r of i.children){let n=t(r);if(n)return n}};return t(s.root)}function Di(s,e,t){let i=[],r=(n,o)=>{if(Yr(n.clip,e,t)){n.scrollView&&Yr(n.rect,e,t)&&i.push({scrollView:n.scrollView,depth:o});for(let l of n.children)r(l,o+1)}};return r(s.root,0),i.sort((n,o)=>o.depth-n.depth),i.map(n=>n.scrollView)}function Uf(){let s=process.env;return process.platform==="darwin"&&s.SSH_CONNECTION===void 0&&s.SSH_CLIENT===void 0&&s.SSH_TTY===void 0}var Ni=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(e="auto",t=!Uf()){this.lines=e,this.accelerate=t}setLines(e){this.lines=e,this.reset()}next(e,t){if(this.lines!=="auto")return Number.isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let i=t-this.lastTime,r=e===this.lastDirection&&i<=200;if(this.lastTime=t,this.lastDirection=e,!r)return this.averageGap=void 0,this.carry=0,1;if(i<5)return 1;this.averageGap=this.averageGap===void 0?i:(this.averageGap+i)/2;let n=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,o=Math.floor(n);return this.carry=n-o,o}reset(){this.lastTime=Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var zf="\x1B[?1049h",Xr="\x1B[?1049l",Jl="\x1B[?7l",Zr="\x1B[?7h",jf="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",Gf="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",ea="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",Yf="\x1B[I",Qf="\x1B[O",Wi="\x1B[?2026h",Ms="\x1B[?2026l",ta=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,Xf=/^\x1b\]133;A(?:\x07|\x1b\\)/,sa=4,Zf=5,Jf=16,ep=32*1024*1024,tp=64*1024*1024,ia=500,sp=5e3,ip=new Set(["/","-","+","\\","~","_","."]),rp=nt(),Fi=class extends Rt{mode="fullscreen";[_r]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="character";selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScroll;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(e,t,i,r={}){super(e,t,i),this.implicitDocument={render:n=>super.render(n),handleMouse:n=>super.handleMouse(n),invalidate:()=>{for(let n of this.children)n.invalidate()}},this.implicitScrollView=new Ft(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new _i(()=>this.requestRender()),this.wheelScroll=new Ni(r.wheelScrollLines??1),this.mouseEnabled=r.mouse??!0,this.searchMatchStyle=r.searchMatchStyle??(n=>`\x1B[4m${n}\x1B[24m`),this.searchCurrentMatchStyle=r.searchCurrentMatchStyle??(n=>`\x1B[1;7m${n}\x1B[22;27m`),this.searchNavigationButtonStyle=r.searchNavigationButtonStyle??(n=>n),this.scrollToEndIndicator=r.scrollToEndIndicator,this.openUrl=r.openUrl,this.onRightClickPaste=r.onRightClickPaste,this.copyOnSelect=r.copyOnSelect??!0,this.copySelection=r.copySelection,this.addInputListener(n=>this.handleViewportInput(n))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(e){this.wheelScroll.setLines(e)}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(e){this.copyOnSelect=e}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):!1}resetTextSelection(){this.clearTextSelection(),this.lastClick=void 0}getScreenLines(){return[...this.previousScreen]}setLayoutRoot(e){this.layoutRoot!==e&&(this.layoutRoot=e,this.currentLayout=void 0,this.requestRender())}render(e){return this.layoutRoot?.render(e)??super.render(e)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let e=se();this.imageProtocol=e.images,this.uploadedKittyImages.clear(),e.images==="iterm2"&&(this.savedCapabilities=e,gs({...e,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let t=process.env.TERM?.toLowerCase()??"",i=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||t.startsWith("tmux")||t.startsWith("screen")?jf:Gf;this.terminal.write(`${zf}${Jl}${this.mouseEnabled?i:""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(e){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${Wi}${this.deleteKittyImages()}${this.mouseEnabled?ea:""}${Zr}${Ms}`),this.uploadedKittyImages.clear())}afterTerminalStop(e){if(this.altScreenActive){if(this.altScreenActive=!1,e.preserveScreen)this.terminal.write(`${Wi}${Xr}\x1B[?25h${Ms}`);else{let t=Math.max(1,this.terminal.columns),i=this.resolveFakeCursors(this.render(t)).map(n=>n.replace(ta,""));this.lastDocument=this.applyLineResets(i.map(n=>n.replaceAll(Z,""))).map(n=>W(n)||S(n)<=t?n:H(n,0,t,!0));let r=`${Wi}${Xr}${Jl}`;for(let n=0;n<this.lastDocument.length;n++)n>0&&(r+=`\r
112
+ `),r+=`\r\x1B[2K${this.lastDocument[n]??""}`;r+=`\x1B[0m${Zr}\r
113
+ \x1B[?25h${Ms}`,this.terminal.write(r)}this.savedCapabilities&&(gs(this.savedCapabilities),this.savedCapabilities=void 0)}}getExitRestorePrefix(){let e=super.getExitRestorePrefix();return this.altScreenActive?`${Ms}${this.mouseEnabled?ea:""}${Zr}${e}`:e}getExitRestoreSuffix(){return`${super.getExitRestoreSuffix()}${this.altScreenActive?`${Xr}\x1B[?25h`:""}`}deleteKittyImages(){return this.imageProtocol==="kitty"?si():""}prepareKittyScreen(e){let t=new Set,i=e.map(a=>{let c=Yo(a);if(!c)return a;t.add(c.imageId);let h=this.uploadedKittyImages.get(c.imageId),u={transmissionGeneration:c.transmissionGeneration,transmissionBytes:c.transmissionBytes,estimatedDecodedBytes:c.estimatedDecodedBytes};return h&&this.uploadedKittyImages.delete(c.imageId),this.uploadedKittyImages.set(c.imageId,u),h?.transmissionGeneration===c.transmissionGeneration?c.replacementLine:a}),r=0,n=0,o=0;for(let[a,c]of this.uploadedKittyImages)t.has(a)||(r+=1,n+=c.transmissionBytes,o+=c.estimatedDecodedBytes);let l="";for(let[a,c]of this.uploadedKittyImages){if(r<=Jf&&n<=ep&&o<=tp)break;t.has(a)||(l+=It(a),this.uploadedKittyImages.delete(a),r-=1,n-=c.transmissionBytes,o-=c.estimatedDecodedBytes)}return{lines:i,evictedImageDeletion:l}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(e){this.getPrimaryScrollView().scrollBy(e),this.requestViewRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestViewRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestViewRender()}scrollToPrompt(e){if(!this.currentLayout)return;let t=this.getPrimaryScrollView(),i=ce(this.currentLayout,t)?.scrollContentLines;if(i){for(let r=t.scrollTop+e;r>=0&&r<i.length;r+=e)if(Xf.test(i[r]??"")){t.scrollTo(r),this.requestViewRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let e=new $i(i=>this.updateSearchQuery(i),this.searchNavigationButtonStyle),t={component:e,index:new Pi,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=t,t.overlay=this.showOverlay(e,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){let e=this.activeSearch;e&&(this.activeSearch=void 0,e.overlay?.hide(),this.requestRender())}updateSearchQuery(e){let t=this.activeSearch;if(!t||e===t.query)return;let i=t.matches[t.selectedIndex];t.anchorRow=i?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,t.query=e,t.selectionMode="query",t.component.setResult(-1,0),this.requestRender()}navigateSearch(e){let t=this.activeSearch;t?.query&&(t.selectionMode=e<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(e,t){let i=this.activeSearch,r=i?.overlay?.getBounds();if(!(!i||!r)&&!(e<r.col||e>=r.col+r.width||t<r.row||t>=r.row+r.height))return i.component.getNavigationDirectionAt(t-r.row,e-r.col)}handleSearchMouseEvent(e){let t=this.activeSearch;if(!t)return!1;let i=this.getSearchNavigationDirectionAt(e.x,e.y);return t.component.setHoveredNavigationDirection(i)&&this.requestRender(),i===void 0||e.release||(e.button&32)!==0||(e.button&3)!==0?!1:(this.navigateSearch(i),!0)}refreshSearch(e){let t=this.activeSearch;if(!t)return!1;let i=e.primaryScrollView??this.implicitScrollView,r=ce(e,i),n=r?.scrollContentLines;if(!n||!t.query.trim())return t.matches=[],t.selectedIndex=-1,t.selectedKey=void 0,t.selectionMode="retain",t.component.setResult(-1,0),!1;let o=t.selectionMode!=="retain",l=t.index.search(n,t.query),a=l.matches;if(t.matches=a,!l.changed&&t.selectionMode==="retain")return!1;let c=l.changed?t.selectedKey?a.findIndex(m=>Gr(m)===t.selectedKey):-1:t.selectedIndex,h=-1;if(a.length>0)if(t.selectionMode==="query"){let m=0,w=a.length;for(;m<w;){let b=m+Math.floor((w-m)/2);(a[b].segments[0]?.row??0)<t.anchorRow?m=b+1:w=b}h=m<a.length?m:0}else if(t.selectionMode==="next"){let m=c>=0?c:Math.min(t.selectedIndex,a.length-1);h=m<0?0:(m+1)%a.length}else if(t.selectionMode==="previous"){let m=c>=0?c:Math.min(t.selectedIndex,a.length-1);h=m<0?a.length-1:(m-1+a.length)%a.length}else h=c>=0?c:Math.min(Math.max(0,t.selectedIndex),a.length-1);if(t.selectedIndex=h,t.selectedKey=h>=0?Gr(a[h]):void 0,t.selectionMode="retain",t.component.setResult(h,a.length),!o)return!1;let u=a[h],d=u?.segments[0],f=u?.segments[u.segments.length-1];if(!r||!d||!f||i.viewportHeight<=0)return!1;let p=i.scrollTop,g=p+i.viewportHeight-1,x=p;return(d.row<p||f.row>g)&&(x=d.row-Math.floor(i.viewportHeight/3)),i.scrollTo(x,{disableFollow:!0}),i.scrollTop!==p}flash(e,t){this.flashes.flash(e,t)}shouldDeferViewportInput(){return this.getFocusedComponent()?.capturesViewportInput?!0:this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(e){if(e===Qf){let o=this.selectionPressActive,l=o&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,o&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,l&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(e===Yf)return{consume:!0};let t=this.parseWheelEvent(e);if(t){let o=this.wheelScroll.next(t.direction,performance.now()),l=t.direction*((t.button&8)!==0?o*Zf:o),a=this.createMouseEvent("wheel",t.button,t.x,t.y,{wheelDelta:l}),c=this.dispatchMouseToOverlay(a),h=c.result??(c.hit?void 0:this.dispatchMouseToLayout(a));return h?(this.applyMouseDispatchResult(a,h)&&this.requestRender(),{consume:!0}):(this.routeWheel(t,l),{consume:!0})}let i=this.parseSgrMouseEvent(e);if(i)return this.handleMouseEvent(i),{consume:!0};if(this.isMouseSequence(e))return{consume:!0};let r=U(),n=bt(e);if(r.matches(e,"tui.altScreen.search"))return n||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(r.matches(e,"tui.altScreen.searchNext"))return n||this.navigateSearch(1),{consume:!0};if(r.matches(e,"tui.altScreen.searchPrevious"))return n||this.navigateSearch(-1),{consume:!0};if(r.matches(e,"tui.altScreen.searchClose"))return n||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInput()){if(r.matches(e,"tui.altScreen.pageUp"))return n||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-sa)),{consume:!0};if(r.matches(e,"tui.altScreen.pageDown"))return n||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-sa)),{consume:!0};if(r.matches(e,"tui.altScreen.halfPageUp"))return n||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(r.matches(e,"tui.altScreen.halfPageDown"))return n||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(r.matches(e,"tui.altScreen.lineUp"))return n||this.scrollBy(-1),{consume:!0};if(r.matches(e,"tui.altScreen.lineDown"))return n||this.scrollBy(1),{consume:!0};if(r.matches(e,"tui.altScreen.previousPrompt"))return n||this.scrollToPrompt(-1),{consume:!0};if(r.matches(e,"tui.altScreen.nextPrompt"))return n||this.scrollToPrompt(1),{consume:!0};if(r.matches(e,"tui.altScreen.top"))return n||this.scrollToTop(),{consume:!0};if(r.matches(e,"tui.altScreen.bottom"))return n||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(e){switch(e&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(e,t,i,r,n={}){return{type:e,button:e==="wheel"?"none":this.decodeMouseButton(t),x:i,y:r,screenX:i,screenY:r,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(t&4)!==0,alt:(t&8)!==0,ctrl:(t&16)!==0,...n.wheelDelta===void 0?{}:{wheelDelta:n.wheelDelta},...n.clickCount===void 0?{}:{clickCount:n.clickCount}}}dispatchMouseToLayout(e){if(!this.currentLayout)return;let t=new Set,i=Zl(this.currentLayout,e.screenX,e.screenY);for(let r of i){if(t.has(r.component)||mi(r.component)&&r.component.handleMouse===ae.prototype.handleMouse)continue;t.add(r.component);let n=qe(r.component,{...e,x:e.screenX-r.rect.x,y:e.screenY-r.rect.y,width:r.rect.width,height:r.rect.height});if(n)return n}}applyMouseDispatchResult(e,t){let i=this.resolveMouseFocusTarget(t.focusTarget??t.target.component),r=t.focus===!0&&this.getFocusedComponent()!==i;return t.focus&&this.setFocus(i),t.capture&&(this.mouseCapture=t.target),t.render??(r||e.type==="press"||e.type==="click"||e.type==="drag"||e.type==="wheel")}dispatchMouseToTarget(e,t){return qe(t.component,Jo(e,t))}getComponentClickCount(e,t,i){let r=Date.now(),n=this.lastComponentClick,o=n&&r-n.timestamp<=ia&&n.component===e.component&&n.x===t&&n.y===i?n.count%3+1:1;return this.lastComponentClick={timestamp:r,count:o,component:e.component,x:t,y:i},o}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(e){let t=(e.button&32)!==0,i=e.release?"release":t?this.decodeMouseButton(e.button)==="none"?"move":"drag":"press",r=this.createMouseEvent(i,e.button,e.x,e.y);if(this.mouseCapture||this.mousePressTarget){let l=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(e.x!==this.mousePressPoint.x||e.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let a=!1,c=this.dispatchMouseToTarget(r,l);if(c&&(a=this.applyMouseDispatchResult(r,c)),e.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===e.x&&this.mousePressPoint.y===e.y){let h=this.createMouseEvent("click",e.button,e.x,e.y,{clickCount:this.getComponentClickCount(l,e.x,e.y)}),u=this.dispatchMouseToTarget(h,l);u&&(a=this.applyMouseDispatchResult(h,u)||a)}this.clearComponentMouseGesture()}a&&this.requestRender();return}if(this.handleSearchMouseEvent(e))return;let n=this.dispatchMouseToOverlay(r);if(n.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(e))return;let l=this.handleScrollbarMouseEvent(e);if(this.scrollbarDrag||this.updateScrollbarHover(e.x,e.y),l)return}let o=n.result??(n.hit?void 0:this.dispatchMouseToLayout(r));if(o){let l=this.applyMouseDispatchResult(r,o);i==="press"&&(this.clearTextSelection(),this.mousePressTarget=o.target,this.mousePressPoint={x:e.x,y:e.y},this.mousePressMoved=!1),l&&this.requestRender();return}this.handleRightClickPaste(e)||this.handleSelectionMouseEvent(e)}parseWheelEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(e);if(t){let i=Number.parseInt(t[1],10);if((i&64)===0)return;let r=i&3;return r!==0&&r!==1?void 0:{direction:r===0?-1:1,x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,button:i}}if(e.length===6&&e.startsWith("\x1B[M")){let i=e.charCodeAt(3)-32;if((i&64)===0)return;let r=i&3;return r!==0&&r!==1?void 0:{direction:r===0?-1:1,x:e.charCodeAt(4)-33,y:e.charCodeAt(5)-33,button:i}}}routeWheel(e,t){let i=t,r=new Set;for(let o of this.currentLayout?Di(this.currentLayout,e.x,e.y):[])if(r.add(o),i=o.scrollBy(i),i===0||o.overscroll==="contain")break;let n=this.getPrimaryScrollView();i!==0&&!r.has(n)&&n.scrollBy(i),this.updateScrollbarHover(e.x,e.y),this.requestViewRender()}parseSgrMouseEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(e);if(t)return{button:Number.parseInt(t[1],10),x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,release:t[4]==="m"}}handleRightClickPaste(e){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||e.release||e.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(e){let t=this.scrollToEndIndicatorRect;return!t||e.release||(e.button&32)!==0||(e.button&3)!==0||e.y!==t.row||e.x<t.column||e.x>=t.column+t.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(e,t,i=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let r of Di(this.currentLayout,e,t)){let n=ce(this.currentLayout,r),o=n?qt(n,i):void 0;if(o&&e===o.column&&t>=o.trackTop&&t<o.trackTop+o.trackHeight)return{scrollView:r,geometry:o}}}setScrollbarHover(e){e!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=e,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(e,t){this.setScrollbarHover(this.getScrollbarTargetAt(e,t,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(e,t,i,r){let n=t.trackHeight-t.thumbHeight,o=Math.max(0,Math.min(n,i-t.trackTop-r)),l=n===0?0:Math.round(o/n*t.maxScrollTop);e.scrollTo(l)}handleScrollbarMouseEvent(e){if(this.scrollbarDrag){if(e.release)return this.stopScrollbarDrag(),!0;let n=this.currentLayout?ce(this.currentLayout,this.scrollbarDrag.scrollView):void 0,o=n?qt(n):void 0;return o&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,o,e.y,this.scrollbarDrag.grabOffset),!0}if(e.release||(e.button&32)!==0||(e.button&3)!==0)return!1;let t=this.getScrollbarTargetAt(e.x,e.y);if(!t)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(t.scrollView);let i=e.y>=t.geometry.thumbTop&&e.y<t.geometry.thumbTop+t.geometry.thumbHeight,r=i?e.y-t.geometry.thumbTop:Math.floor(t.geometry.thumbHeight/2);return i||this.scrollScrollbarToPointer(t.scrollView,t.geometry,e.y,r),this.scrollbarDrag={scrollView:t.scrollView,grabOffset:r},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(e,t,i){if(!this.currentLayout)return;let r=ce(this.currentLayout,e);if(!r||r.rect.height<=0||r.clip.height<=0)return;let n=Math.max(0,r.rect.y,r.clip.y),o=Math.min(this.terminal.rows-1,r.rect.y+r.rect.height-1,r.clip.y+r.clip.height-1);if(o<n)return;let l=Math.max(n,Math.min(o,i)),a=Math.max(0,(r.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(a,e.scrollTop+l-r.rect.y)),col:Math.max(0,Math.min(r.rect.width-1,t-r.rect.x)),scrollView:e}}getSelectionPoint(e,t){if(t){let i=this.getScrollSelectionPoint(t,e.x,e.y);if(i)return i}return{row:Math.max(0,Math.min(this.terminal.rows-1,e.y)),col:Math.max(0,Math.min(this.terminal.columns-1,e.x))}}getSelectionSourceLine(e){if(e.scrollView&&this.currentLayout){let t=ce(this.currentLayout,e.scrollView)?.scrollContentLines;if(t)return t[e.row]??""}return this.previousScreen[e.row]??""}getWordSelection(e){let t=_e(this.getSelectionSourceLine(e)),i=[],r=0;for(let c of rp.segment(t)){let h=r+S(c.segment),u=ip.has(c.segment);i.push({start:r,end:h,selectable:c.isWordLike===!0||u,joiner:u}),r=h}let n=i.findIndex(c=>e.col>=c.start&&e.col<c.end);if(n<0)return;let o=(c,h)=>c.selectable&&h.selectable&&(c.joiner||h.joiner),l=i[n].start,a=i[n].end;for(let c=n;c>0&&o(i[c-1],i[c]);c--)l=i[c-1].start;for(let c=n;c<i.length-1&&o(i[c],i[c+1]);c++)a=i[c+1].end;return{start:{...e,col:l},end:{...e,col:a,boundary:!0}}}getLineSelection(e){return{start:{...e,col:0},end:{...e,col:S(this.getSelectionSourceLine(e)),boundary:!0}}}updateSelectionFocus(e){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=e;return}let t=this.selectionGranularity==="word"?this.getWordSelection(e):this.getLineSelection(e);if(!t)return;let i=this.selectionInitialRange;t.start.row<i.start.row||t.start.row===i.start.row&&t.start.col<i.start.col?(this.selectionAnchor=i.end,this.selectionFocus=t.start):(this.selectionAnchor=i.start,this.selectionFocus=t.end)}getClickCount(e,t){let i=Date.now(),r=this.lastClick,n=t&&r&&i-r.timestamp<=ia&&r.row===e.row&&r.scrollView===e.scrollView&&r.wordStart===t.start.col&&r.wordEnd===t.end.col?r.count%3+1:1;return this.lastClick=t?{timestamp:i,count:n,row:e.row,scrollView:e.scrollView,wordStart:t.start.col,wordEnd:t.end.col}:void 0,n}updateSelectionAutoScroll(e){let t=this.selectionAnchor?.scrollView;if(!t||!this.currentLayout){this.stopSelectionAutoScroll();return}let i=ce(this.currentLayout,t);if(!i||i.rect.height<=0||i.clip.height<=0){this.stopSelectionAutoScroll();return}let r=Math.max(0,i.rect.y,i.clip.y),n=Math.min(this.terminal.rows-1,i.rect.y+i.rect.height-1,i.clip.y+i.clip.height-1);if(this.selectionDragPointer={x:e.x,y:e.y},this.selectionAutoScrollDirection=e.y<=r?-1:e.y>=n?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref())}autoScrollSelection(){let e=this.selectionAnchor?.scrollView,t=this.selectionDragPointer,i=this.selectionAutoScrollDirection;if(!e||!t||i===0){this.stopSelectionAutoScroll();return}if(e.scrollBy(i)===i){this.stopSelectionAutoScroll();return}let n=this.getScrollSelectionPoint(e,t.x,t.y);n&&this.updateSelectionFocus(n),this.requestViewRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(e){let t=e.button&3;if(t!==0&&!(e.release&&t===3))return;let i=this.selectionAnchor?.scrollView,r=this.getSelectionPoint(e,i);if(e.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(r);let h=!this.selectionDragged&&this.selectionAnchor.scrollView===r.scrollView&&this.selectionAnchor.row===r.row&&this.selectionAnchor.col===r.col,u=h?this.pressedUrl:void 0;if(this.pressedUrl=void 0,u&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(u)}catch{}this.requestRender();return}if(h){let d=this.createMouseEvent("click",e.button,e.x,e.y,{clickCount:this.lastClick?.count??1}),f=this.dispatchMouseToOverlay(d),p=f.result??(f.hit?void 0:this.dispatchMouseToLayout(d));if(p){let g=this.applyMouseDispatchResult(d,p);this.clearTextSelection(),g&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((e.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(r),this.updateSelectionAutoScroll(e),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let n=!this.hasOverlay()&&this.currentLayout?Di(this.currentLayout,e.x,e.y)[0]:void 0,o=this.getSelectionPoint(e,n),l=this.getWordSelection(o),a=this.getClickCount(o,l),c=a===2?l:a===3?this.getLineSelection(o):void 0;this.selectionGranularity=c?a===2?"word":"line":"character",this.selectionInitialRange=c,this.selectionAnchor=c?.start??o,this.selectionFocus=c?.end??o,this.selectionDragged=!1,this.pressedUrl=c?void 0:_s(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,e.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,e.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let e=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return e?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(e,t,i,r=0,n=S(e)){let o=S(e),l=Math.max(0,r),a=Math.min(o,n);return t===i.start.row&&(l=Jt(e,i.start.col)?.start??Math.min(i.start.col,o)),t===i.end.row&&(a=i.end.boundary?Math.min(i.end.col,o):Jt(e,i.end.col)?.end??Math.min(i.end.col+1,o)),{start:Math.max(r,l),end:Math.min(n,a)}}getActiveSelectionText(){let e=this.getSelectionBounds();if(!e)return;let t=this.previousScreen;if(e.start.scrollView){if(!this.currentLayout)return;let n=ce(this.currentLayout,e.start.scrollView);if(!n?.scrollContentLines)return;t=n.scrollContentLines}let i=[];for(let n=e.start.row;n<=e.end.row;n++){let o=t[n]??"",l=this.getSelectionColumns(o,n,e);i.push(_e(H(o,l.start,Math.max(0,l.end-l.start),!0)).trimEnd())}let r=i.join(`
114
+ `);return r.length===0?void 0:r}async copySelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):!1}async copyTextToClipboard(e){if(this.copySelection){let t=await this.copySelection(e),i=t===!0;return this.flash(i?"Copied!":typeof t=="string"?t:"Copy failed",i?void 0:sp),i}return this.terminal.write(`\x1B]52;c;${Buffer.from(e).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(e,t){let i=t?this.searchCurrentMatchStyle:this.searchMatchStyle,r="",n=0,o=0;for(;o<e.length;){let l=K(e,o);if(!l){o+=1;continue}o>n&&(r+=i(e.slice(n,o))),r+=l.code,o+=l.length,n=o}return n<e.length&&(r+=i(e.slice(n))),r}applySearchHighlights(e,t){let i=this.activeSearch;if(!i||i.selectedIndex<0||i.matches.length===0)return e;let r=t.primaryScrollView??this.implicitScrollView,n=ce(t,r);if(!n)return e;let o=new Map,l=qt(n)?.column,a=Math.max(0,n.rect.y,n.clip.y),c=Math.min(e.length,n.rect.y+n.rect.height,n.clip.y+n.clip.height),h=Math.max(0,n.rect.x,n.clip.x),u=Math.min(this.terminal.columns,n.rect.x+n.rect.width,n.clip.x+n.clip.width,l??Number.POSITIVE_INFINITY),d=r.scrollTop+a-n.rect.y,f=r.scrollTop+c-n.rect.y-1,p=0,g=i.matches.length;for(;p<g;){let m=p+Math.floor((g-p)/2),w=i.matches[m];(w.segments[w.segments.length-1]?.row??-1)<d?p=m+1:g=m}for(let m=p;m<i.matches.length;m++){let w=i.matches[m];if((w.segments[0]?.row??0)>f)break;for(let b of w.segments){let k=n.rect.y+b.row-r.scrollTop;if(k<a||k>=c)continue;let v=Math.max(h,n.rect.x+b.startCol),y=Math.min(u,n.rect.x+b.endCol);if(y<=v)continue;let C=o.get(k)??[];C.push({startCol:v,endCol:y,current:m===i.selectedIndex}),o.set(k,C)}}let x=[...e];for(let[m,w]of o){let b=x[m]??"";if(W(b))continue;let k=S(b);for(let v of w.sort((y,C)=>C.startCol-y.startCol)){let y=Math.min(v.startCol,k),C=Math.min(v.endCol,k);if(C<=y)continue;let I=H(b,0,y,!0),A=H(b,y,C-y,!0),T=H(b,C,Math.max(0,k-C),!0);b=`${I}${this.applySearchTextHighlight(A,v.current)}${T}`}x[m]=b}return x}applySelectionHighlight(e){let t="\x1B[7m",i=0;for(;i<e.length;){let r=K(e,i);if(!r){t+=e[i],i+=1;continue}t+=r.code,r.code.endsWith("m")&&(t+="\x1B[7m"),i+=r.length}return`${t}\x1B[27m`}applySelection(e,t=this.currentLayout){let i=this.getSelectionBounds();if(!i)return e;let r=i,n=0,o=e.length-1,l=0,a=this.terminal.columns;if(i.start.scrollView){if(!t)return e;let c=ce(t,i.start.scrollView);if(!c)return e;n=Math.max(0,c.rect.y,c.clip.y),o=Math.min(e.length-1,c.rect.y+c.rect.height-1,c.clip.y+c.clip.height-1),l=Math.max(0,c.rect.x,c.clip.x),a=Math.min(this.terminal.columns,c.rect.x+c.rect.width,c.clip.x+c.clip.width),r={start:{...i.start,row:c.rect.y+i.start.row-i.start.scrollView.scrollTop,col:c.rect.x+i.start.col},end:{...i.end,row:c.rect.y+i.end.row-i.start.scrollView.scrollTop,col:c.rect.x+i.end.col}}}return e.map((c,h)=>{if(h<n||h>o||h<r.start.row||h>r.end.row||W(c))return c;let u=S(c),d=this.getSelectionColumns(c,h,r,l,a);if(d.end<=d.start)return c;let f=H(c,0,d.start,!0),p=H(c,d.start,d.end-d.start,!0),g=H(c,d.end,Math.max(0,u-d.end),!0);return`${f}${this.applySelectionHighlight(p)}${g}`})}isMouseSequence(e){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(e)||e.length===6&&e.startsWith("\x1B[M")}compositeScrollToEndIndicator(e,t,i){this.scrollToEndIndicatorRect=void 0;let r=t.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!r.followEnd||r.isFollowingEnd)return e;let n=ce(t,r),o=n?.clip;if(!o||o.width<=0||o.height<=0)return e;let l=o.y+o.height-1;if(l>=e.length||W(e[l]??""))return e;let a=n?qt(n)?.column:void 0,c=D(this.scrollToEndIndicator(),o.width,""),h=S(c),u=o.x+Math.floor((o.width-h)/2),d=a??o.x+o.width,f=Math.max(0,d-u),p=D(c,f,""),g=S(p);if(g===0)return e;let x=[...e];return x[l]=ye(x[l]??"",p,u,g,i),this.scrollToEndIndicatorRect={row:l,column:u,width:g},x}compositeFlashes(e,t,i){let r=this.flashes.render(t).slice(-i);if(r.length===0)return e;let n=[...e];for(;n.length<i;)n.push("");for(let o=0;o<r.length;o++){let l=r[o],a=S(l);a!==0&&(n[o]=ye(n[o]??"",l,t-a,a,t))}return n}doRender(){if(this.stopped||!this.altScreenActive)return;let e=Math.max(1,this.terminal.columns),t=Math.max(1,this.terminal.rows),i=this.layoutRoot??this.implicitScrollView,r=()=>this.requestViewRender(),n=this.contentChanged?void 0:this.currentLayout?.renderCache;this.contentChanged=!1;let o=Qr(i,e,t,r,n);this.refreshSearch(o)&&(o=Qr(i,e,t,r,o.renderCache));let l=this.resolveFakeCursors(o.lines.map(b=>b.replace(ta,"")));l=this.applySearchHighlights(l,o),l=this.compositeScrollToEndIndicator(l,o,e),l=this.compositeOverlays(l,e,t),l.length>t&&(l=l.slice(l.length-t)),l=this.applySelection(l,o),l=this.compositeFlashes(l,e,t);let a=this.extractCursorPosition(l,t);l=this.applyLineResets(l).map(b=>W(b)||S(b)<=e?b:H(b,0,e,!0));let c=this.previousScreen.length===0||this.previousScreenWidth!==e||this.previousScreenHeight!==t,h=l.map((b,k)=>b!==this.previousScreen[k]),u=l.some((b,k)=>h[k]&&(W(b)||W(this.previousScreen[k]??""))),d=!u&&this.imageProtocol==="kitty"&&h.some(Boolean)&&l.some((b,k)=>{let v=Mr(b);if(v===void 0)return!1;for(let y=k;y<k+v;y++)if(h[y])return!0;return!1}),f=u||d,p=c||f,g=this.uploadedKittyImages.size>0,x=p&&this.imageProtocol==="kitty"?this.prepareKittyScreen(l):{lines:l,evictedImageDeletion:""},m=Wi;if(c?(this.fullRedrawCount+=1,this.imageProtocol==="kitty"&&g?m+=Tr():m+=`${this.deleteKittyImages()}\x1B[2J`):f&&(this.imageProtocol==="iterm2"?m+="\x1B[2J":this.imageProtocol==="kitty"&&(m+=Tr())),m+=x.evictedImageDeletion,p&&this.imageProtocol==="kitty"&&l.some(W)){for(let b=0;b<t;b++)!c&&!f&&l[b]===this.previousScreen[b]||(m+=`\x1B[${b+1};1H\x1B[2K`);for(let b=0;b<t;b++)!c&&!f&&l[b]===this.previousScreen[b]||W(x.lines[b]??"")||(m+=`\x1B[${b+1};1H${x.lines[b]??""}`);for(let b=0;b<t;b++)!c&&!f&&l[b]===this.previousScreen[b]||W(x.lines[b]??"")&&(m+=`\x1B[${b+1};1H${x.lines[b]??""}`)}else for(let b=0;b<t;b++)!c&&!f&&l[b]===this.previousScreen[b]||(m+=`\x1B[${b+1};1H\x1B[2K${x.lines[b]??""}`);a?(m+=`\x1B[${a.row+1};${Math.min(e,a.col)+1}H`,m+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):m+="\x1B[?25l",m+=Ms,this.terminal.write(m),this.previousScreen=l,this.previousScreenWidth=e,this.previousScreenHeight=t,this.currentLayout=o}};import*as Me from"node:fs";import*as oa from"node:os";import*as Xe from"node:path";var np=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,ra="\x1B_G",na=1024*1024,Is=class{buffer="";writtenChars=0;write;constructor(e){this.write=e}append(e){let t=0;for(;t<e.length;){let i=na-this.buffer.length;if(i===0){this.flush();continue}let r=Math.min(e.length,t+i);if(r<e.length&&e.charCodeAt(r-1)>=55296&&e.charCodeAt(r-1)<=56319&&e.charCodeAt(r)>=56320&&e.charCodeAt(r)<=57343&&r--,r===t){this.flush();continue}this.buffer+=e.slice(t,r),t=r,this.buffer.length===na&&this.flush()}}flush(){this.buffer&&(this.write(this.buffer),this.writtenChars+=this.buffer.length,this.buffer="")}get length(){return this.writtenChars+this.buffer.length}};function la(s){let e=s.indexOf(ra);if(e===-1)return;let t=e+ra.length,i=s.indexOf(";",t);if(i===-1)return;let r=[],n=1;for(let o of s.slice(t,i).split(",")){let[l,a]=o.split("=",2);if(a===void 0)continue;let c=Number(a);!Number.isInteger(c)||c<=0||c>4294967295||(l==="i"?r.push(c):l==="r"&&(n=c))}return{ids:r,rows:n}}function Jr(s){return la(s)?.ids??[]}function op(s){return la(s)?.rows??1}function lp(){return!!process.env.TERMUX_VERSION}var Hi=class extends Rt{mode="regular";previousLines=[];previousKittyImageIds=new Set;previousWidth=0;previousHeight=0;cursorRow=0;hardwareCursorRow=0;maxLinesRendered=0;previousViewportTop=0;captureRenderState(){return{previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(e){this.previousLines=e.previousLines.map(t=>W(t)?"":t),this.previousKittyImageIds=new Set,this.previousWidth=e.previousWidth,this.previousHeight=e.previousHeight,this.cursorRow=e.cursorRow,this.hardwareCursorRow=e.hardwareCursorRow,this.maxLinesRendered=e.maxLinesRendered,this.previousViewportTop=e.previousViewportTop}resetRenderState(){this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}beforeTerminalStop(e){if(e.preserveScreen||this.previousLines.length===0)return;this.terminal.write(" ");let i=this.previousLines.length-this.hardwareCursorRow;i>0?this.terminal.write(`\x1B[${i}B`):i<0&&this.terminal.write(`\x1B[${-i}A`),this.terminal.write(`\r
115
+ `)}collectKittyImageIds(e){let t=new Set;for(let i of e)for(let r of Jr(i))t.add(r);return t}deleteKittyImages(e){let t="";for(let i of e)t+=It(i);return t}getKittyImageReservedRows(e,t,i=e.length-1){let r=op(e[t]??"");if(r<=1)return 1;let n=Math.min(r,i-t+1,e.length-t),o=1;for(;o<n;){let l=e[t+o]??"";if(W(l)||S(l)>0)break;o++}return o}expandChangedRangeForKittyImages(e,t,i){let r=e,n=t,o=l=>{for(let a=0;a<l.length;a++){if(Jr(l[a]).length===0)continue;let c=a+this.getKittyImageReservedRows(l,a)-1;(a>=e||a<=t&&c>=e)&&(r=Math.min(r,a),n=Math.max(n,c))}};return o(this.previousLines),o(i),{firstChanged:r,lastChanged:n}}deleteChangedKittyImages(e,t){if(e<0||t<e)return"";let i=new Set,r=Math.min(t,this.previousLines.length-1);for(let n=e;n<=r;n++)for(let o of Jr(this.previousLines[n]??""))i.add(o);return this.deleteKittyImages(i)}doRender(){if(this.stopped)return;let e=this.terminal.columns,t=this.terminal.rows,i=this.previousWidth!==0&&this.previousWidth!==e,r=this.previousHeight!==0&&this.previousHeight!==t,n=this.previousHeight>0?this.previousViewportTop+this.previousHeight:t,o=r?Math.max(0,n-t):this.previousViewportTop,l=o,a=this.hardwareCursorRow,c=T=>{let M=a-o;return T-l-M},h=this.resolveFakeCursors(this.render(e).map(T=>T.replace(np,"")));this.hasOverlayEntries&&(h=this.compositeOverlays(h,e,t));let u=this.extractCursorPosition(h,t);h=this.applyLineResets(h);let d=T=>{this.fullRedrawCount+=1;let M=new Is(B=>this.terminal.write(B));M.append("\x1B[?2026h"),T&&(M.append(this.deleteKittyImages(this.previousKittyImageIds)),M.append("\x1B[2J\x1B[H\x1B[3J"));for(let B=0;B<h.length;B++){B>0&&M.append(`\r
116
+ `);let F=h[B],Q=W(F)?this.getKittyImageReservedRows(h,B):1;if(Q>1&&Q<=t){for(let Qt=1;Qt<Q;Qt++)M.append(`\r
117
+ `);M.append(`\x1B[${Q-1}A`),M.append(F),M.append(`\x1B[${Q-1}B`),B+=Q-1;continue}M.append(F)}M.append("\x1B[?2026l"),M.flush(),this.cursorRow=Math.max(0,h.length-1),this.hardwareCursorRow=this.cursorRow,T?this.maxLinesRendered=h.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,h.length);let P=Math.max(t,h.length);this.previousViewportTop=Math.max(0,P-t),this.positionHardwareCursor(u,h.length),this.previousLines=h,this.previousKittyImageIds=this.collectKittyImageIds(h),this.previousWidth=e,this.previousHeight=t},f=process.env.PI_TUI_DEBUG_REDRAW==="1"?this.logDirectory:void 0,p=T=>{if(f===void 0)return;let M=Xe.join(f,"pi-tui-debug.log"),P=`[${new Date().toISOString()}] fullRender: ${T} (prev=${this.previousLines.length}, new=${h.length}, height=${t})
118
+ `;Me.mkdirSync(Xe.dirname(M),{recursive:!0}),Me.appendFileSync(M,P)};if(this.previousLines.length===0&&!i&&!r){p("first render"),d(!1);return}if(i){p(`terminal width changed (${this.previousWidth} -> ${e})`),d(!0);return}if(r&&!lp()){p(`terminal height changed (${this.previousHeight} -> ${t})`),d(!0);return}if(this.getClearOnShrink()&&h.length<this.maxLinesRendered&&!this.hasOverlayEntries){p(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),d(!0);return}let g=-1,x=-1,m=Math.max(h.length,this.previousLines.length);for(let T=0;T<m;T++){let M=T<this.previousLines.length?this.previousLines[T]:"",P=T<h.length?h[T]:"";M!==P&&(g===-1&&(g=T),x=T)}let w=h.length>this.previousLines.length;if(w&&(g===-1&&(g=this.previousLines.length),x=h.length-1),g!==-1){let T=this.expandChangedRangeForKittyImages(g,x,h);g=T.firstChanged,x=T.lastChanged}let b=w&&g===this.previousLines.length&&g>0;if(g===-1){this.positionHardwareCursor(u,h.length),this.previousViewportTop=o,this.previousHeight=t;return}if(g>=h.length){if(this.previousLines.length>h.length){let T=new Is(Q=>this.terminal.write(Q));T.append("\x1B[?2026h"),T.append(this.deleteChangedKittyImages(g,x));let M=Math.max(0,h.length-1);if(M<o){p(`deleted lines moved viewport up (${M} < ${o})`),d(!0);return}let P=c(M);P>0?T.append(`\x1B[${P}B`):P<0&&T.append(`\x1B[${-P}A`),T.append("\r");let B=this.previousLines.length-h.length;if(B>t){p(`extraLines > height (${B} > ${t})`),d(!0);return}let F=h.length===0?0:1;B>0&&F>0&&T.append(`\x1B[${F}B`);for(let Q=0;Q<B;Q++)T.append("\r\x1B[2K"),Q<B-1&&T.append("\x1B[1B");let Ie=Math.max(0,B-1+F);Ie>0&&T.append(`\x1B[${Ie}A`),T.append("\x1B[?2026l"),T.flush(),this.cursorRow=M,this.hardwareCursorRow=M}this.positionHardwareCursor(u,h.length),this.previousLines=h,this.previousKittyImageIds=this.collectKittyImageIds(h),this.previousWidth=e,this.previousHeight=t,this.previousViewportTop=o;return}if(g<o){p(`firstChanged < viewportTop (${g} < ${o})`),d(!0);return}let k=new Is(T=>this.terminal.write(T));k.append("\x1B[?2026h"),k.append(this.deleteChangedKittyImages(g,x));let v=o+t-1,y=b?g-1:g;if(y>v){let T=Math.max(0,Math.min(t-1,a-o)),M=t-1-T;M>0&&k.append(`\x1B[${M}B`);let P=y-v;k.append(`\r
119
+ `.repeat(P)),o+=P,l+=P,a=y}let C=c(y);C>0?k.append(`\x1B[${C}B`):C<0&&k.append(`\x1B[${-C}A`),k.append(b?`\r
120
+ `:"\r");let I=Math.min(x,h.length-1);for(let T=g;T<=I;T++){T>g&&k.append(`\r
121
+ `);let M=h[T],P=W(M),B=P?this.getKittyImageReservedRows(h,T,I):1;if(B>1){let F=T-l;if(F<0||F+B>t){p(`kitty image pre-clear would scroll (${F} + ${B} > ${t})`),d(!0);return}k.append("\x1B[2K");for(let Ie=1;Ie<B;Ie++)k.append(`\r
122
+ \x1B[2K`);k.append(`\x1B[${B-1}A`),k.append(M),k.append(`\x1B[${B-1}B`),T+=B-1;continue}if(k.append("\x1B[2K"),!P&&S(M)>e){let F=Xe.join(this.logDirectory??oa.tmpdir(),"pi-tui-crash.log"),Ie=[`Crash at ${new Date().toISOString()}`,`Terminal width: ${e}`,`Line ${T} visible width: ${S(M)}`,"","=== All rendered lines ===",...h.map((Qt,ac)=>`[${ac}] (w=${S(Qt)}) ${Qt}`),""].join(`
123
+ `);Me.mkdirSync(Xe.dirname(F),{recursive:!0}),Me.writeFileSync(F,Ie),this.stop();let Q=[`Rendered line ${T} exceeds terminal width (${S(M)} > ${e}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",`Debug log written to: ${F}`].join(`
124
+ `);throw new Error(Q)}k.append(M)}let A=I;if(this.previousLines.length>h.length){if(I<h.length-1){let M=h.length-1-I;k.append(`\x1B[${M}B`),A=h.length-1}let T=this.previousLines.length-h.length;for(let M=h.length;M<this.previousLines.length;M++)k.append(`\r
125
+ \x1B[2K`);k.append(`\x1B[${T}A`)}if(k.append("\x1B[?2026l"),process.env.PI_TUI_DEBUG==="1"){let T="/tmp/tui";Me.mkdirSync(T,{recursive:!0});let M=Xe.join(T,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),P=[`firstChanged: ${g}`,`viewportTop: ${l}`,`cursorRow: ${this.cursorRow}`,`height: ${t}`,`lineDiff: ${C}`,`hardwareCursorRow: ${a}`,`renderEnd: ${I}`,`finalCursorRow: ${A}`,`cursorPos: ${JSON.stringify(u)}`,`newLines.length: ${h.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(h,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",`[${k.length} chars written in bounded chunks]`].join(`
126
+ `);Me.writeFileSync(M,P)}k.flush(),this.cursorRow=Math.max(0,h.length-1),this.hardwareCursorRow=A,this.maxLinesRendered=Math.max(this.maxLinesRendered,h.length),this.previousViewportTop=Math.max(o,A-t+1),this.positionHardwareCursor(u,h.length),this.previousLines=h,this.previousKittyImageIds=this.collectKittyImageIds(h),this.previousWidth=e,this.previousHeight=t}positionHardwareCursor(e,t){if(!e||t<=0){this.terminal.hideCursor();return}let i=Math.max(0,Math.min(e.row,t-1)),r=Math.max(0,e.col),n=i-this.hardwareCursorRow,o="";n>0?o+=`\x1B[${n}B`:n<0&&(o+=`\x1B[${-n}A`),o+=`\x1B[${r+1}G`,o&&this.terminal.write(o),this.hardwareCursorRow=i,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}};import*as ie from"node:fs";import*as et from"node:path";import{watch as cp}from"node:fs";var Dx=5e3;function en(s){if(s)try{s.close()}catch{}}function aa(s,e,t){try{let i=cp(s,e);return i.on("error",t),i}catch{return t(),null}}var Ut=V(hc(),1),fa=V(uc(),1),pa=V(dc(),1),ga=V(fc(),1),ma=V(pc(),1),xa=V(gc(),1),ba=V(mc(),1),ya=V(xc(),1),wa=V(bc(),1),ka=V(yc(),1),Sa=V(wc(),1),Ca=V(kc(),1),Ta=V(Sc(),1),va=V(Cc(),1),Ma=V(Tc(),1),Ia=V(vc(),1),Ra=V(Mc(),1),Aa=V(Ic(),1),La=V(Rc(),1),Ea=V(Ac(),1),Pa=V(Lc(),1),$a=V(Ec(),1);function ca(s){if(!(!Number.isInteger(s)||s<0||s>1114111))return String.fromCodePoint(s)}function hp(s){switch(s){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'"}if(s.startsWith("#x")||s.startsWith("#X"))return ca(Number.parseInt(s.slice(2),16));if(s.startsWith("#"))return ca(Number.parseInt(s.slice(1),10))}function ha(s,e){let t=s.indexOf(";",e+1);if(t===-1||t-e>16)return;let i=s.slice(e+1,t),r=hp(i);if(r!==void 0)return{text:r,length:t-e+1}}var up={python:Ra.default,java:wa.default,go:ba.default,javascript:ka.default,json:Sa.default,cpp:ga.default,typescript:$a.default,php:Ia.default,ruby:Aa.default,c:pa.default,csharp:ma.default,nix:va.default,bash:fa.default,rust:La.default,scala:Ea.default,kotlin:Ca.default,swift:Pa.default,dart:xa.default,groovy:ya.default,perl:Ma.default,lua:Ta.default};for(let[s,e]of Object.entries(up))Ut.default.registerLanguage(s,e);var tn;function Hx(){return tn||(tn=new Promise(s=>{setImmediate(()=>{import("./lib-RSOU34HQ.js").then(()=>s(),()=>{s()})})})),tn}var ua="</span>",da="hljs-";function dp(s){let e=/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(s),t=e?.[1]??e?.[2];if(t){for(let i of t.split(/\s+/))if(i.startsWith(da))return i.slice(da.length)}}function fp(s,e){let t=e[s];if(t)return t;let i=s.indexOf(".");if(i!==-1){let n=e[s.slice(0,i)];if(n)return n}let r=s.indexOf("-");if(r!==-1){let n=e[s.slice(0,r)];if(n)return n}}function pp(s,e){for(let t=s.length-1;t>=0;t--){let i=s[t];if(!i)continue;let r=fp(i,e);if(r)return r}return e.default}function gp(s,e){if(!s.startsWith("<span",e))return!1;let t=s[e+5];return t===">"||t===" "||t===" "||t===`
127
+ `||t==="\r"}function mp(s,e={}){let t="",i="",r=[],n=()=>{if(!i)return;let l=pp(r,e);t+=l?i.split(`
128
+ `).map(a=>a&&l(a)).join(`
129
+ `):i,i=""},o=0;for(;o<s.length;){if(gp(s,o)){let l=s.indexOf(">",o+5);if(l!==-1){n();let a=s.slice(o,l+1),c=dp(a);r.push(c),o=l+1;continue}}if(s.startsWith(ua,o)){n(),r.length>0&&r.pop(),o+=ua.length;continue}if(s[o]==="&"){let l=ha(s,o);if(l){i+=l.text,o+=l.length;continue}}i+=s[o],o++}return n(),t}function _a(s,e={}){let t=e.language?Ut.default.highlight(s,{language:e.language,ignoreIllegals:e.ignoreIllegals}).value:Ut.default.highlightAuto(s,e.languageSubset).value;return mp(t,e.theme)}function Oa(s){return Ut.default.getLanguage(s)!==void 0}function Ba(){return Ut.default.listLanguages().length}var G="system",sn={neutral:{hue:231.49,saturation:{min:.02,max:.08},slot:8},blue:{hue:231.49,saturation:{min:.1,max:.68},slot:4},green:{hue:158.68,saturation:{min:.1,max:.76},slot:2},red:{hue:20,saturation:{min:.1,max:.92},slot:1},yellow:{hue:82.36,saturation:{min:.5,max:1},slot:3},orange:{hue:52,saturation:{min:.12,max:.85},slot:3},violet:{hue:295,saturation:{min:.2,max:.6},slot:5},calamine:{hue:202.43,saturation:{min:.1,max:.74},slot:6},thinkingSlate:{hue:231.49,saturation:{min:.08,max:.2},slot:4},thinkingBlue:{hue:231.49,saturation:{min:.2,max:.45},slot:4},thinkingPeriwinkle:{hue:263.25,saturation:{min:.3,max:.6},slot:6},thinkingViolet:{hue:295,saturation:{min:.4,max:.75},slot:5},thinkingMagenta:{hue:337.5,saturation:{min:.5,max:.85},slot:13},thinkingRed:{hue:20,saturation:{min:.95,max:1},slot:1}},rn={selectedBg:"blue",searchMatchBg:"orange",userMessageBg:"blue",customMessageBg:"violet",toolPendingBg:"neutral",toolSuccessBg:"green",toolErrorBg:"red",text:"neutral",userMessageText:"neutral",customMessageText:"neutral",toolTitle:"neutral",syntaxOperator:"neutral",syntaxPunctuation:"neutral",muted:"neutral",dim:"neutral",thinkingText:"neutral",toolOutput:"neutral",mdLinkUrl:"neutral",mdQuote:"neutral",mdQuoteBorder:"neutral",mdHr:"neutral",mdCodeBlockBorder:"neutral",toolDiffContext:"neutral",syntaxComment:"neutral",scrollbarTrack:"neutral",scrollbarThumb:"neutral",searchMatchText:"neutral",borderMuted:"neutral",accent:"violet",borderAccent:"violet",customMessageLabel:"violet",mdCode:"violet",mdListBullet:"violet",syntaxType:"violet",border:"blue",mdLink:"blue",syntaxKeyword:"blue",syntaxVariable:"calamine",success:"green",mdCodeBlock:"green",toolDiffAdded:"green",bashMode:"green",syntaxNumber:"green",error:"red",toolDiffRemoved:"red",warning:"yellow",mdHeading:"yellow",syntaxFunction:"yellow",syntaxString:"orange",thinkingOff:"neutral",thinkingMinimal:"thinkingSlate",thinkingLow:"thinkingBlue",thinkingMedium:"thinkingPeriwinkle",thinkingHigh:"thinkingViolet",thinkingXhigh:"thinkingMagenta",thinkingMax:"thinkingRed"},Va={syntaxString:2,syntaxNumber:5,searchMatchBg:3},xp={panel:{dark:{coefficients:[.29131,-.39746,2.33185,-.85524,-1.2076,.86276],reachable:[0,.979]},light:{coefficients:[-3.74073,27.94549,-78.44258,112.6798,-79.60015,22.11277],reachable:[.348,1]}},track:{dark:{coefficients:[.39028,-.23015,.83573,2.43829,-4.38292,2.01582],reachable:[0,.946]},light:{coefficients:[-5.24921,38.37322,-107.28833,152.10005,-106.17127,29.18061],reachable:[.368,1]}},thinking0:{dark:{coefficients:[.52988,-.05809,-.30924,4.63567,-6.52933,2.89108],reachable:[0,.873]},light:{coefficients:[-28.27749,182.85284,-469.62416,603.15916,-384.59976,97.35147],reachable:[.51,1]}},thinking1:{dark:{coefficients:[.55278,-.03667,-.45659,4.95347,-6.90265,3.0706],reachable:[0,.858]},light:{coefficients:[-37.10484,235.86282,-596.62344,754.3633,-474.00763,118.3551],reachable:[.535,1]}},thinking2:{dark:{coefficients:[.57486,-.01765,-.58987,5.25227,-7.27175,3.25532],reachable:[0,.842]},light:{coefficients:[-59.89653,377.05024,-945.07843,1182.03145,-734.96375,181.68658],reachable:[.556,1]}},thinking3:{dark:{coefficients:[.59621,-62e-5,-.71148,5.53588,-7.6392,3.44606],reachable:[0,.827]},light:{coefficients:[-72.07122,445.84082,-1099.57352,1353.88793,-829.53392,202.26164],reachable:[.58,1]}},thinking4:{dark:{coefficients:[.61691,.01462,-.82288,5.80651,-8.00641,3.64333],reachable:[0,.811]},light:{coefficients:[-110.14338,674.21488,-1645.75941,2004.32367,-1215.15899,293.3183],reachable:[.6,1]}},thinking5:{dark:{coefficients:[.63702,.02826,-.92498,6.06465,-8.37246,3.84651],reachable:[0,.795]},light:{coefficients:[-175.47701,1063.54495,-2570.70594,3098.80776,-1860.15527,444.76392],reachable:[.62,1]}},thinking6:{dark:{coefficients:[.65658,.04044,-1.01835,6.30989,-8.73529,4.05439],reachable:[0,.779]},light:{coefficients:[-183.81712,1094.70055,-2602.68539,3088.71276,-1826.91131,430.75931],reachable:[.643,1]}},subtle:{dark:{coefficients:[.56762,-.02475,-.5383,5.12628,-7.10931,3.17324],reachable:[0,.848]},light:{coefficients:[-232.85459,1376.54473,-3249.11801,3827.91186,-2248.29472,526.55751],reachable:[.657,1]}},thumb:{dark:{coefficients:[.60323,.00278,-.73328,5.57157,-7.68067,3.46933],reachable:[0,.823]},light:{coefficients:[-82.89897,511.01355,-1255.98095,1540.76821,-940.68087,228.58523],reachable:[.586,1]}},readable:{dark:{coefficients:[.66937,.04704,-1.06871,6.43941,-8.9332,4.17229],reachable:[0,.77]},light:{coefficients:[-1554.52576,8733.56817,-19604.93507,21977.72696,-12300.99599,2749.81288],reachable:[.751,1]}},emphasis:{dark:{coefficients:[.7303,.07695,-1.31626,7.1681,-10.14436,4.92846],reachable:[0,.712]},light:{coefficients:[-4948.31942,26870.91986,-58334.48399,63280.17197,-34298.01053,7430.30146],reachable:[.811,1]}},textOnPanel:{dark:{coefficients:[.86713,.05232,-.89428,4.79014,-5.5432,1.75023],reachable:[0,.542]},light:{coefficients:[-8570.89457,43954.60805,-90084.00702,92220.6791,-47152.15802,9632.27113],reachable:[.867,1]}},text:{dark:{coefficients:[.89242,.02311,-.44862,2.34417,-.06084,-2.63844],reachable:[0,.5]},light:{coefficients:[-2004.67048,6664.47299,-6060.70202,-1792.61209,5133.82359,-1939.85583],reachable:[.894,1]}}},ge=["toolPendingBg","toolSuccessBg","toolErrorBg"],Ki=["userMessageBg","customMessageBg"],nn=["userMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg","selectedBg","searchMatchBg","customMessageBg"],bp=["thinkingOff","thinkingMinimal","thinkingLow","thinkingMedium","thinkingHigh","thinkingXhigh","thinkingMax"],yp=["thinking0","thinking1","thinking2","thinking3","thinking4","thinking5","thinking6"],Ze=(s,e,t)=>s.map(i=>({token:i,on:e,level:t})),Vi=[...Ze(nn,["background"],"panel"),{token:"text",on:["background"],level:"text"},{token:"text",on:["selectedBg"],level:"textOnPanel"},{token:"userMessageText",on:["userMessageBg"],level:"textOnPanel"},{token:"toolTitle",on:ge,level:"textOnPanel"},...Ze(["accent","success","error","warning"],["background","selectedBg",...ge],"readable"),{token:"muted",on:["background","selectedBg","customMessageBg",...ge],level:"readable"},{token:"dim",on:["background","selectedBg","customMessageBg",...ge],level:"subtle"},{token:"thinkingText",on:["background"],level:"readable"},{token:"customMessageText",on:["customMessageBg",...ge],level:"readable"},{token:"customMessageLabel",on:["background","customMessageBg","selectedBg",...ge],level:"readable"},{token:"toolOutput",on:["background",...ge],level:"readable"},...Ze(["mdHeading","mdLink","mdLinkUrl","mdCode","mdQuote","mdCodeBlockBorder","mdListBullet"],["background",...Ki],"readable"),{token:"mdCodeBlock",on:["background",...Ki,...ge],level:"readable"},...Ze(["toolDiffAdded","toolDiffRemoved","toolDiffContext"],["background",...ge],"readable"),...Ze(["syntaxComment","syntaxKeyword","syntaxFunction","syntaxVariable","syntaxString","syntaxNumber","syntaxType","syntaxOperator","syntaxPunctuation"],["background",...Ki,...ge],"readable"),{token:"searchMatchText",on:["searchMatchBg"],level:"readable"},...Ze(["bashMode","border","borderAccent"],["background"],"readable"),{token:"borderMuted",on:["background"],level:"subtle"},...Ze(["mdQuoteBorder","mdHr"],["background",...Ki,...ge],"readable"),{token:"scrollbarTrack",on:["background"],level:"track"},{token:"scrollbarThumb",on:["scrollbarTrack"],level:"thumb"},...bp.map((s,e)=>({token:s,on:["background"],level:yp[e]}))],wp={dark:"readable",light:"subtle"},kp="emphasis",qa=["text","userMessageText","toolTitle"],on=4.5,Sp=(()=>{let s=[],e=t=>{if(!s.includes(t)){for(let i of Vi)if(i.token===t)for(let r of i.on)r!=="background"&&e(r);s.push(t)}};for(let t of Vi)e(t.token);return s})();function zt(s){return xe(he(s.r,s.g,s.b)).l}function Da({r:s,g:e,b:t}){let i=r=>{let n=r/255;return n<=.04045?n/12.92:((n+.055)/1.055)**2.4};return .2126*i(s)+.7152*i(e)+.0722*i(t)}function qi(s,e){let t=Da(s),i=Da(e);return(Math.max(t,i)+.05)/(Math.min(t,i)+.05)}function ln(s,e){let t={r:255,g:255,b:255},i={r:0,g:0,b:0},r=qi(t,s),n=qi(i,s);if(e){let o=zt(e),l=zt(s);if(Math.abs(o-l)>.05){let a=o>l?"dark":"light";if((a==="dark"?r:n)>=on)return a}}return r>=n?"dark":"light"}var Cp=(s,e,t)=>Math.min(t,Math.max(e,s));function Na({r:s,g:e,b:t}){return`#${[s,e,t].map(i=>Math.round(i).toString(16).padStart(2,"0")).join("")}`}function Ua(s){let e=t=>Math.exp(-((t-.5)**2)/.125);return(e(s)-e(0))/(1-e(0))}function Wa({saturation:{min:s,max:e}},t){let i=e>0?s/e:1;return i+(1-i)*Ua(t)}function Fa(s,e,t){let i=xp[s][e];if(!(t<i.reachable[0]||t>i.reachable[1]))return i.coefficients.reduce((r,n,o)=>r+n*t**o,0)}function za(s){let e=Cp(s.saturation??1,0,1),{background:t,foreground:i}=s;if(!t)return vp(e,s.appearanceHint);let r=s.palette?.length===16?s.palette.map(Ha):void 0,n=ln(t,i),o=n==="dark",l=o?1:0,a=zt(t),c=(k,v)=>{let y=ht(v),C=sn[rn[k]];if(!r){let{min:I,max:A}=C.saturation;return De(C.hue,(I+(A-I)*Ua(y))*e,y)}return Ka(r[Va[k]??C.slot],C,y,e)},h=(k,v,y)=>{let C=Fa(k,n,v);if(C===void 0&&y===0)return;let I=(C??l)-v,A=(Fa(wp[n],n,v)??l)-v,T=Math.abs(I)>Math.abs(A)?I-(I-A)*Math.min(y,1):I;return v+T*(1-Math.max(0,y-1))},u=o?{r:255,g:255,b:255}:{r:0,g:0,b:0},d=k=>qi(u,k)>=on,f=(k,v)=>{let y=c(k,v);if(d(y))return y;let[C,I]=[a,v];for(let A=0;A<20;A++){let T=(C+I)/2;d(c(k,T))?C=T:I=T}return c(k,C)},p=k=>{let v=new Map([["background",t]]);for(let y of Sp){let C=[];for(let A of Vi)if(A.token===y)for(let T of A.on){let M=h(A.level,zt(v.get(T)??t),k);if(M===void 0||M<0||M>1)return;C.push(M)}let I=o?Math.max(...C):Math.min(...C);v.set(y,nn.includes(y)?f(y,I):c(y,I))}return v},g=0,x=p(0);if(!x){let[k,v]=[0,2];x=p(v);for(let y=0;y<20;y++){let C=(k+v)/2,I=p(C);I?[v,x]=[C,I]:k=C}g=v}let m=x??new Map,w=k=>Vi.filter(v=>v.token===k).flatMap(v=>v.on.map(y=>m.get(y)??t)),b={};for(let k of Object.keys(rn)){let v=m.get(k);b[k]=v?Na(v):""}for(let k of qa){let v=w(k),y=m.get(k);if(i){let C=v.map(I=>h(kp,zt(I),g));if(C.every(I=>I!==void 0&&I>=0&&I<=1)){let I=o?Math.max(...C):Math.min(...C),A=zt(i);if(o?A>=I:A<=I){b[k]="";continue}y=Ka(Ha(i),sn.neutral,ht(I),e)}}y&&(b[k]=Na(Tp(y,v,o)))}return{colors:b,dim:[],appearance:n}}function ja({r:s,g:e,b:t}){return Ks(he(s,e,t))}function Ha(s){return{...ja(s),chroma:xe(he(s.r,s.g,s.b)).c}}function Ka(s,e,t,i){let r=Wa(e,s.l),n=r>0?Math.min(1,Wa(e,t)/r):1,o=De(s.h,s.s*n*i,t),l=s.chroma*n*i,{l:a,c}=xe(o);return c<=l?o:me(dt(a,l,s.h))}function Tp(s,e,t){let i=u=>e.every(d=>qi(u,d)>=on);if(i(s))return s;let{h:r,s:n,l:o}=ja(s),l=u=>De(r,n,u),a=t?1:0;if(!i(l(a)))return l(a);let[c,h]=[o,a];for(let u=0;u<20;u++){let d=(c+h)/2;i(l(d))?h=d:c=d}return l(h)}function vp(s,e){let t={},i=[];for(let[r,n]of Object.entries(rn)){if(nn.includes(r)){t[r]="";continue}let o=n==="neutral";t[r]=!o&&s>0?Va[r]??sn[n].slot:"",o&&!qa.includes(r)&&i.push(r)}return{colors:t,dim:i,appearance:e}}function Mp(s){for(let[e,t]of Object.entries(s)){if(t.fallback===void 0)continue;let i=s[t.fallback];if(i===void 0)throw new Error(`Theme token ${e} has unknown fallback ${t.fallback}`);if(i.slot!==t.slot)throw new Error(`Theme token ${e} has fallback ${t.fallback} in a different color slot`)}return s}var an=Mp({accent:{slot:"foreground",description:"Primary accent color (logo, selected items, cursor)"},border:{slot:"foreground",description:"Normal borders"},borderAccent:{slot:"foreground",description:"Highlighted borders"},borderMuted:{slot:"foreground",description:"Subtle borders"},success:{slot:"foreground",description:"Success states"},error:{slot:"foreground",description:"Error states"},warning:{slot:"foreground",description:"Warning states"},muted:{slot:"foreground",description:"Secondary/dimmed text"},dim:{slot:"foreground",description:"Very dimmed text (more subtle than muted)"},text:{slot:"foreground",description:"Default text color (usually empty string)"},thinkingText:{slot:"foreground",description:"Thinking block text color"},scrollbarTrack:{slot:"foreground",description:"Fullscreen scrollbar track foreground (falls back to muted when omitted)",fallback:"muted"},scrollbarThumb:{slot:"foreground",description:"Fullscreen scrollbar thumb foreground (falls back to text when omitted)",fallback:"text"},selectedBg:{slot:"background",description:"Selected item background"},searchMatchBg:{slot:"background",description:"Transcript search match background and current-match text (falls back to selectedBg when omitted)",fallback:"selectedBg"},searchMatchText:{slot:"foreground",description:"Transcript search match text and current-match background (falls back to text when omitted)",fallback:"text"},userMessageBg:{slot:"background",description:"User message background"},userMessageText:{slot:"foreground",description:"User message text color"},customMessageBg:{slot:"background",description:"Custom message background (hook-injected messages)"},customMessageText:{slot:"foreground",description:"Custom message text color"},customMessageLabel:{slot:"foreground",description:"Custom message type label color"},toolPendingBg:{slot:"background",description:"Tool execution box (pending state)"},toolSuccessBg:{slot:"background",description:"Tool execution box (success state)"},toolErrorBg:{slot:"background",description:"Tool execution box (error state)"},toolTitle:{slot:"foreground",description:"Tool execution box title color"},toolOutput:{slot:"foreground",description:"Tool execution box output text color"},mdHeading:{slot:"foreground",description:"Markdown heading text"},mdLink:{slot:"foreground",description:"Markdown link text"},mdLinkUrl:{slot:"foreground",description:"Markdown link URL"},mdCode:{slot:"foreground",description:"Markdown inline code"},mdCodeBlock:{slot:"foreground",description:"Markdown code block content"},mdCodeBlockBorder:{slot:"foreground",description:"Markdown code block fences"},mdQuote:{slot:"foreground",description:"Markdown blockquote text"},mdQuoteBorder:{slot:"foreground",description:"Markdown blockquote border"},mdHr:{slot:"foreground",description:"Markdown horizontal rule"},mdListBullet:{slot:"foreground",description:"Markdown list bullets/numbers"},toolDiffAdded:{slot:"foreground",description:"Added lines in tool diffs"},toolDiffRemoved:{slot:"foreground",description:"Removed lines in tool diffs"},toolDiffContext:{slot:"foreground",description:"Context lines in tool diffs"},syntaxComment:{slot:"foreground",description:"Syntax highlighting: comments"},syntaxKeyword:{slot:"foreground",description:"Syntax highlighting: keywords"},syntaxFunction:{slot:"foreground",description:"Syntax highlighting: function names"},syntaxVariable:{slot:"foreground",description:"Syntax highlighting: variable names"},syntaxString:{slot:"foreground",description:"Syntax highlighting: string literals"},syntaxNumber:{slot:"foreground",description:"Syntax highlighting: number literals"},syntaxType:{slot:"foreground",description:"Syntax highlighting: type names"},syntaxOperator:{slot:"foreground",description:"Syntax highlighting: operators"},syntaxPunctuation:{slot:"foreground",description:"Syntax highlighting: punctuation"},thinkingOff:{slot:"foreground",description:"Thinking level border: off"},thinkingMinimal:{slot:"foreground",description:"Thinking level border: minimal"},thinkingLow:{slot:"foreground",description:"Thinking level border: low"},thinkingMedium:{slot:"foreground",description:"Thinking level border: medium"},thinkingHigh:{slot:"foreground",description:"Thinking level border: high"},thinkingXhigh:{slot:"foreground",description:"Thinking level border: xhigh"},thinkingMax:{slot:"foreground",description:"Thinking level border: max (falls back to thinkingXhigh when omitted)",fallback:"thinkingXhigh"},bashMode:{slot:"foreground",description:"Editor border color in bash mode"}});var un;function e1(s){un=s}function fn(s,e,t=new Set){if(typeof s=="number"||s===""||s.startsWith("#")||/^ok(lch|hsl)\(/i.test(s))return s;if(t.has(s))throw new Error(`Circular variable reference detected: ${s}`);if(!(s in e))throw new Error(`Variable reference not found: ${s}`);return t.add(s),fn(e[s],e,t)}function Ip(s,e={}){let t={};for(let[i,r]of Object.entries(s))t[i]=fn(r,e);return t}function pn(s){let e={...s};for(let[t,i]of Object.entries(an)){if(!("fallback"in i))continue;let r=t;if(e[r]!==void 0)continue;let n=i.fallback,o=e[n];if(o===void 0)throw new Error(`Theme token ${t} has unresolved fallback ${i.fallback}`);e[r]=o}return e}var zi={},gn=!1,Xa;function t1(s){zi={...s},gn=!1}function s1(s){Xa=s}function i1(){gn=!0}var Rp={dark:{foreground:Se("#e5e5e7"),background:Se("#000000")},light:{foreground:Se("#000000"),background:Se("#ffffff")}};function Ga(s){let e=s.filter(t=>t.kind!=="indexed"||t.index>=16);if(e.length!==0)return e.reduce((t,i)=>t+xe(i).l,0)/e.length}function Ap(s,e){let t=Ga(s),i=Ga(e);if(t!==void 0&&i!==void 0)return i<t?"dark":"light";if(i!==void 0)return i<.5?"dark":"light";if(t!==void 0)return t>.5?"dark":"light"}var Ui=class{name;sourcePath;sourceInfo;mode;fgAnsi=new Map;bgAnsi=new Map;concreteColors={};defaultForegroundTokens=[];defaultBackgroundTokens=[];dimTokens;ownAppearance;resolvedColors;constructor(e,t,i,r={}){this.name=r.name,this.sourcePath=r.sourcePath,this.sourceInfo=r.sourceInfo,this.mode=i,this.dimTokens=new Set(r.dim);let{fgColors:n,bgColors:o}=mn(pn({...e,...t})),l=[],a=[],c=(h,u,d)=>{if(u==="")return(d?this.defaultBackgroundTokens:this.defaultForegroundTokens).push(h),d?"\x1B[49m":"\x1B[39m";let f=Se(u);return this.concreteColors[h]=f,(d?a:l).push(f),d?gt(f,i):pt(f,i)};for(let[h,u]of Object.entries(n))this.fgAnsi.set(h,c(h,u,!1));for(let[h,u]of Object.entries(o))this.bgAnsi.set(h,c(h,u,!0));this.ownAppearance=r.appearance??Ap(l,a)}get appearance(){return this.ownAppearance??sc()}get colors(){let e=zi;if(this.resolvedColors?.terminal!==e){let t=Rp[this.appearance],i=(l,a)=>l?he(l.r,l.g,l.b):a,r=i(e.foreground,t.foreground),n=i(e.background,t.background),o={...this.concreteColors};for(let l of this.defaultForegroundTokens)o[l]=r;for(let l of this.defaultBackgroundTokens)o[l]=n;for(let l of this.dimTokens){let a=o[l];a&&(o[l]=Vs(a,n,.4))}this.resolvedColors={terminal:e,colors:Object.freeze(o)}}return this.resolvedColors.colors}style(e,t){let{fg:i,bg:r}=t;return typeof i=="string"&&this.dimTokens.has(i)&&(t={...t,dim:!0}),ts(e,i===void 0?void 0:typeof i=="string"?this.tokenAnsi(this.fgAnsi,i):pt(i,this.mode),r===void 0?void 0:typeof r=="string"?this.tokenAnsi(this.bgAnsi,r):gt(r,this.mode),t)}fg(e,t){let i=this.tokenAnsi(this.fgAnsi,e);return this.dimTokens.has(e)?`${i}\x1B[2m${t}\x1B[22;39m`:`${i}${t}\x1B[39m`}bg(e,t){return`${this.tokenAnsi(this.bgAnsi,e)}${t}\x1B[49m`}tokenAnsi(e,t){let i=e.get(t);if(i===void 0)throw new Error(`Unknown theme color: ${t}`);return i}bold(e){return st.bold(e)}italic(e){return st.italic(e)}underline(e){return st.underline(e)}inverse(e){return st.inverse(e)}strikethrough(e){return st.strikethrough(e)}getFgAnsi(e){let t=this.tokenAnsi(this.fgAnsi,e);return this.dimTokens.has(e)?`${t}\x1B[2m`:t}getBgAnsi(e){return this.tokenAnsi(this.bgAnsi,e)}getColorMode(){return this.mode}getThinkingBorderColor(e){switch(e){case"off":return t=>this.fg("thinkingOff",t);case"minimal":return t=>this.fg("thinkingMinimal",t);case"low":return t=>this.fg("thinkingLow",t);case"medium":return t=>this.fg("thinkingMedium",t);case"high":return t=>this.fg("thinkingHigh",t);case"xhigh":return t=>this.fg("thinkingXhigh",t);case"max":return t=>this.fg("thinkingMax",t);default:return t=>this.fg("thinkingOff",t)}}getBashModeBorderColor(){return e=>this.fg("bashMode",e)}},cn;function Za(){if(!cn){let s=ji(),e=et.join(s,"dark.json"),t=et.join(s,"light.json");cn={dark:JSON.parse(As(ie.readFileSync(e,"utf-8"))),light:JSON.parse(As(ie.readFileSync(t,"utf-8")))}}return cn}function r1(){return Lp().map(({name:s})=>s)}function Lp(){let s=ji(),e=[],t=new Set,i=r=>{t.has(r.name)||(t.add(r.name),e.push(r))};i({name:G,path:void 0});for(let r of Object.keys(Za()))i({name:r,path:et.join(s,`${r}.json`)});for(let r of Ep())i(r);for(let[r,n]of Yt.entries())i({name:r,path:n.sourcePath});return e.sort((r,n)=>r.name===G?-1:n.name===G?1:r.name.localeCompare(n.name))}function Ep(){let s=Ls(),e=[];if(!ie.existsSync(s))return e;for(let t of ie.readdirSync(s)){if(!t.endsWith(".json"))continue;let i=et.join(s,t);try{let r=tc(i);r.name&&e.push({name:r.name,path:i})}catch{}}return e}function Pp(s){if(s.includes("/"))throw new Error(`Invalid theme name "${s}": theme names cannot contain "/" because it is reserved for automatic light/dark theme settings.`)}function $p(s,e){if(un)return un(s,e);if(typeof e!="object"||e===null||!("colors"in e))throw new Error(`Invalid theme "${s}": expected an object with a "colors" map.`);return e}function dn(s,e){let t;try{t=JSON.parse(As(e))}catch(i){throw new Error(`Failed to parse theme ${s}: ${i}`)}return $p(s,t)}function Ja(s){let e=Za();if(s in e)return e[s];let t=Yt.get(s);if(t?.sourcePath){let o=ie.readFileSync(t.sourcePath,"utf-8");return dn(t.sourcePath,o)}if(t)throw new Error(`Theme "${s}" does not have a source path for export`);let i=Ls(),r=et.join(i,`${s}.json`);if(!ie.existsSync(r))throw new Error(`Theme not found: ${s}`);let n=ie.readFileSync(r,"utf-8");return dn(s,n)}function mn(s){let e={},t={};for(let[i,r]of Object.entries(s))an[i].slot==="background"?t[i]=r:e[i]=r;return{fgColors:e,bgColors:t}}function ec(s,e,t){let i=e??ps(),r=pn(Ip(s.colors,s.vars)),{fgColors:n,bgColors:o}=mn(r);return new Ui(n,o,i,{name:s.name,sourcePath:t,appearance:s.appearance})}function _p(s){let e=za({...zi,saturation:gn?0:1,appearanceHint:sc()}),{fgColors:t,bgColors:i}=mn(pn(e.colors));return new Ui(t,i,s??ps(),{name:G,appearance:e.appearance,dim:e.dim})}function tc(s,e){let t=ie.readFileSync(s,"utf-8"),i=dn(s,t);return ec(i,e,s)}function jt(s,e){if(s===G)return _p(e);let t=Yt.get(s);if(t)return t;let i=Ja(s);return ec(i,e)}function n1(s){try{return jt(s)}catch{return}}function Op(s){if(!s)return;let e=s.indexOf("/");if(e===-1||s.indexOf("/",e+1)!==-1)return;let t=s.slice(0,e).trim(),i=s.slice(e+1).trim();if(!(!t||!i))return{lightTheme:t,darkTheme:i}}function o1(s,e){let t=Op(s);if(t)return e==="light"?t.lightTheme:t.darkTheme;if(!s?.includes("/")&&typeof s=="string")return s}function Bp(s=process.env){let e=s.COLORFGBG?.split(";").at(-1)?.trim();if(!e||!/^\d{1,2}$/.test(e))return;let t=Number(e);if(!(t>15))return t<=6||t===8?"dark":"light"}function Dp(s={},e,t=process.env){let{background:i,foreground:r}=s;return i?ln(i,r):e??Bp(t)??"dark"}function sc(){return Dp(zi,Xa)}var xn=Symbol.for("@earendil-works/pi-coding-agent:theme"),Np=Symbol.for("@mariozechner/pi-coding-agent:theme"),O=new Proxy({},{get(s,e){let t=globalThis[xn];if(!t)throw new Error("Theme not initialized. Call initTheme() first.");return t[e]}});function Wp(){return globalThis[xn]}function Gt(s){globalThis[xn]=s,globalThis[Np]=s}var J,Rs,Je,tt,Yt=new Map;function l1(s){Yt.clear();for(let e of s)e.name&&(Pp(e.name),Yt.set(e.name,e))}function a1(s,e=!1){let t=s??G;J=t;try{Gt(jt(t)),e&&ic()}catch{J=G,Gt(jt(G))}}function c1(s,e=!1){J=s;try{return Gt(jt(s)),e&&ic(),tt&&tt(),{success:!0}}catch(t){return J=G,Gt(jt(G)),{success:!1,error:t instanceof Error?t.message:String(t)}}}function h1(s){Gt(s),J="<in-memory>",rc(),tt&&tt()}function u1(s){tt=s}function ic(){if(rc(),!J||J==="dark"||J==="light"||J===G)return;let s=Ls(),e=J,t=`${e}.json`,i=et.join(s,t);if(!ie.existsSync(i))return;let r=()=>{Je&&clearTimeout(Je),Je=setTimeout(()=>{if(Je=void 0,J===e&&ie.existsSync(i))try{let n=tc(i);Yt.set(e,n),Gt(n),tt&&tt()}catch{}},100)};Rs=aa(s,(n,o)=>{if(J===e){if(!o){r();return}o===t&&r()}},()=>{en(Rs),Rs=void 0})??void 0}function rc(){Je&&(clearTimeout(Je),Je=void 0),en(Rs),Rs=void 0}function d1(s){let e=jt(s??J??G).colors;return Object.fromEntries(Object.entries(e).map(([t,i])=>[t,ft(i)]))}function f1(s){let e=s??J??G;if(e===G)return{};try{let t=Ja(e),i=t.export;if(!i)return{};let r=t.vars??{},n=o=>{if(o===void 0)return;let l=fn(o,r);if(typeof l=="number")return ft(es(l));if(l!=="")return/^okhsl\(/i.test(l)?ft(Se(l)):l};return{pageBg:n(i.pageBg),cardBg:n(i.cardBg),infoBg:n(i.infoBg)}}catch{return{}}}var Ya,hn;function Fp(s){return{default:e=>s.fg("text",e),keyword:e=>s.fg("syntaxKeyword",e),built_in:e=>s.fg("syntaxType",e),literal:e=>s.fg("syntaxNumber",e),number:e=>s.fg("syntaxNumber",e),regexp:e=>s.fg("syntaxString",e),string:e=>s.fg("syntaxString",e),subst:e=>s.fg("text",e),comment:e=>s.fg("syntaxComment",e),doctag:e=>s.fg("syntaxComment",e),meta:e=>s.fg("muted",e),function:e=>s.fg("syntaxFunction",e),title:e=>s.fg("syntaxFunction",e),class:e=>s.fg("syntaxType",e),type:e=>s.fg("syntaxType",e),tag:e=>s.fg("syntaxPunctuation",e),name:e=>s.fg("syntaxKeyword",e),attr:e=>s.fg("syntaxVariable",e),variable:e=>s.fg("syntaxVariable",e),params:e=>s.fg("syntaxVariable",e),operator:e=>s.fg("syntaxOperator",e),punctuation:e=>s.fg("syntaxPunctuation",e),emphasis:e=>s.italic(e),strong:e=>s.bold(e),link:e=>s.underline(e),addition:e=>s.fg("toolDiffAdded",e),deletion:e=>s.fg("toolDiffRemoved",e)}}function Hp(s){return(Ya!==s||!hn)&&(Ya=s,hn=Fp(s)),hn}function nc(s,e){let t=e&&Oa(e)?e:void 0;if(!t)return s.split(`
130
+ `).map(r=>O.fg("mdCodeBlock",r));let i={language:t,ignoreIllegals:!0,theme:Hp(O)};try{return _a(s,i).split(`
131
+ `)}catch{return s.split(`
132
+ `).map(r=>O.fg("mdCodeBlock",r))}}var Qa=class{last;highlight(e,t){let i=Wp(),r=Ba(),n=this.last;if(n?.code===e&&n.lang===t&&n.theme===i&&n.languageCount===r)return n.lines;let o=nc(e,t);return this.last={code:e,lang:t,theme:i,languageCount:r,lines:o},o}};function p1(s){let e=s.split(".").pop()?.toLowerCase();return e?{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",dart:"dart",groovy:"groovy",gradle:"groovy",nix:"nix",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"dockerfile",makefile:"makefile",cmake:"cmake",lua:"lua",perl:"perl",r:"r",scala:"scala",clj:"clojure",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",ml:"ocaml",vim:"vim",graphql:"graphql",proto:"protobuf",tf:"hcl",hcl:"hcl"}[e]:void 0}function g1(){return{heading:s=>O.fg("mdHeading",s),link:s=>O.fg("mdLink",s),linkUrl:s=>O.fg("mdLinkUrl",s),code:s=>O.fg("mdCode",s),codeBlock:s=>O.fg("mdCodeBlock",s),codeBlockBorder:s=>O.fg("mdCodeBlockBorder",s),quote:s=>O.fg("mdQuote",s),quoteBorder:s=>O.fg("mdQuoteBorder",s),hr:s=>O.fg("mdHr",s),listBullet:s=>O.fg("mdListBullet",s),bold:s=>O.bold(s),italic:s=>O.italic(s),underline:s=>O.underline(s),strikethrough:s=>O.strikethrough(s),highlightCode:nc}}function Kp(){return{selectedPrefix:s=>O.fg("accent",s),selectedText:s=>O.fg("accent",s),description:s=>O.fg("muted",s),scrollInfo:s=>O.fg("muted",s),noMatch:s=>O.fg("muted",s)}}function m1(){return{borderColor:s=>O.fg("borderMuted",s),selectList:Kp()}}function x1(){return{label:(s,e)=>e?O.fg("accent",s):s,value:(s,e)=>e?O.fg("accent",s):O.fg("muted",s),description:s=>O.fg("dim",s),cursor:O.fg("accent","\u2192 "),hint:s=>O.fg("dim",s)}}function Vp(s,e){let t=process.platform==="darwin"&&s.toLowerCase()==="alt"?"option":s;return e.capitalize?t.charAt(0).toUpperCase()+t.slice(1):t}function oc(s,e={}){return s.split("/").map(t=>t.split("+").map(i=>Vp(i,e)).join("+")).join("/")}function lc(s,e={}){return s.length===0?"":oc(s.join("/"),e)}function qp(s){return lc(U().getKeys(s))}function S1(s){return lc(U().getKeys(s),{capitalize:!0})}function C1(s,e){return O.fg("dim",qp(s))+O.fg("muted",` ${e}`)}function T1(s,e){return O.fg("dim",oc(s))+O.fg("muted",` ${e}`)}export{ds as a,br as b,Ke as c,S as d,at as e,ne as f,D as g,H as h,Zs as i,es as j,he as k,Se as l,me as m,Vs as n,pt as o,gt as p,Jn as q,ue as r,Sr as s,se as t,ps as u,Uo as v,oi as w,xs as x,bs as y,Z as z,ae as A,tl as B,ui as C,or as D,ls as E,no as F,U as G,yt as H,At as I,Lt as J,di as K,$t as L,gi as M,xl as N,bi as O,$e as P,Si as Q,Ci as R,Ft as S,Ti as T,vi as U,Mi as V,Ii as W,_l as X,jr as Y,Ei as Z,Fi as _,Hi as $,ap as aa,Dx as ba,en as ca,aa as da,Hx as ea,G as fa,an as ga,e1 as ha,t1 as ia,s1 as ja,i1 as ka,Ui as la,r1 as ma,Lp as na,tc as oa,n1 as pa,Op as qa,o1 as ra,sc as sa,O as ta,l1 as ua,a1 as va,c1 as wa,h1 as xa,u1 as ya,rc as za,d1 as Aa,f1 as Ba,nc as Ca,Qa as Da,p1 as Ea,g1 as Fa,Kp as Ga,m1 as Ha,x1 as Ia,oc as Ja,qp as Ka,S1 as La,C1 as Ma,T1 as Na};