@humain/humain-code 0.4.17 → 0.5.0

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 (439) hide show
  1. package/CHANGELOG.md +260 -1
  2. package/dist/bundle/agent-monitor.js +1 -1
  3. package/dist/bundle/chunks/anthropic-messages-ZP5KUK52.js +67 -0
  4. package/dist/bundle/chunks/anthropic.js +2 -2
  5. package/dist/bundle/chunks/azure-openai-responses-QJFYQ3DF.js +15 -0
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +152 -200
  7. package/dist/bundle/chunks/{chunk-4XU7TDAL.js → chunk-2GCMACT4.js} +48 -46
  8. package/dist/bundle/chunks/{chunk-DUSJT2W4.js → chunk-476XBL3W.js} +3 -3
  9. package/dist/bundle/chunks/{chunk-4NFYTS4C.js → chunk-5C4VL2AR.js} +4 -4
  10. package/dist/bundle/chunks/{chunk-QEF72EIZ.js → chunk-A6B2QMA7.js} +40 -96
  11. package/dist/bundle/chunks/{chunk-AOL6QG6L.js → chunk-A6YBWW4T.js} +1405 -1311
  12. package/dist/bundle/chunks/{chunk-ZRGFX6T6.js → chunk-CN3Q5UNB.js} +387 -309
  13. package/dist/bundle/chunks/{chunk-TJG52LZB.js → chunk-DR37WKFZ.js} +9 -8
  14. package/dist/bundle/chunks/chunk-DU6POZ7E.js +10 -0
  15. package/dist/bundle/chunks/{chunk-X6OTEVGA.js → chunk-FO2NYB6O.js} +626 -619
  16. package/dist/bundle/chunks/{chunk-RXOCQRBG.js → chunk-GEISZXXH.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-OKALNPTJ.js → chunk-HIZWUSPN.js} +24 -24
  18. package/dist/bundle/chunks/{chunk-MVYV6MJY.js → chunk-HT5YN3LX.js} +1 -1
  19. package/dist/bundle/chunks/chunk-IDU5BNNI.js +15 -0
  20. package/dist/bundle/chunks/{chunk-TIFFHHW6.js → chunk-JCXXRCP6.js} +5 -5
  21. package/dist/bundle/chunks/{chunk-QYCOHSI7.js → chunk-KKCMWB63.js} +8 -7
  22. package/dist/bundle/chunks/{chunk-SCBU5WOP.js → chunk-M74U5X4S.js} +30 -23
  23. package/dist/bundle/chunks/{chunk-AWCJWXGD.js → chunk-MIJHJNNQ.js} +3 -2
  24. package/dist/bundle/chunks/{chunk-Y26OS23T.js → chunk-N7CQ3UV3.js} +4 -4
  25. package/dist/bundle/chunks/{chunk-XQZG5HPT.js → chunk-O4DO5RWS.js} +11 -6
  26. package/dist/bundle/chunks/chunk-OR25QDSS.js +365 -0
  27. package/dist/bundle/chunks/{chunk-7PRU6YW3.js → chunk-OZNC2W4B.js} +306 -286
  28. package/dist/bundle/chunks/{chunk-Z33NNMNB.js → chunk-PH7UP57J.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-FHVNUUBF.js → chunk-PS7DGA7B.js} +1 -1
  30. package/dist/bundle/chunks/chunk-Q3SFYT2X.js +1965 -0
  31. package/dist/bundle/chunks/chunk-QW6PTCAB.js +10 -0
  32. package/dist/bundle/chunks/{chunk-5CDES42D.js → chunk-QWXPGBAG.js} +1 -1
  33. package/dist/bundle/chunks/{chunk-NCQ6WAQK.js → chunk-ROZV2IYD.js} +1 -1
  34. package/dist/bundle/chunks/{chunk-PTP2ZHFQ.js → chunk-RTXDU3AA.js} +148 -122
  35. package/dist/bundle/chunks/{chunk-36Q5UVQL.js → chunk-T3HXWZG4.js} +2 -2
  36. package/dist/bundle/chunks/{chunk-FZUJXM6D.js → chunk-UDB6NI4G.js} +309 -240
  37. package/dist/bundle/chunks/chunk-UTNHGOFS.js +88 -0
  38. package/dist/bundle/chunks/{chunk-H2FY3PEV.js → chunk-V62QBESW.js} +4 -3
  39. package/dist/bundle/chunks/{chunk-LG2PJ6JN.js → chunk-XA7CJAYH.js} +4 -3
  40. package/dist/bundle/chunks/chunk-XQX7S3GM.js +7 -0
  41. package/dist/bundle/chunks/chunk-YFOLLX5D.js +23 -0
  42. package/dist/bundle/chunks/{chunk-YRCLNWFV.js → chunk-ZI7TK7HM.js} +1 -1
  43. package/dist/bundle/chunks/{chunk-V76YPIMT.js → chunk-ZR4GF4WU.js} +21 -15
  44. package/dist/bundle/chunks/{cli-SRI4UOSL.js → cli-VXU7OWFU.js} +1 -1
  45. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-T7TPP7SQ.js +4 -0
  46. package/dist/bundle/chunks/codemode-worker.js +27 -27
  47. package/dist/bundle/chunks/compat-S2IBVV6V.js +13 -0
  48. package/dist/bundle/chunks/{dist-D7M52E3X.js → dist-645GFIWH.js} +452 -448
  49. package/dist/bundle/chunks/{dist-XVXV2CL4.js → dist-IBUWEKEE.js} +3 -3
  50. package/dist/bundle/chunks/dist-YFMJEHPH.js +8 -0
  51. package/dist/bundle/chunks/{dist-cjs-AXBW3N4F.js → dist-cjs-HTASUQXQ.js} +82 -80
  52. package/dist/bundle/chunks/{easter-egg-3d-4SUPLBUF.js → easter-egg-3d-YOPLCOVW.js} +2 -2
  53. package/dist/bundle/chunks/{esm-NCUV2DF7.js → esm-R6HJ4QEG.js} +5 -5
  54. package/dist/bundle/chunks/{event-streams-NXFTZDSF.js → event-streams-BR2IL6C5.js} +1 -1
  55. package/dist/bundle/chunks/{execute-NTO3U76E.js → execute-2JXEKQ2X.js} +17 -8
  56. package/dist/bundle/chunks/{extract-BKBHK4AK.js → extract-OTCGZGTL.js} +50 -47
  57. package/dist/bundle/chunks/github-copilot.js +42 -40
  58. package/dist/bundle/chunks/google-generative-ai-HVPCGIZ6.js +21 -0
  59. package/dist/bundle/chunks/google-vertex-UM5MAALA.js +25 -0
  60. package/dist/bundle/chunks/host-ZHEL5XQW.js +2 -0
  61. package/dist/bundle/chunks/{https-proxy-agent-7CAXVAFH.js → https-proxy-agent-JQICCRPH.js} +1 -1
  62. package/dist/bundle/chunks/{llama-cpp-classify-AGCW7HYN.js → llama-cpp-classify-B3G57LVR.js} +5 -5
  63. package/dist/bundle/chunks/{mistral-conversations-G3GN6CMT.js → mistral-conversations-AH72RLXK.js} +11 -11
  64. package/dist/bundle/chunks/{node-ELWNZC34.js → node-SJPZTR4K.js} +6 -6
  65. package/dist/bundle/chunks/{node-DZCAT4Q6.js → node-VSA4ZN7D.js} +1 -1
  66. package/dist/bundle/chunks/openai-chatgpt.js +2 -2
  67. package/dist/bundle/chunks/{openai-codex-responses-FJFDAWHI.js → openai-codex-responses-L366637C.js} +48 -47
  68. package/dist/bundle/chunks/openai-codex.js +2 -2
  69. package/dist/bundle/chunks/openai-completions-ZP62QXJX.js +83 -0
  70. package/dist/bundle/chunks/{openai-decisions-HESOHYZB.js → openai-decisions-WOWUC65P.js} +1 -1
  71. package/dist/bundle/chunks/openai-responses-DXUGSUTN.js +26 -0
  72. package/dist/bundle/chunks/openrouter-images-5K47HDAT.js +8 -0
  73. package/dist/bundle/chunks/openrouter.js +2 -2
  74. package/dist/bundle/chunks/{pi-messages-SAOV3JNW.js → pi-messages-MOQQDZBK.js} +5 -4
  75. package/dist/bundle/chunks/radius.js +2 -2
  76. package/dist/bundle/chunks/{runtime-VGSK3QCM.js → runtime-5VFZTMWL.js} +1 -1
  77. package/dist/bundle/chunks/typesafe-system-one-43OCHGKP.js +3 -0
  78. package/dist/bundle/chunks/{undici-N4LWJ3S3.js → undici-EK3EUI2E.js} +1 -1
  79. package/dist/bundle/chunks/virtual-modules-GU6AW5ZK.js +5 -0
  80. package/dist/bundle/cli-runtime.js +3 -3
  81. package/dist/bundle/flow/package.json +4 -4
  82. package/dist/bundle/index.js +6 -6
  83. package/dist/bundle/rpc-entry.js +3 -3
  84. package/dist/cli/args.d.ts +6 -0
  85. package/dist/cli/args.d.ts.map +1 -1
  86. package/dist/cli/args.js +11 -0
  87. package/dist/cli/args.js.map +1 -1
  88. package/dist/coordination/adapter/tool.d.ts.map +1 -1
  89. package/dist/coordination/adapter/tool.js +3 -1
  90. package/dist/coordination/adapter/tool.js.map +1 -1
  91. package/dist/coordination/broker/broker.d.ts +6 -2
  92. package/dist/coordination/broker/broker.d.ts.map +1 -1
  93. package/dist/coordination/broker/broker.js +20 -8
  94. package/dist/coordination/broker/broker.js.map +1 -1
  95. package/dist/coordination/client/client.d.ts.map +1 -1
  96. package/dist/coordination/client/client.js +4 -2
  97. package/dist/coordination/client/client.js.map +1 -1
  98. package/dist/coordination/transport/discovery.d.ts +10 -3
  99. package/dist/coordination/transport/discovery.d.ts.map +1 -1
  100. package/dist/coordination/transport/discovery.js +18 -5
  101. package/dist/coordination/transport/discovery.js.map +1 -1
  102. package/dist/core/agent-session.d.ts +35 -2
  103. package/dist/core/agent-session.d.ts.map +1 -1
  104. package/dist/core/agent-session.js +163 -40
  105. package/dist/core/agent-session.js.map +1 -1
  106. package/dist/core/anthropic-subscription-usage.d.ts +47 -0
  107. package/dist/core/anthropic-subscription-usage.d.ts.map +1 -0
  108. package/dist/core/anthropic-subscription-usage.js +170 -0
  109. package/dist/core/anthropic-subscription-usage.js.map +1 -0
  110. package/dist/core/bash-executor.d.ts.map +1 -1
  111. package/dist/core/bash-executor.js +7 -1
  112. package/dist/core/bash-executor.js.map +1 -1
  113. package/dist/core/client-identity.d.ts +13 -0
  114. package/dist/core/client-identity.d.ts.map +1 -0
  115. package/dist/core/client-identity.js +25 -0
  116. package/dist/core/client-identity.js.map +1 -0
  117. package/dist/core/codex-usage.d.ts +37 -1
  118. package/dist/core/codex-usage.d.ts.map +1 -1
  119. package/dist/core/codex-usage.js +104 -11
  120. package/dist/core/codex-usage.js.map +1 -1
  121. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  122. package/dist/core/compaction/branch-summarization.js +1 -2
  123. package/dist/core/compaction/branch-summarization.js.map +1 -1
  124. package/dist/core/compaction/compaction.d.ts +2 -2
  125. package/dist/core/compaction/compaction.d.ts.map +1 -1
  126. package/dist/core/compaction/compaction.js +20 -15
  127. package/dist/core/compaction/compaction.js.map +1 -1
  128. package/dist/core/export-html/index.d.ts.map +1 -1
  129. package/dist/core/export-html/index.js +2 -0
  130. package/dist/core/export-html/index.js.map +1 -1
  131. package/dist/core/export-html/template.html +1 -0
  132. package/dist/core/export-html/template.js +2 -1
  133. package/dist/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
  134. package/dist/core/export-html/vendor/marked.min.js +30 -29
  135. package/dist/core/extensions/loader.d.ts.map +1 -1
  136. package/dist/core/extensions/loader.js +3 -0
  137. package/dist/core/extensions/loader.js.map +1 -1
  138. package/dist/core/extensions/runner.d.ts +14 -0
  139. package/dist/core/extensions/runner.d.ts.map +1 -1
  140. package/dist/core/extensions/runner.js +86 -2
  141. package/dist/core/extensions/runner.js.map +1 -1
  142. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  143. package/dist/core/extensions/virtual-modules.js +3 -0
  144. package/dist/core/extensions/virtual-modules.js.map +1 -1
  145. package/dist/core/model-config.d.ts +920 -0
  146. package/dist/core/model-config.d.ts.map +1 -1
  147. package/dist/core/model-config.js +48 -24
  148. package/dist/core/model-config.js.map +1 -1
  149. package/dist/core/model-registry.d.ts +18 -0
  150. package/dist/core/model-registry.d.ts.map +1 -1
  151. package/dist/core/model-registry.js +20 -0
  152. package/dist/core/model-registry.js.map +1 -1
  153. package/dist/core/model-resolver.d.ts.map +1 -1
  154. package/dist/core/model-resolver.js +14 -6
  155. package/dist/core/model-resolver.js.map +1 -1
  156. package/dist/core/model-runtime.d.ts +9 -0
  157. package/dist/core/model-runtime.d.ts.map +1 -1
  158. package/dist/core/model-runtime.js +99 -12
  159. package/dist/core/model-runtime.js.map +1 -1
  160. package/dist/core/output-guard.d.ts +13 -1
  161. package/dist/core/output-guard.d.ts.map +1 -1
  162. package/dist/core/output-guard.js +101 -11
  163. package/dist/core/output-guard.js.map +1 -1
  164. package/dist/core/provider-composer.d.ts +2 -1
  165. package/dist/core/provider-composer.d.ts.map +1 -1
  166. package/dist/core/provider-composer.js +7 -3
  167. package/dist/core/provider-composer.js.map +1 -1
  168. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  169. package/dist/core/remote-catalog-provider.js +7 -2
  170. package/dist/core/remote-catalog-provider.js.map +1 -1
  171. package/dist/core/sdk.d.ts.map +1 -1
  172. package/dist/core/sdk.js +8 -9
  173. package/dist/core/sdk.js.map +1 -1
  174. package/dist/core/session-manager.d.ts +4 -0
  175. package/dist/core/session-manager.d.ts.map +1 -1
  176. package/dist/core/session-manager.js +242 -26
  177. package/dist/core/session-manager.js.map +1 -1
  178. package/dist/core/system-prompt.d.ts +6 -1
  179. package/dist/core/system-prompt.d.ts.map +1 -1
  180. package/dist/core/system-prompt.js +93 -1
  181. package/dist/core/system-prompt.js.map +1 -1
  182. package/dist/core/tools/grep.d.ts.map +1 -1
  183. package/dist/core/tools/grep.js +3 -1
  184. package/dist/core/tools/grep.js.map +1 -1
  185. package/dist/core/tools/ls.d.ts.map +1 -1
  186. package/dist/core/tools/ls.js +37 -12
  187. package/dist/core/tools/ls.js.map +1 -1
  188. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  189. package/dist/extensions/codemode/execute.js +102 -24
  190. package/dist/extensions/codemode/execute.js.map +1 -1
  191. package/dist/extensions/index.d.ts.map +1 -1
  192. package/dist/extensions/index.js +3 -1
  193. package/dist/extensions/index.js.map +1 -1
  194. package/dist/extensions/mcp/config.d.ts.map +1 -1
  195. package/dist/extensions/mcp/config.js +3 -2
  196. package/dist/extensions/mcp/config.js.map +1 -1
  197. package/dist/extensions/usage/index.d.ts +15 -0
  198. package/dist/extensions/usage/index.d.ts.map +1 -0
  199. package/dist/extensions/usage/index.js +110 -0
  200. package/dist/extensions/usage/index.js.map +1 -0
  201. package/dist/extensions/usage/overview.d.ts +90 -0
  202. package/dist/extensions/usage/overview.d.ts.map +1 -0
  203. package/dist/extensions/usage/overview.js +215 -0
  204. package/dist/extensions/usage/overview.js.map +1 -0
  205. package/dist/extensions/usage/popup.d.ts +21 -0
  206. package/dist/extensions/usage/popup.d.ts.map +1 -0
  207. package/dist/extensions/usage/popup.js +98 -0
  208. package/dist/extensions/usage/popup.js.map +1 -0
  209. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +21 -2
  210. package/dist/humain/bundled-extension-names.d.ts +6 -0
  211. package/dist/humain/bundled-extension-names.d.ts.map +1 -0
  212. package/dist/humain/bundled-extension-names.js +9 -0
  213. package/dist/humain/bundled-extension-names.js.map +1 -0
  214. package/dist/humain/index.d.ts +2 -2
  215. package/dist/humain/index.d.ts.map +1 -1
  216. package/dist/humain/index.js +3 -2
  217. package/dist/humain/index.js.map +1 -1
  218. package/dist/humain/web-access/vendor/anysearch.d.ts.map +1 -1
  219. package/dist/humain/web-access/vendor/anysearch.js +3 -3
  220. package/dist/humain/web-access/vendor/anysearch.js.map +1 -1
  221. package/dist/humain/web-access/vendor/bocha.d.ts.map +1 -1
  222. package/dist/humain/web-access/vendor/bocha.js +3 -3
  223. package/dist/humain/web-access/vendor/bocha.js.map +1 -1
  224. package/dist/humain/web-access/vendor/brightdata-unlocker.d.ts.map +1 -1
  225. package/dist/humain/web-access/vendor/brightdata-unlocker.js +2 -2
  226. package/dist/humain/web-access/vendor/brightdata-unlocker.js.map +1 -1
  227. package/dist/humain/web-access/vendor/brightdata.d.ts.map +1 -1
  228. package/dist/humain/web-access/vendor/brightdata.js +3 -3
  229. package/dist/humain/web-access/vendor/brightdata.js.map +1 -1
  230. package/dist/humain/web-access/vendor/ceramic.d.ts.map +1 -1
  231. package/dist/humain/web-access/vendor/ceramic.js +2 -2
  232. package/dist/humain/web-access/vendor/ceramic.js.map +1 -1
  233. package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
  234. package/dist/humain/web-access/vendor/curator-page.js +3 -1
  235. package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
  236. package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
  237. package/dist/humain/web-access/vendor/curator-server.js +2 -0
  238. package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
  239. package/dist/humain/web-access/vendor/deepseek.d.ts +11 -1
  240. package/dist/humain/web-access/vendor/deepseek.d.ts.map +1 -1
  241. package/dist/humain/web-access/vendor/deepseek.js +170 -5
  242. package/dist/humain/web-access/vendor/deepseek.js.map +1 -1
  243. package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
  244. package/dist/humain/web-access/vendor/extract.js +63 -6
  245. package/dist/humain/web-access/vendor/extract.js.map +1 -1
  246. package/dist/humain/web-access/vendor/gemini-search.d.ts +5 -3
  247. package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
  248. package/dist/humain/web-access/vendor/gemini-search.js +33 -7
  249. package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
  250. package/dist/humain/web-access/vendor/index.d.ts +1 -0
  251. package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
  252. package/dist/humain/web-access/vendor/index.js +18 -3
  253. package/dist/humain/web-access/vendor/index.js.map +1 -1
  254. package/dist/humain/web-access/vendor/jina-search.d.ts.map +1 -1
  255. package/dist/humain/web-access/vendor/jina-search.js +6 -4
  256. package/dist/humain/web-access/vendor/jina-search.js.map +1 -1
  257. package/dist/humain/web-access/vendor/kagi.d.ts.map +1 -1
  258. package/dist/humain/web-access/vendor/kagi.js +4 -4
  259. package/dist/humain/web-access/vendor/kagi.js.map +1 -1
  260. package/dist/humain/web-access/vendor/keenable.d.ts.map +1 -1
  261. package/dist/humain/web-access/vendor/keenable.js +2 -2
  262. package/dist/humain/web-access/vendor/keenable.js.map +1 -1
  263. package/dist/humain/web-access/vendor/linkup.d.ts +6 -0
  264. package/dist/humain/web-access/vendor/linkup.d.ts.map +1 -0
  265. package/dist/humain/web-access/vendor/linkup.js +167 -0
  266. package/dist/humain/web-access/vendor/linkup.js.map +1 -0
  267. package/dist/humain/web-access/vendor/mistral-search.d.ts.map +1 -1
  268. package/dist/humain/web-access/vendor/mistral-search.js +3 -3
  269. package/dist/humain/web-access/vendor/mistral-search.js.map +1 -1
  270. package/dist/humain/web-access/vendor/ollama.d.ts.map +1 -1
  271. package/dist/humain/web-access/vendor/ollama.js +4 -4
  272. package/dist/humain/web-access/vendor/ollama.js.map +1 -1
  273. package/dist/humain/web-access/vendor/parallel.js +6 -7
  274. package/dist/humain/web-access/vendor/parallel.js.map +1 -1
  275. package/dist/humain/web-access/vendor/perplexity.d.ts.map +1 -1
  276. package/dist/humain/web-access/vendor/perplexity.js +4 -3
  277. package/dist/humain/web-access/vendor/perplexity.js.map +1 -1
  278. package/dist/humain/web-access/vendor/querit.d.ts.map +1 -1
  279. package/dist/humain/web-access/vendor/querit.js +3 -3
  280. package/dist/humain/web-access/vendor/querit.js.map +1 -1
  281. package/dist/humain/web-access/vendor/search1api.d.ts.map +1 -1
  282. package/dist/humain/web-access/vendor/search1api.js +3 -3
  283. package/dist/humain/web-access/vendor/search1api.js.map +1 -1
  284. package/dist/humain/web-access/vendor/searchinfinity.d.ts.map +1 -1
  285. package/dist/humain/web-access/vendor/searchinfinity.js +3 -3
  286. package/dist/humain/web-access/vendor/searchinfinity.js.map +1 -1
  287. package/dist/humain/web-access/vendor/serpapi.d.ts.map +1 -1
  288. package/dist/humain/web-access/vendor/serpapi.js +6 -5
  289. package/dist/humain/web-access/vendor/serpapi.js.map +1 -1
  290. package/dist/humain/web-access/vendor/serpbase.d.ts.map +1 -1
  291. package/dist/humain/web-access/vendor/serpbase.js +4 -4
  292. package/dist/humain/web-access/vendor/serpbase.js.map +1 -1
  293. package/dist/humain/web-access/vendor/serpdive.d.ts.map +1 -1
  294. package/dist/humain/web-access/vendor/serpdive.js +3 -3
  295. package/dist/humain/web-access/vendor/serpdive.js.map +1 -1
  296. package/dist/humain/web-access/vendor/serper.d.ts.map +1 -1
  297. package/dist/humain/web-access/vendor/serper.js +5 -4
  298. package/dist/humain/web-access/vendor/serper.js.map +1 -1
  299. package/dist/humain/web-access/vendor/serply.d.ts.map +1 -1
  300. package/dist/humain/web-access/vendor/serply.js +2 -2
  301. package/dist/humain/web-access/vendor/serply.js.map +1 -1
  302. package/dist/humain/web-access/vendor/utils.d.ts +3 -1
  303. package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
  304. package/dist/humain/web-access/vendor/utils.js +27 -2
  305. package/dist/humain/web-access/vendor/utils.js.map +1 -1
  306. package/dist/humain/web-access/vendor/valyu.d.ts.map +1 -1
  307. package/dist/humain/web-access/vendor/valyu.js +3 -3
  308. package/dist/humain/web-access/vendor/valyu.js.map +1 -1
  309. package/dist/humain/web-access/vendor/web-tool-core.d.ts +2 -0
  310. package/dist/humain/web-access/vendor/web-tool-core.d.ts.map +1 -1
  311. package/dist/humain/web-access/vendor/web-tool-core.js +3 -0
  312. package/dist/humain/web-access/vendor/web-tool-core.js.map +1 -1
  313. package/dist/humain/web-access/vendor/xai-search.d.ts.map +1 -1
  314. package/dist/humain/web-access/vendor/xai-search.js +51 -8
  315. package/dist/humain/web-access/vendor/xai-search.js.map +1 -1
  316. package/dist/humain/web-access/vendor/xcrawl.d.ts.map +1 -1
  317. package/dist/humain/web-access/vendor/xcrawl.js +3 -3
  318. package/dist/humain/web-access/vendor/xcrawl.js.map +1 -1
  319. package/dist/humain/web-access/vendor/you.d.ts.map +1 -1
  320. package/dist/humain/web-access/vendor/you.js +2 -2
  321. package/dist/humain/web-access/vendor/you.js.map +1 -1
  322. package/dist/main.d.ts.map +1 -1
  323. package/dist/main.js +15 -2
  324. package/dist/main.js.map +1 -1
  325. package/dist/modes/interactive/components/assistant-message.d.ts +14 -2
  326. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  327. package/dist/modes/interactive/components/assistant-message.js +62 -7
  328. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  329. package/dist/modes/interactive/components/config-selector.js +1 -1
  330. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  331. package/dist/modes/interactive/components/custom-editor.d.ts +2 -0
  332. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  333. package/dist/modes/interactive/components/custom-editor.js +6 -1
  334. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  335. package/dist/modes/interactive/components/easter-egg-3d.js +1 -1
  336. package/dist/modes/interactive/components/easter-egg-3d.js.map +1 -1
  337. package/dist/modes/interactive/components/footer.d.ts +10 -2
  338. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  339. package/dist/modes/interactive/components/footer.js +141 -66
  340. package/dist/modes/interactive/components/footer.js.map +1 -1
  341. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  342. package/dist/modes/interactive/components/mermaid.js +16 -3
  343. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  344. package/dist/modes/interactive/components/model-selector.js +1 -1
  345. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  346. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
  347. package/dist/modes/interactive/components/themed-text.js +3 -2
  348. package/dist/modes/interactive/components/themed-text.js.map +1 -1
  349. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  350. package/dist/modes/interactive/components/tool-execution.js +17 -6
  351. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  352. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  353. package/dist/modes/interactive/components/user-message.js +3 -2
  354. package/dist/modes/interactive/components/user-message.js.map +1 -1
  355. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  356. package/dist/modes/interactive/components/visual-truncate.js +4 -2
  357. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  358. package/dist/modes/interactive/interactive-mode.d.ts +13 -17
  359. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  360. package/dist/modes/interactive/interactive-mode.js +90 -122
  361. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  362. package/dist/modes/print-mode.d.ts.map +1 -1
  363. package/dist/modes/print-mode.js +2 -5
  364. package/dist/modes/print-mode.js.map +1 -1
  365. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  366. package/dist/modes/rpc/rpc-mode.js +2 -3
  367. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  368. package/dist/package-manager-cli.d.ts.map +1 -1
  369. package/dist/package-manager-cli.js +2 -1
  370. package/dist/package-manager-cli.js.map +1 -1
  371. package/dist/utils/child-process.d.ts.map +1 -1
  372. package/dist/utils/child-process.js +3 -2
  373. package/dist/utils/child-process.js.map +1 -1
  374. package/dist/utils/clipboard-command.d.ts.map +1 -1
  375. package/dist/utils/clipboard-command.js +3 -0
  376. package/dist/utils/clipboard-command.js.map +1 -1
  377. package/dist/utils/pi-user-agent.d.ts +1 -0
  378. package/dist/utils/pi-user-agent.d.ts.map +1 -1
  379. package/dist/utils/pi-user-agent.js +3 -2
  380. package/dist/utils/pi-user-agent.js.map +1 -1
  381. package/dist/utils/shell.d.ts.map +1 -1
  382. package/dist/utils/shell.js +45 -13
  383. package/dist/utils/shell.js.map +1 -1
  384. package/dist/utils/tools-manager.d.ts.map +1 -1
  385. package/dist/utils/tools-manager.js +4 -3
  386. package/dist/utils/tools-manager.js.map +1 -1
  387. package/docs/codemode.md +2 -2
  388. package/docs/compaction.md +3 -3
  389. package/docs/coordination.md +1 -1
  390. package/docs/custom-provider.md +53 -1
  391. package/docs/docs.json +4 -0
  392. package/docs/environment-variables.md +2 -0
  393. package/docs/extensions.md +133 -10
  394. package/docs/models-configuration.md +197 -0
  395. package/docs/models.md +21 -5
  396. package/docs/settings.md +1 -1
  397. package/docs/slash-commands.md +10 -0
  398. package/docs/tui.md +70 -0
  399. package/docs/windows.md +16 -2
  400. package/examples/extensions/custom-provider-anthropic/package.json +2 -2
  401. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  402. package/examples/extensions/gondolin/package-lock.json +2 -2
  403. package/examples/extensions/gondolin/package.json +1 -1
  404. package/examples/extensions/sandbox/package-lock.json +2 -2
  405. package/examples/extensions/sandbox/package.json +2 -2
  406. package/examples/extensions/with-deps/package.json +1 -1
  407. package/examples/plugins/pi-example-plugin/package.json +2 -2
  408. package/npm-shrinkwrap.json +243 -219
  409. package/package.json +21 -20
  410. package/schemas/models.schema.json +84 -30
  411. package/src/coordination/UPSTREAM.md +36 -3
  412. package/src/coordination/upstream.json +3 -3
  413. package/src/humain/web-access/UPSTREAM.md +72 -1
  414. package/src/humain/web-access/upstream.json +5 -4
  415. package/dist/bundle/chunks/anthropic-messages-TSNY5MWH.js +0 -67
  416. package/dist/bundle/chunks/azure-openai-responses-Z4DCXO2G.js +0 -15
  417. package/dist/bundle/chunks/chunk-5K5RFXXO.js +0 -74
  418. package/dist/bundle/chunks/chunk-65U7MPF4.js +0 -1790
  419. package/dist/bundle/chunks/chunk-PY7SOXCA.js +0 -10
  420. package/dist/bundle/chunks/chunk-UGJAAWNC.js +0 -7
  421. package/dist/bundle/chunks/chunk-UGXYG7HN.js +0 -22
  422. package/dist/bundle/chunks/chunk-VEYTRNQC.js +0 -5
  423. package/dist/bundle/chunks/chunk-W2QRCQBX.js +0 -165
  424. package/dist/bundle/chunks/chunk-X3O5MCKJ.js +0 -7
  425. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-MUJQ6LT2.js +0 -4
  426. package/dist/bundle/chunks/compat-ARQPWKBQ.js +0 -13
  427. package/dist/bundle/chunks/dist-LKDZAEUQ.js +0 -7
  428. package/dist/bundle/chunks/google-generative-ai-SJ4JO2MY.js +0 -21
  429. package/dist/bundle/chunks/google-vertex-KNLNNDET.js +0 -25
  430. package/dist/bundle/chunks/host-63SNKK5Y.js +0 -2
  431. package/dist/bundle/chunks/openai-completions-IC7WRLTI.js +0 -82
  432. package/dist/bundle/chunks/openai-responses-XXCYDFSM.js +0 -24
  433. package/dist/bundle/chunks/openrouter-images-DT2HMZNO.js +0 -8
  434. package/dist/bundle/chunks/typesafe-system-one-HCMGHK6A.js +0 -2
  435. package/dist/bundle/chunks/virtual-modules-LP2ULVLW.js +0 -5
  436. package/dist/core/provider-attribution.d.ts +0 -4
  437. package/dist/core/provider-attribution.d.ts.map +0 -1
  438. package/dist/core/provider-attribution.js +0 -85
  439. package/dist/core/provider-attribution.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{source_default}from"./chunk-XQRYOCHA.js";import{require_core}from"./chunk-DNGJMRJW.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-YRCLNWFV.js";import{__export,__toESM}from"./chunk-JXWJOIH4.js";var ambiguousRanges=[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,
2
+ import{source_default}from"./chunk-XQRYOCHA.js";import{require_core}from"./chunk-DNGJMRJW.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-ZI7TK7HM.js";import{__export,__toESM}from"./chunk-JXWJOIH4.js";var ambiguousRanges=[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,
3
3
  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,
4
4
  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,
5
5
  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],fullwidthMinimalCodePoint=12288,fullwidthMaximumCodePoint=65510,fullwidthRanges=[12288,12288,65281,65376,65504,65510];var wideMinimalCodePoint=4352,wideMaximumCodePoint=262141,wideRanges=[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,
@@ -31,11 +31,11 @@ this.fgColor),this.bgColor&&codes.push(this.bgColor);let result=codes.length>0?`
31
31
  return this.underline&&(result+="\x1B[24m"),this.activeHyperlink&&(result+=formatOsc8Close(this.activeHyperlink.terminator)),result}};function updateTrackerFromText(text,tracker){let i=text.indexOf("\x1B");for(;i!==-1;){let length=ansiCodeLength(text,i);length>0?(tracker.process(text.substring(i,i+length)),i+=length):i++,i=text.indexOf("\x1B",i)}}function getActiveBackgroundAnsi(text){let tracker=new AnsiCodeTracker;return updateTrackerFromText(text,tracker),tracker.getActiveBackgroundCode()}function*graphemeSegments(text){
32
32
  for(let{segment}of graphemeSegmenter.segment(text))yield segment}function splitIntoTokensWithAnsi(text){let tokens=[],current="",pendingAnsi="",currentKind=null,i=0,flushCurrent=()=>{current&&(tokens.push(current),current="",currentKind=null)};for(;i<text.length;){let ansiResult=extractAnsiCode(text,i);if(ansiResult){pendingAnsi+=ansiResult.code,i+=ansiResult.length;continue}let end=text.indexOf("\x1B",i+1);for(;end!==-1&&ansiCodeLength(text,end)===0;)end=text.indexOf("\x1B",end+1);end===-1&&(end=
33
33
  text.length);let chunk=text.slice(i,end),ascii=isPrintableAscii(chunk);for(let segment of ascii?chunk:graphemeSegments(chunk)){let segmentIsSpace=segment===" ";if(!ascii&&!segmentIsSpace&&cjkBreakRegex.test(segment)){flushCurrent();let token=pendingAnsi+segment;pendingAnsi="",tokens.push(token);continue}let segmentKind=segmentIsSpace?"space":"word";current&&currentKind!==segmentKind&&flushCurrent(),pendingAnsi&&(current+=pendingAnsi,pendingAnsi=""),currentKind=segmentKind,current+=segment}i=end}
34
- return pendingAnsi&&(current?current+=pendingAnsi:tokens.length>0?tokens[tokens.length-1]+=pendingAnsi:current=pendingAnsi),current&&tokens.push(current),tokens}function flattenLines(lines){for(let line of lines)Number(line)}function wrapTextWithAnsi(text,width){if(!text)return[""];let inputLines=text.split(/\r\n|\r|\n/),result=[],tracker=new AnsiCodeTracker;for(let inputLine of inputLines){let prefix=result.length>0?tracker.getActiveCodes():"",wrappedLines=wrapSingleLine(prefix+inputLine,width);
35
- for(let wrappedLine of wrappedLines)result.push(wrappedLine);updateTrackerFromText(inputLine,tracker)}return result.length>0?result:[""]}function wrapSingleLine(line,width){if(!line)return[""];if(visibleWidth(line)<=width)return[line];let wrapped=[],tracker=new AnsiCodeTracker,tokens=splitIntoTokensWithAnsi(line),currentLine="",currentVisibleLength=0;for(let token of tokens){let tokenVisibleLength=visibleWidth(token),isWhitespace=token.trim()==="";if(tokenVisibleLength>width&&!isWhitespace){if(currentLine){
36
- let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),wrapped.push(currentLine),currentLine="",currentVisibleLength=0}let broken=breakLongWord(token,width,tracker);for(let i=0;i<broken.length-1;i++)wrapped.push(broken[i]);currentLine=broken[broken.length-1],currentVisibleLength=visibleWidth(currentLine);continue}if(currentVisibleLength+tokenVisibleLength>width&&currentVisibleLength>0){let lineToWrap=currentLine.trimEnd(),lineEndReset=tracker.getLineEndReset();lineEndReset&&
37
- (lineToWrap+=lineEndReset),wrapped.push(lineToWrap),isWhitespace?(currentLine=tracker.getActiveCodes(),currentVisibleLength=0):(currentLine=tracker.getActiveCodes()+token,currentVisibleLength=tokenVisibleLength)}else currentLine+=token,currentVisibleLength+=tokenVisibleLength;updateTrackerFromText(token,tracker)}return currentLine&&wrapped.push(currentLine),wrapped.length>0?wrapped.map(line2=>line2.trimEnd()):[""]}var PUNCTUATION_REGEX=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function isWhitespaceChar(char){
38
- return/\s/.test(char)}function breakLongWord(word,width,tracker){let lines=[],currentLine=tracker.getActiveCodes(),currentWidth=0,i=0,segments=[];for(;i<word.length;){let ansiResult=extractAnsiCode(word,i);if(ansiResult)segments.push({type:"ansi",value:ansiResult.code}),i+=ansiResult.length;else{let end=i;for(;end<word.length&&!extractAnsiCode(word,end);)end++;let textPortion=word.slice(i,end);for(let seg of graphemeSegmenter.segment(textPortion))segments.push({type:"grapheme",value:seg.segment});i=end}}for(let seg of segments){
34
+ return pendingAnsi&&(current?current+=pendingAnsi:tokens.length>0?tokens[tokens.length-1]+=pendingAnsi:current=pendingAnsi),current&&tokens.push(current),tokens}function flattenLines(lines){for(let line of lines)Number(line)}function wrapTextWithAnsi(text,width){if(!text)return[""];if(text.indexOf(`
35
+ `)===-1&&text.indexOf("\r")===-1)return wrapSingleLine(text,width);let inputLines=text.split(/\r\n|\r|\n/),result=[],tracker=new AnsiCodeTracker;for(let index=0;index<inputLines.length;index++){let inputLine=inputLines[index],prefix=result.length>0?tracker.getActiveCodes():"",wrappedLines=wrapSingleLine(prefix+inputLine,width);for(let wrappedLine of wrappedLines)result.push(wrappedLine);index<inputLines.length-1&&updateTrackerFromText(inputLine,tracker)}return result.length>0?result:[""]}function wrapSingleLine(line,width){
36
+ if(!line)return[""];if(visibleWidth(line)<=width)return[line];let wrapped=[],tracker=new AnsiCodeTracker,tokens=splitIntoTokensWithAnsi(line),currentLine="",currentVisibleLength=0;for(let token of tokens){let tokenVisibleLength=visibleWidth(token),isWhitespace=token.trim()==="";if(tokenVisibleLength>width&&!isWhitespace){if(currentLine){let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),wrapped.push(currentLine),currentLine="",currentVisibleLength=0}let broken=breakLongWord(
37
+ token,width,tracker);for(let i=0;i<broken.length-1;i++)wrapped.push(broken[i]);currentLine=broken[broken.length-1],currentVisibleLength=visibleWidth(currentLine);continue}if(currentVisibleLength+tokenVisibleLength>width&&currentVisibleLength>0){let lineToWrap=currentLine.trimEnd(),lineEndReset=tracker.getLineEndReset();lineEndReset&&(lineToWrap+=lineEndReset),wrapped.push(lineToWrap),isWhitespace?(currentLine=tracker.getActiveCodes(),currentVisibleLength=0):(currentLine=tracker.getActiveCodes()+
38
+ token,currentVisibleLength=tokenVisibleLength)}else currentLine+=token,currentVisibleLength+=tokenVisibleLength;updateTrackerFromText(token,tracker)}return currentLine&&wrapped.push(currentLine),wrapped.length>0?wrapped.map(line2=>line2.trimEnd()):[""]}var PUNCTUATION_REGEX=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function isWhitespaceChar(char){return/\s/.test(char)}function breakLongWord(word,width,tracker){let lines=[],currentLine=tracker.getActiveCodes(),currentWidth=0,i=0,segments=[];for(;i<word.length;){let ansiResult=extractAnsiCode(word,i);if(ansiResult)segments.push({type:"ansi",value:ansiResult.code}),i+=ansiResult.length;else{let end=i;for(;end<word.length&&!extractAnsiCode(word,end);)end++;let textPortion=word.slice(i,end);for(let seg of graphemeSegmenter.segment(textPortion))segments.push({type:"grapheme",value:seg.segment});i=end}}for(let seg of segments){
39
39
  if(seg.type==="ansi"){currentLine+=seg.value,tracker.process(seg.value);continue}let grapheme=seg.value;if(!grapheme)continue;let graphemeWidth2=visibleWidth(grapheme);if(currentWidth+graphemeWidth2>width){let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),lines.push(currentLine),currentLine=tracker.getActiveCodes(),currentWidth=0}currentLine+=grapheme,currentWidth+=graphemeWidth2}return currentLine&&lines.push(currentLine),lines.length>0?lines:[""]}function applyBackgroundToLine(line,width,bgFn){
40
40
  let visibleLen=visibleWidth(line),paddingNeeded=Math.max(0,width-visibleLen),padding=" ".repeat(paddingNeeded),withPadding=line+padding;return bgFn(withPadding)}function truncateToWidth(text,maxWidth,ellipsis="...",pad=!1){if(maxWidth<=0)return"";if(text.length===0)return pad?" ".repeat(maxWidth):"";let ellipsisWidth=visibleWidth(ellipsis);if(ellipsisWidth>=maxWidth){let textWidth=visibleWidth(text);if(textWidth<=maxWidth)return pad?text+" ".repeat(maxWidth-textWidth):text;let clippedEllipsis=truncateFragmentToWidth(
41
41
  ellipsis,maxWidth);return clippedEllipsis.width===0?pad?" ".repeat(maxWidth):"":finalizeTruncatedResult("",0,clippedEllipsis.text,clippedEllipsis.width,maxWidth,pad)}if(isPrintableAscii(text)){if(text.length<=maxWidth)return pad?text+" ".repeat(maxWidth-text.length):text;let targetWidth2=maxWidth-ellipsisWidth;return finalizeTruncatedResult(text.slice(0,targetWidth2),targetWidth2,ellipsis,ellipsisWidth,maxWidth,pad)}let targetWidth=maxWidth-ellipsisWidth,result="",pendingAnsi="",visibleSoFar=0,keptWidth=0,
@@ -131,13 +131,14 @@ p":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen
131
131
  definitions,this.userBindings=userBindings,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let userClaims=new Map;for(let[keybinding,keys]of Object.entries(this.userBindings))if(keybinding in this.definitions)for(let key of normalizeKeys(keys)){let claimants=userClaims.get(key)??new Set;claimants.add(keybinding),userClaims.set(key,claimants)}for(let[key,keybindings]of userClaims)keybindings.size>1&&this.conflicts.push({key,keybindings:[...keybindings]});for(let[id,definition]of Object.
132
132
  entries(this.definitions)){let userKeys=this.userBindings[id],keys=normalizeKeys(userKeys===void 0?definition.defaultKeys:userKeys);this.keysById.set(id,keys)}}matches(data,keybinding){let keys=this.keysById.get(keybinding)??[];for(let key of keys)if(matchesKey(data,key))return!0;return!1}getKeys(keybinding){return[...this.keysById.get(keybinding)??[]]}getDefinition(keybinding){return this.definitions[keybinding]}getConflicts(){return this.conflicts.map(conflict=>({...conflict,keybindings:[...conflict.
133
133
  keybindings]}))}setUserBindings(userBindings){this.userBindings=userBindings,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let resolved={};for(let id of Object.keys(this.definitions)){let keys=this.keysById.get(id)??[];resolved[id]=keys.length===1?keys[0]:[...keys]}return resolved}},globalKeybindings=null;function setKeybindings(keybindings){globalKeybindings=keybindings}function getKeybindings(){return globalKeybindings||(globalKeybindings=new KeybindingsManager(
134
- TUI_KEYBINDINGS)),globalKeybindings}var dist_exports={};__export(dist_exports,{Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,Image:()=>Image,Input:()=>Input,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,Markdown:()=>Markdown,Marked:()=>U,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,
135
- SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,backgroundAnsi:()=>backgroundAnsi,calculateImageRows:()=>calculateImageRows,colorToHex:()=>colorToHex,colorToOkhsl:()=>colorToOkhsl,colorToOklch:()=>colorToOklch,colorToRgb:()=>colorToRgb,compositeTuiLine:()=>compositeTuiLine,
134
+ TUI_KEYBINDINGS)),globalKeybindings}var dist_exports={};__export(dist_exports,{Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,Image:()=>Image,Input:()=>Input,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,LiveLineArray:()=>LiveLineArray,Loader:()=>Loader,Markdown:()=>Markdown,Marked:()=>U,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,
135
+ SelectList:()=>SelectList,SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,backgroundAnsi:()=>backgroundAnsi,calculateImageRows:()=>calculateImageRows,colorToHex:()=>colorToHex,colorToOkhsl:()=>colorToOkhsl,colorToOklch:()=>colorToOklch,colorToRgb:()=>colorToRgb,compositeTuiLine:()=>compositeTuiLine,
136
136
  decodeKittyPrintable:()=>decodeKittyPrintable,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,foregroundAnsi:()=>foregroundAnsi,formatProgramStatus:()=>formatProgramStatus,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getImageDimensions:()=>getImageDimensions,
137
137
  getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,indexedColor:()=>indexedColor,invalidateRenderedMarkdown:()=>invalidateRenderedMarkdown,isAppleTerminalSession:()=>isAppleTerminalSession,isFocusable:()=>isFocusable,
138
- isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isStableRender:()=>isStableRender,isViewportTUI:()=>isViewportTUI,markStableRender:()=>markStableRender,matchesKey:()=>matchesKey,mixColors:()=>mixColors,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,oklchColor:()=>oklchColor,onCapabilitiesChange:()=>onCapabilitiesChange,parseColor:()=>parseColor,parseKey:()=>parseKey,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,
139
- renderFakeCursor:()=>renderFakeCursor,renderImage:()=>renderImage,renderLatex:()=>renderLatex,renderSharedLines:()=>renderSharedLines,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,
140
- styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function B(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var y=B();function V(a3){y=a3}var M={exec:()=>null};function D(a3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),i=e[n];return i||(i=a3(n),e[n]=i),i}}function h(a3,e=""){let t=typeof a3=="string"?a3:a3.source,n={replace:(i,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(x.caret,"$1"),t=t.replace(i,o),n},getRegex:()=>new RegExp(t,e)};return n}
138
+ isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isStableRender:()=>isStableRender,isViewportTUI:()=>isViewportTUI,markLiveRender:()=>markLiveRender,markReportsChanges:()=>markReportsChanges,markStableRender:()=>markStableRender,matchesKey:()=>matchesKey,mixColors:()=>mixColors,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,oklchColor:()=>oklchColor,onCapabilitiesChange:()=>onCapabilitiesChange,parseColor:()=>parseColor,
139
+ parseKey:()=>parseKey,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,renderChildLines:()=>renderChildLines,renderFakeCursor:()=>renderFakeCursor,renderImage:()=>renderImage,renderLatex:()=>renderLatex,renderLiveLines:()=>renderLiveLines,renderSharedLines:()=>renderSharedLines,reportRenderChange:()=>reportRenderChange,reportsChanges:()=>reportsChanges,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,
140
+ setCellDimensions:()=>setCellDimensions,setChangeReportsForTest:()=>setChangeReportsForTest,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,setRenderClockForTest:()=>setRenderClockForTest,setRenderOwner:()=>setRenderOwner,setSubtreeReportsChanges:()=>setSubtreeReportsChanges,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,
141
+ truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function B(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var y=B();function V(a3){y=a3}var M={exec:()=>null};function D(a3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),i=e[n];return i||(i=a3(n),e[n]=i),i}}function h(a3,e=""){let t=typeof a3=="string"?a3:a3.source,n={replace:(i,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(x.caret,"$1"),t=t.replace(i,o),n},getRegex:()=>new RegExp(t,e)};return n}
141
142
  var ze=((a3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+a3)}catch{return!1}})(),x={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,
142
143
  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,
143
144
  endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,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,
@@ -279,62 +280,75 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
279
280
  a3,e)};f.parseInline=I.parseInline;f.Parser=O;f.parser=O.parse;f.Renderer=$;f.TextRenderer=z;f.Lexer=T;f.lexer=T.lex;f.Tokenizer=_;f.Hooks=L;f.parse=f;var Rn=f.options,Tn=f.setOptions,On=f.walkTokens,wn=f.parseInline;var yn=O.parse,Sn=T.lex;import{spawn}from"child_process";import{readdirSync,statSync}from"fs";import{homedir}from"os";import{basename,dirname,join}from"path";function fuzzyMatch(query,text){let queryLower=query.toLowerCase(),textLower=text.toLowerCase(),matchQuery=normalizedQuery=>{if(normalizedQuery.length===0)return{matches:!0,score:0};if(normalizedQuery.length>textLower.length)return{matches:!1,score:0};let queryIndex=0,score=0,lastMatchIndex=-1,consecutiveMatches=0;for(;queryIndex<normalizedQuery.length;){let i=textLower.indexOf(normalizedQuery[queryIndex],lastMatchIndex+1);if(i===-1)break;let isWordBoundary=i===0||/[\s\-_./:]/.test(textLower[i-1]);
280
281
  lastMatchIndex===i-1?(consecutiveMatches++,score-=consecutiveMatches*5):(consecutiveMatches=0,lastMatchIndex>=0&&(score+=(i-lastMatchIndex-1)*2)),isWordBoundary&&(score-=10),score+=i*.1,lastMatchIndex=i,queryIndex++}return queryIndex<normalizedQuery.length?{matches:!1,score:0}:(normalizedQuery===textLower&&(score-=100),{matches:!0,score})},primaryMatch=matchQuery(queryLower);if(primaryMatch.matches)return primaryMatch;let alphaNumericMatch=queryLower.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/),
281
282
  numericAlphaMatch=queryLower.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/),swappedQuery=alphaNumericMatch?`${alphaNumericMatch.groups?.digits??""}${alphaNumericMatch.groups?.letters??""}`:numericAlphaMatch?`${numericAlphaMatch.groups?.letters??""}${numericAlphaMatch.groups?.digits??""}`:"";if(!swappedQuery)return primaryMatch;let swappedMatch=matchQuery(swappedQuery);return swappedMatch.matches?{matches:!0,score:swappedMatch.score+5}:primaryMatch}function fuzzyFilter(items,query,getText){if(!query.
282
- trim())return items;let tokens=query.trim().split(/[\s/]+/).filter(t=>t.length>0);if(tokens.length===0)return items;let results=[];for(let item of items){let text=getText(item),totalScore=0,allMatch=!0;for(let token of tokens){let match=fuzzyMatch(token,text);if(match.matches)totalScore+=match.score;else{allMatch=!1;break}}allMatch&&results.push({item,totalScore})}return results.sort((a3,b)=>a3.totalScore-b.totalScore),results.map(r=>r.item)}var PATH_DELIMITERS=new Set([" "," ",'"',"'","="]),tokenStartRegex=new RegExp(`${autocompleteBoundaryRegex.source}$`,"u"),PATH_WRAPPERS={"(":")","[":"]","{":"}","<":">","`":"`"};function toDisplayPath(value){return value.replace(/\\/g,"/")}function escapeRegex(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildFdPathQuery(query){let normalized=toDisplayPath(query);if(!normalized.includes("/"))return normalized;let hasTrailingSeparator=normalized.endsWith("/"),trimmed=normalized.
283
- replace(/^\/+|\/+$/g,"");if(!trimmed)return normalized;let separatorPattern="[\\\\/]",segments=trimmed.split("/").filter(Boolean).map(segment=>escapeRegex(segment));if(segments.length===0)return normalized;let pattern=segments.join(separatorPattern);return hasTrailingSeparator&&(pattern+=separatorPattern),pattern}function findLastDelimiter(text){let lastDelimiter=-1,index=0;for(let character of text)index+=character.length,(PATH_DELIMITERS.has(character)||autocompleteSeparatorRegex.test(character))&&
284
- (lastDelimiter=index-1);return lastDelimiter}function stripLeadingWrappers(token){let result=token;for(;result.length>0;){let closer=PATH_WRAPPERS[result[0]];if(!closer||result.includes(closer,1))break;result=result.slice(1)}return result}function findUnclosedQuoteStart(text){let inQuotes=!1,quoteStart=-1;for(let i=0;i<text.length;i+=1)text[i]==='"'&&(inQuotes=!inQuotes,inQuotes&&(quoteStart=i));return inQuotes?quoteStart:null}function isTokenStart(text,index){let start=index;for(;start>0&&PATH_WRAPPERS[text[start-
285
- 1]];)start-=1;return PATH_DELIMITERS.has(text[start-1]??"")||tokenStartRegex.test(text.slice(0,start))}function extractQuotedPrefix(text){let quoteStart=findUnclosedQuoteStart(text);return quoteStart===null?null:quoteStart>0&&text[quoteStart-1]==="@"?isTokenStart(text,quoteStart-1)?text.slice(quoteStart-1):null:isTokenStart(text,quoteStart)?text.slice(quoteStart):null}function parsePathPrefix(prefix){return prefix.startsWith('@"')?{rawPrefix:prefix.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:prefix.
286
- startsWith('"')?{rawPrefix:prefix.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:prefix.startsWith("@")?{rawPrefix:prefix.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:prefix,isAtPrefix:!1,isQuotedPrefix:!1}}function buildCompletionValue(path5,options){let needsQuotes=options.isQuotedPrefix||autocompleteSeparatorRegex.test(path5),prefix=options.isAtPrefix?"@":"";return needsQuotes?`${`${prefix}"`}${path5}"`:`${prefix}${path5}`}async function walkDirectoryWithFd(baseDir,fdPath,query,maxResults,signal,maxDepth){
287
- let args=["--base-directory",baseDir,"--max-results",String(maxResults),"--type","f","--type","d","--follow","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];return maxDepth!==void 0&&args.push("--max-depth",String(maxDepth)),toDisplayPath(query).includes("/")&&args.push("--full-path"),query&&args.push(buildFdPathQuery(query)),await new Promise(resolve=>{if(signal.aborted){resolve([]);return}let child=spawn(fdPath,args,{stdio:["ignore","pipe","pipe"]}),stdout="",resolved=!1,
288
- finish=results=>{resolved||(resolved=!0,signal.removeEventListener("abort",onAbort),resolve(results))},onAbort=()=>{child.exitCode===null&&child.kill("SIGKILL")};signal.addEventListener("abort",onAbort,{once:!0}),child.stdout.setEncoding("utf-8"),child.stdout.on("data",chunk=>{stdout+=chunk}),child.on("error",()=>{finish([])}),child.on("close",code=>{if(signal.aborted||code!==0||!stdout){finish([]);return}let lines=stdout.trim().split(`
289
- `).filter(Boolean),results=[];for(let line of lines){let displayLine=toDisplayPath(line),hasTrailingSeparator=displayLine.endsWith("/"),normalizedPath=hasTrailingSeparator?displayLine.slice(0,-1):displayLine;normalizedPath===".git"||normalizedPath.startsWith(".git/")||normalizedPath.includes("/.git/")||results.push({path:displayLine,isDirectory:hasTrailingSeparator})}finish(results)})})}var CombinedAutocompleteProvider=class{commands;basePath;fdPath;constructor(commands=[],basePath,fdPath=null){
290
- this.commands=commands,this.basePath=basePath,this.fdPath=fdPath}async getSuggestions(lines,cursorLine,cursorCol,options){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol),atPrefix=this.extractAtPrefix(textBeforeCursor);if(atPrefix){let{rawPrefix,isQuotedPrefix}=parsePathPrefix(atPrefix),suggestions2=await this.getFuzzyFileSuggestions(rawPrefix,{isQuotedPrefix,signal:options.signal});return suggestions2.length===0?null:{items:suggestions2,prefix:atPrefix}}let commandText=textBeforeCursor.
291
- trimStart();if(!options.force&&commandText.startsWith("/")){let spaceIndex=commandText.indexOf(" ");if(spaceIndex===-1){let prefix=commandText.slice(1),commandItems=this.commands.map(cmd=>{let name="name"in cmd?cmd.name:cmd.value,hint="argumentHint"in cmd&&cmd.argumentHint?cmd.argumentHint:void 0,desc=cmd.description??"",fullDesc=hint?desc?`${hint} \u2014 ${desc}`:hint:desc;return{name,label:name,description:fullDesc||void 0}}),bareNameMatches=fuzzyFilter(commandItems,prefix,item=>item.name.startsWith(
292
- "skill:")?item.name.slice(6):item.name),bareNameMatchSet=new Set(bareNameMatches),fullNameOnlyMatches=fuzzyFilter(commandItems.filter(item=>item.name.startsWith("skill:")&&!bareNameMatchSet.has(item)),prefix,item=>item.name),filtered=[...bareNameMatches,...fullNameOnlyMatches].map(item=>({value:item.name,label:item.label,...item.description&&{description:item.description}}));return filtered.length===0?null:{items:filtered,prefix:commandText}}let commandName=commandText.slice(1,spaceIndex),argumentText=commandText.
293
- slice(spaceIndex+1),command=this.commands.find(cmd=>("name"in cmd?cmd.name:cmd.value)===commandName);if(!command||!("getArgumentCompletions"in command)||!command.getArgumentCompletions)return null;let argumentSuggestions=await command.getArgumentCompletions(argumentText);return!Array.isArray(argumentSuggestions)||argumentSuggestions.length===0?null:{items:argumentSuggestions,prefix:argumentText}}let pathMatch=this.extractPathPrefix(textBeforeCursor,options.force??!1);if(pathMatch===null)return null;
294
- let suggestions=this.getFileSuggestions(pathMatch);return suggestions.length===0?null:{items:suggestions,prefix:pathMatch}}applyCompletion(lines,cursorLine,cursorCol,item,prefix){let currentLine=lines[cursorLine]||"",beforePrefix=currentLine.slice(0,cursorCol-prefix.length),afterCursor=currentLine.slice(cursorCol),isQuotedPrefix=prefix.startsWith('"')||prefix.startsWith('@"'),hasLeadingQuoteAfterCursor=afterCursor.startsWith('"'),hasTrailingQuoteInItem=item.value.endsWith('"'),adjustedAfterCursor=isQuotedPrefix&&
295
- hasTrailingQuoteInItem&&hasLeadingQuoteAfterCursor?afterCursor.slice(1):afterCursor;if(prefix.startsWith("/")&&beforePrefix.trim()===""&&!prefix.slice(1).includes("/")){let newLine2=`${beforePrefix}/${item.value} ${adjustedAfterCursor}`,newLines2=[...lines];return newLines2[cursorLine]=newLine2,{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+item.value.length+2}}if(prefix.startsWith("@")){let isDirectory2=item.label.endsWith("/"),suffix=isDirectory2?"":" ",newLine2=`${beforePrefix+item.
296
- value}${suffix}${adjustedAfterCursor}`,newLines2=[...lines];newLines2[cursorLine]=newLine2;let hasTrailingQuote2=item.value.endsWith('"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2+suffix.length}}let textBeforeCursor=currentLine.slice(0,cursorCol);if(textBeforeCursor.includes("/")&&textBeforeCursor.includes(" ")){let newLine2=beforePrefix+item.value+adjustedAfterCursor,newLines2=[
297
- ...lines];newLines2[cursorLine]=newLine2;let isDirectory2=item.label.endsWith("/"),hasTrailingQuote2=item.value.endsWith('"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2}}let newLine=beforePrefix+item.value+adjustedAfterCursor,newLines=[...lines];newLines[cursorLine]=newLine;let isDirectory=item.label.endsWith("/"),hasTrailingQuote=item.value.endsWith('"'),cursorOffset=isDirectory&&
298
- hasTrailingQuote?item.value.length-1:item.value.length;return{lines:newLines,cursorLine,cursorCol:beforePrefix.length+cursorOffset}}extractAtPrefix(text){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix?.startsWith('@"'))return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),token=stripLeadingWrappers(lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return token.startsWith("@")?token:null}extractPathPrefix(text,forceExtract=!1){let quotedPrefix=extractQuotedPrefix(
299
- text);if(quotedPrefix)return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),pathPrefix=stripLeadingWrappers(lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return forceExtract||pathPrefix.includes("/")||pathPrefix.startsWith(".")||pathPrefix.startsWith("~/")||pathPrefix===""&&text!==""&&tokenStartRegex.test(text)?pathPrefix:null}expandHomePath(path5){if(path5.startsWith("~/")){let expandedPath=join(homedir(),path5.slice(2));return path5.endsWith("/")&&!expandedPath.endsWith(
300
- "/")?`${expandedPath}/`:expandedPath}else if(path5==="~")return homedir();return path5}resolveScopedFuzzyQuery(rawQuery){let normalizedQuery=toDisplayPath(rawQuery),slashIndex=normalizedQuery.lastIndexOf("/");if(slashIndex===-1)return null;let displayBase=normalizedQuery.slice(0,slashIndex+1),query=normalizedQuery.slice(slashIndex+1),baseDir;displayBase.startsWith("~/")?baseDir=this.expandHomePath(displayBase):displayBase.startsWith("/")?baseDir=displayBase:baseDir=join(this.basePath,displayBase);
301
- try{if(!statSync(baseDir).isDirectory())return null}catch{return null}return{baseDir,query,displayBase}}scopedPathForDisplay(displayBase,relativePath){let normalizedRelativePath=toDisplayPath(relativePath);return displayBase==="/"?`/${normalizedRelativePath}`:`${toDisplayPath(displayBase)}${normalizedRelativePath}`}getFileSuggestions(prefix){try{let searchDir,searchPrefix,{rawPrefix,isAtPrefix,isQuotedPrefix}=parsePathPrefix(prefix),expandedPrefix=rawPrefix;if(expandedPrefix.startsWith("~")&&(expandedPrefix=
302
- this.expandHomePath(expandedPrefix)),rawPrefix===""||rawPrefix==="./"||rawPrefix==="../"||rawPrefix==="~"||rawPrefix==="~/"||rawPrefix==="/"||isAtPrefix&&rawPrefix==="")rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join(this.basePath,expandedPrefix),searchPrefix="";else if(rawPrefix.endsWith("/"))rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join(this.basePath,expandedPrefix),searchPrefix="";else{let dir=dirname(
303
- expandedPrefix),file=basename(expandedPrefix);rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=dir:searchDir=join(this.basePath,dir),searchPrefix=file}let entries=readdirSync(searchDir,{withFileTypes:!0}),suggestions=[];for(let entry of entries){if(!entry.name.toLowerCase().startsWith(searchPrefix.toLowerCase()))continue;let isDirectory=entry.isDirectory();if(!isDirectory&&entry.isSymbolicLink())try{let fullPath=join(searchDir,entry.name);isDirectory=statSync(fullPath).isDirectory()}catch{}
304
- let relativePath,name=entry.name,displayPrefix=rawPrefix;if(displayPrefix.endsWith("/"))relativePath=displayPrefix+name;else if(displayPrefix.includes("/")||displayPrefix.includes("\\"))if(displayPrefix.startsWith("~/")){let homeRelativeDir=displayPrefix.slice(2),dir=dirname(homeRelativeDir);relativePath=`~/${dir==="."?name:join(dir,name)}`}else if(displayPrefix.startsWith("/")){let dir=dirname(displayPrefix);dir==="/"?relativePath=`/${name}`:relativePath=`${dir}/${name}`}else relativePath=join(
305
- dirname(displayPrefix),name),displayPrefix.startsWith("./")&&!relativePath.startsWith("./")&&(relativePath=`./${relativePath}`);else displayPrefix.startsWith("~")?relativePath=`~/${name}`:relativePath=name;relativePath=toDisplayPath(relativePath);let pathValue=isDirectory?`${relativePath}/`:relativePath,value=buildCompletionValue(pathValue,{isDirectory,isAtPrefix,isQuotedPrefix});suggestions.push({value,label:name+(isDirectory?"/":"")})}return suggestions.sort((a3,b)=>{let aIsDir=a3.label.endsWith(
306
- "/"),bIsDir=b.label.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a3.label.localeCompare(b.label)}),suggestions}catch{return[]}}scoreEntry(filePath,query,isDirectory){let lowerFileName=basename(filePath).toLowerCase(),lowerQuery=query.toLowerCase(),score=0;return lowerFileName===lowerQuery?score=100:lowerFileName.startsWith(lowerQuery)?score=80:lowerFileName.includes(lowerQuery)?score=50:filePath.toLowerCase().includes(lowerQuery)&&(score=30),isDirectory&&score>0&&(score+=10),score}async getBaseDirSuggestions(baseDir,query,signal){
307
- return!this.fdPath||signal.aborted?[]:await walkDirectoryWithFd(baseDir,this.fdPath,query,100,signal,1)}async getFuzzyFileSuggestions(query,options){if(!this.fdPath||options.signal.aborted)return[];try{let scopedQuery=this.resolveScopedFuzzyQuery(query),fdBaseDir=scopedQuery?.baseDir??this.basePath,fdQuery=scopedQuery?.query??query,[baseDirEntries,recursiveEntries]=await Promise.all([this.getBaseDirSuggestions(fdBaseDir,fdQuery,options.signal),walkDirectoryWithFd(fdBaseDir,this.fdPath,fdQuery,100,
308
- options.signal)]),seenPaths=new Set(baseDirEntries.map(entry=>entry.path)),entries=[...baseDirEntries,...recursiveEntries.filter(entry=>seenPaths.has(entry.path)?!1:(seenPaths.add(entry.path),!0))];if(options.signal.aborted)return[];let scoredEntries=entries.map(entry=>({...entry,score:fdQuery?this.scoreEntry(entry.path,fdQuery,entry.isDirectory):1})).filter(entry=>entry.score>0);scoredEntries.sort((a3,b)=>{let scoreDiff=b.score-a3.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(
309
- a3.path).split("/").filter(Boolean).length,bDepth=toDisplayPath(b.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a3.path.length-b.path.length;return lengthDiff!==0?lengthDiff:a3.path.localeCompare(b.path)});let topEntries=scoredEntries.slice(0,20),suggestions=[];for(let{path:entryPath,isDirectory}of topEntries){let pathWithoutSlash=isDirectory?entryPath.slice(0,-1):entryPath,displayPath=scopedQuery?this.scopedPathForDisplay(scopedQuery.
310
- displayBase,pathWithoutSlash):pathWithoutSlash,entryName=basename(pathWithoutSlash),completionPath=isDirectory?`${displayPath}/`:displayPath,value=buildCompletionValue(completionPath,{isDirectory,isAtPrefix:!0,isQuotedPrefix:options.isQuotedPrefix});suggestions.push({value,label:entryName+(isDirectory?"/":""),description:displayPath})}return suggestions}catch{return[]}}shouldTriggerFileCompletion(lines,cursorLine,cursorCol){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol);return!(textBeforeCursor.
311
- trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};import{performance as performance2}from"node:perf_hooks";var generation=0;function renderedMarkdownGeneration(){return generation}function invalidateRenderedMarkdown(){generation++}function hexToRgb(hex){let normalized=hex.startsWith("#")?hex.slice(1):hex,r=parseInt(normalized.slice(0,2),16),g=parseInt(normalized.slice(2,4),16),b=parseInt(normalized.slice(4,6),16);return{r,g,b}}function parseOscHexChannel(channel){if(!/^[0-9a-f]+$/i.test(channel))return;let max=16**channel.length-1;if(!(max<=0))return Math.round(parseInt(channel,16)/max*255)}var OSC_COLOR_RESPONSE_PATTERN=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,COLOR_SCHEME_REPORT_PATTERN=/^(?:\x1b\[\?997;(1|2)n)+$/;
283
+ trim())return items;let tokens=query.trim().split(/[\s/]+/).filter(t=>t.length>0);if(tokens.length===0)return items;let results=[];for(let item of items){let text=getText(item),totalScore=0,allMatch=!0;for(let token of tokens){let match=fuzzyMatch(token,text);if(match.matches)totalScore+=match.score;else{allMatch=!1;break}}allMatch&&results.push({item,totalScore})}return results.sort((a3,b)=>a3.totalScore-b.totalScore),results.map(r=>r.item)}var PATH_DELIMITERS=new Set([" "," ",'"',"'","="]),tokenStartRegex=new RegExp(`${autocompleteBoundaryRegex.source}$`,"u"),PATH_WRAPPERS={"(":")","[":"]","{":"}","<":">","`":"`"};function toDisplayPath(value){return value.replace(/\\/g,"/")}function escapeRegex(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildFdPathQuery(query){let normalized=toDisplayPath(query);if(!normalized.includes("/"))return escapeRegex(normalized);let hasTrailingSeparator=normalized.endsWith("/"),trimmed=normalized.
284
+ replace(/^\/+|\/+$/g,"");if(!trimmed)return normalized;let separatorPattern="[\\\\/]",pattern=trimmed.split("/").filter(Boolean).map(segment=>escapeRegex(segment)).join(separatorPattern);return hasTrailingSeparator&&(pattern+=separatorPattern),pattern}function findLastDelimiter(text){let lastDelimiter=-1,index=0;for(let character of text)index+=character.length,(PATH_DELIMITERS.has(character)||autocompleteSeparatorRegex.test(character))&&(lastDelimiter=index-1);return lastDelimiter}function stripLeadingWrappers(token){
285
+ let result=token;for(;result.length>0;){let closer=PATH_WRAPPERS[result[0]];if(!closer||result.includes(closer,1))break;result=result.slice(1)}return result}function findUnclosedQuoteStart(text){let inQuotes=!1,quoteStart=-1;for(let i=0;i<text.length;i+=1)text[i]==='"'&&(inQuotes=!inQuotes,inQuotes&&(quoteStart=i));return inQuotes?quoteStart:null}function isTokenStart(text,index){let start=index;for(;start>0&&PATH_WRAPPERS[text[start-1]];)start-=1;return PATH_DELIMITERS.has(text[start-1]??"")||tokenStartRegex.
286
+ test(text.slice(0,start))}function extractQuotedPrefix(text){let quoteStart=findUnclosedQuoteStart(text);return quoteStart===null?null:quoteStart>0&&text[quoteStart-1]==="@"?isTokenStart(text,quoteStart-1)?text.slice(quoteStart-1):null:isTokenStart(text,quoteStart)?text.slice(quoteStart):null}function parsePathPrefix(prefix){return prefix.startsWith('@"')?{rawPrefix:prefix.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:prefix.startsWith('"')?{rawPrefix:prefix.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:
287
+ prefix.startsWith("@")?{rawPrefix:prefix.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:prefix,isAtPrefix:!1,isQuotedPrefix:!1}}function buildCompletionValue(path5,options){let needsQuotes=options.isQuotedPrefix||autocompleteSeparatorRegex.test(path5),prefix=options.isAtPrefix?"@":"";return needsQuotes?`${`${prefix}"`}${path5}"`:`${prefix}${path5}`}async function walkDirectoryWithFd(baseDir,fdPath,query,maxResults,signal,maxDepth){return(await runFdWalk(baseDir,fdPath,query,maxResults,signal,
288
+ maxDepth))?.entries??[]}function fdWalkArgs(baseDir,query,maxResults,maxDepth){let args=["--base-directory",baseDir,"--max-results",String(maxResults),"--type","f","--type","d","--follow","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];return maxDepth!==void 0&&args.push("--max-depth",String(maxDepth)),toDisplayPath(query).includes("/")&&args.push("--full-path"),query&&args.push(buildFdPathQuery(query)),args}function parseFdLine(line){let displayLine=toDisplayPath(line),
289
+ hasTrailingSeparator=displayLine.endsWith("/"),normalizedPath=hasTrailingSeparator?displayLine.slice(0,-1):displayLine;if(!(normalizedPath===".git"||normalizedPath.startsWith(".git/")||normalizedPath.includes("/.git/")))return{path:displayLine,isDirectory:hasTrailingSeparator}}function runFd(fdPath,args,signal,onOutput){return new Promise(resolve=>{if(signal?.aborted){resolve(!1);return}let child=spawn(fdPath,args,{stdio:["ignore","pipe","pipe"]}),resolved=!1,finish=ok=>{resolved||(resolved=!0,signal?.
290
+ removeEventListener("abort",onAbort),resolve(ok))},onAbort=()=>{child.exitCode===null&&child.kill("SIGKILL")};signal?.addEventListener("abort",onAbort,{once:!0}),child.stdout.setEncoding("utf-8"),child.stdout.on("data",onOutput),child.on("error",()=>{finish(!1)}),child.on("close",code=>{finish(!signal?.aborted&&code===0)})})}async function runFdWalk(baseDir,fdPath,query,maxResults,signal,maxDepth){let stdout="";if(!await runFd(fdPath,fdWalkArgs(baseDir,query,maxResults,maxDepth),signal,chunk=>{stdout+=
291
+ chunk}))return;if(!stdout)return{entries:[],lineCount:0};let lines=stdout.trim().split(`
292
+ `).filter(Boolean),results=[];for(let line of lines){let entry=parseFdLine(line);entry&&results.push(entry)}return{entries:results,lineCount:lines.length}}async function runFdListing(baseDir,fdPath,maxEntries,signal){let entries=[],lineCount=0,partial="",ok=await runFd(fdPath,fdWalkArgs(baseDir,"",maxEntries+1),signal,chunk=>{let lines=(partial+chunk).split(`
293
+ `);partial=lines.pop();for(let line of lines){if(!line)continue;lineCount++;let entry=parseFdLine(line);entry&&entries.push(indexFdEntry(entry))}});if(partial){lineCount++;let entry=parseFdLine(partial);entry&&entries.push(indexFdEntry(entry))}return ok&&lineCount<=maxEntries?entries:void 0}function indexFdEntry(entry){let path5=entry.isDirectory?entry.path.slice(0,-1):entry.path,slash=path5.lastIndexOf("/"),name=path5.slice(slash+1);return{path:entry.path,isDirectory:entry.isDirectory,name,topLevel:slash===
294
+ -1}}function isPlainFdQuery(query){return!query.startsWith("-")&&!/[\\/+*?()|[\]{}^$\x00-\x1f\x7f\uD800-\uDFFF]/.test(query)}function createFdNameMatcher(query){if(query==="")return()=>!0;let regex=new RegExp(escapeRegex(query),new RegExp("\\p{Uppercase}","u").test(query)?"su":"isu");return entry=>regex.test(entry.name)}function selectFdResults(matches,maxResults){let baseDirEntries=[],recursiveEntries=[];for(let entry of matches)if(recursiveEntries.length<maxResults&&recursiveEntries.push(entry),
295
+ entry.topLevel&&baseDirEntries.length<maxResults&&baseDirEntries.push(entry),recursiveEntries.length>=maxResults&&baseDirEntries.length>=maxResults)break;return{baseDirEntries,recursiveEntries}}var FD_MAX_RESULTS=100,FD_INDEX_MAX_ENTRIES=1e5,FD_INDEX_STALE_MS=3e3,FD_INDEX_RETRY_MS=6e5,FD_INDEX_MAX_FOLDERS=8,FdFolderIndex=class{fdPath;baseDir;generation=0;sessionGeneration=0;listing;narrowed;building;unusableUntil=0;constructor(fdPath,baseDir){this.fdPath=fdPath,this.baseDir=baseDir}startSession(){
296
+ if(Date.now()<this.unusableUntil){this.sessionGeneration=++this.generation;return}this.sessionGeneration=this.build()}cancelListing(){this.building?.abort.abort(),this.building=void 0}readyListFor(query){let now=Date.now(),narrowed=this.narrowed;if(narrowed&&narrowed.generation>=this.sessionGeneration&&query.startsWith(narrowed.query)&&(narrowed.fromListing?narrowed.generation===this.listing?.generation:now-narrowed.walkedAt<=FD_INDEX_STALE_MS))return narrowed.fromListing&&this.refreshIfStale(narrowed,
297
+ now),narrowed;if(this.listing&&this.listing.generation>=this.sessionGeneration)return this.refreshIfStale(this.listing,now),this.listing}pendingListing(){return this.building&&this.building.generation>=this.sessionGeneration?this.building.promise:void 0}setNarrowed(list){this.narrowed=list}setCompleteResult(query,entries,walkedAt){this.narrowed={query,entries:entries.map(indexFdEntry),generation:this.sessionGeneration,walkedAt,fromListing:!1}}refreshIfStale(list,now){now-list.walkedAt>FD_INDEX_STALE_MS&&
298
+ !this.building&&now>=this.unusableUntil&&this.build()}build(){this.cancelListing();let generation2=++this.generation,walkedAt=Date.now(),abort=new AbortController,promise=runFdListing(this.baseDir,this.fdPath,FD_INDEX_MAX_ENTRIES,abort.signal).catch(()=>{}).then(entries=>{if(this.building?.generation===generation2&&(this.building=void 0),abort.signal.aborted)return;if(!entries){this.unusableUntil=Date.now()+FD_INDEX_RETRY_MS;return}let list={query:"",entries,generation:generation2,walkedAt,fromListing:!0};
299
+ return(!this.listing||this.listing.generation<generation2)&&(this.listing=list),list});return this.building={generation:generation2,promise,abort},generation2}},CombinedAutocompleteProvider=class{commands;basePath;fdPath;fdIndexes=new Map;fdSessionKey;fdSessionIndex;constructor(commands=[],basePath,fdPath=null){this.commands=commands,this.basePath=basePath,this.fdPath=fdPath}async getSuggestions(lines,cursorLine,cursorCol,options){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol),atPrefix=this.
300
+ extractAtPrefix(textBeforeCursor);if(atPrefix){let{rawPrefix,isQuotedPrefix}=parsePathPrefix(atPrefix),suggestions2=await this.getFuzzyFileSuggestions(rawPrefix,{isQuotedPrefix,signal:options.signal,tokenKey:`${cursorLine}\0${textBeforeCursor.slice(0,textBeforeCursor.length-atPrefix.length)}`});return suggestions2.length===0?null:{items:suggestions2,prefix:atPrefix}}let commandText=textBeforeCursor.trimStart();if(!options.force&&commandText.startsWith("/")){let spaceIndex=commandText.indexOf(" ");
301
+ if(spaceIndex===-1){let prefix=commandText.slice(1),commandItems=this.commands.map(cmd=>{let name="name"in cmd?cmd.name:cmd.value,hint="argumentHint"in cmd&&cmd.argumentHint?cmd.argumentHint:void 0,desc=cmd.description??"",fullDesc=hint?desc?`${hint} \u2014 ${desc}`:hint:desc;return{name,label:name,description:fullDesc||void 0}}),bareNameMatches=fuzzyFilter(commandItems,prefix,item=>item.name.startsWith("skill:")?item.name.slice(6):item.name),bareNameMatchSet=new Set(bareNameMatches),fullNameOnlyMatches=fuzzyFilter(
302
+ commandItems.filter(item=>item.name.startsWith("skill:")&&!bareNameMatchSet.has(item)),prefix,item=>item.name),filtered=[...bareNameMatches,...fullNameOnlyMatches].map(item=>({value:item.name,label:item.label,...item.description&&{description:item.description}}));return filtered.length===0?null:{items:filtered,prefix:commandText}}let commandName=commandText.slice(1,spaceIndex),argumentText=commandText.slice(spaceIndex+1),command=this.commands.find(cmd=>("name"in cmd?cmd.name:cmd.value)===commandName);
303
+ if(!command||!("getArgumentCompletions"in command)||!command.getArgumentCompletions)return null;let argumentSuggestions=await command.getArgumentCompletions(argumentText);return!Array.isArray(argumentSuggestions)||argumentSuggestions.length===0?null:{items:argumentSuggestions,prefix:argumentText}}let pathMatch=this.extractPathPrefix(textBeforeCursor,options.force??!1);if(pathMatch===null)return null;let suggestions=this.getFileSuggestions(pathMatch);return suggestions.length===0?null:{items:suggestions,
304
+ prefix:pathMatch}}applyCompletion(lines,cursorLine,cursorCol,item,prefix){let currentLine=lines[cursorLine]||"",beforePrefix=currentLine.slice(0,cursorCol-prefix.length),afterCursor=currentLine.slice(cursorCol),isQuotedPrefix=prefix.startsWith('"')||prefix.startsWith('@"'),hasLeadingQuoteAfterCursor=afterCursor.startsWith('"'),hasTrailingQuoteInItem=item.value.endsWith('"'),adjustedAfterCursor=isQuotedPrefix&&hasTrailingQuoteInItem&&hasLeadingQuoteAfterCursor?afterCursor.slice(1):afterCursor;if(prefix.
305
+ startsWith("/")&&beforePrefix.trim()===""&&!prefix.slice(1).includes("/")){let newLine2=`${beforePrefix}/${item.value} ${adjustedAfterCursor}`,newLines2=[...lines];return newLines2[cursorLine]=newLine2,{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+item.value.length+2}}if(prefix.startsWith("@")){let isDirectory2=item.label.endsWith("/"),suffix=isDirectory2?"":" ",newLine2=`${beforePrefix+item.value}${suffix}${adjustedAfterCursor}`,newLines2=[...lines];newLines2[cursorLine]=newLine2;let hasTrailingQuote2=item.
306
+ value.endsWith('"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2+suffix.length}}let textBeforeCursor=currentLine.slice(0,cursorCol);if(textBeforeCursor.includes("/")&&textBeforeCursor.includes(" ")){let newLine2=beforePrefix+item.value+adjustedAfterCursor,newLines2=[...lines];newLines2[cursorLine]=newLine2;let isDirectory2=item.label.endsWith("/"),hasTrailingQuote2=item.value.endsWith(
307
+ '"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2}}let newLine=beforePrefix+item.value+adjustedAfterCursor,newLines=[...lines];newLines[cursorLine]=newLine;let isDirectory=item.label.endsWith("/"),hasTrailingQuote=item.value.endsWith('"'),cursorOffset=isDirectory&&hasTrailingQuote?item.value.length-1:item.value.length;return{lines:newLines,cursorLine,cursorCol:beforePrefix.length+
308
+ cursorOffset}}extractAtPrefix(text){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix?.startsWith('@"'))return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),token=stripLeadingWrappers(lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return token.startsWith("@")?token:null}extractPathPrefix(text,forceExtract=!1){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix)return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),pathPrefix=stripLeadingWrappers(
309
+ lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return forceExtract||pathPrefix.includes("/")||pathPrefix.startsWith(".")||pathPrefix.startsWith("~/")||pathPrefix===""&&text!==""&&tokenStartRegex.test(text)?pathPrefix:null}expandHomePath(path5){if(path5.startsWith("~/")){let expandedPath=join(homedir(),path5.slice(2));return path5.endsWith("/")&&!expandedPath.endsWith("/")?`${expandedPath}/`:expandedPath}else if(path5==="~")return homedir();return path5}resolveScopedFuzzyQuery(rawQuery){
310
+ let normalizedQuery=toDisplayPath(rawQuery),slashIndex=normalizedQuery.lastIndexOf("/");if(slashIndex===-1)return null;let displayBase=normalizedQuery.slice(0,slashIndex+1),query=normalizedQuery.slice(slashIndex+1),baseDir;displayBase.startsWith("~/")?baseDir=this.expandHomePath(displayBase):displayBase.startsWith("/")?baseDir=displayBase:baseDir=join(this.basePath,displayBase);try{if(!statSync(baseDir).isDirectory())return null}catch{return null}return{baseDir,query,displayBase}}scopedPathForDisplay(displayBase,relativePath){
311
+ let normalizedRelativePath=toDisplayPath(relativePath);return displayBase==="/"?`/${normalizedRelativePath}`:`${toDisplayPath(displayBase)}${normalizedRelativePath}`}getFileSuggestions(prefix){try{let searchDir,searchPrefix,{rawPrefix,isAtPrefix,isQuotedPrefix}=parsePathPrefix(prefix),expandedPrefix=rawPrefix;if(expandedPrefix.startsWith("~")&&(expandedPrefix=this.expandHomePath(expandedPrefix)),rawPrefix===""||rawPrefix==="./"||rawPrefix==="../"||rawPrefix==="~"||rawPrefix==="~/"||rawPrefix==="\
312
+ /"||isAtPrefix&&rawPrefix==="")rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join(this.basePath,expandedPrefix),searchPrefix="";else if(rawPrefix.endsWith("/"))rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join(this.basePath,expandedPrefix),searchPrefix="";else{let dir=dirname(expandedPrefix),file=basename(expandedPrefix);rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=dir:searchDir=
313
+ join(this.basePath,dir),searchPrefix=file}let entries=readdirSync(searchDir,{withFileTypes:!0}),suggestions=[];for(let entry of entries){if(!entry.name.toLowerCase().startsWith(searchPrefix.toLowerCase()))continue;let isDirectory=entry.isDirectory();if(!isDirectory&&entry.isSymbolicLink())try{let fullPath=join(searchDir,entry.name);isDirectory=statSync(fullPath).isDirectory()}catch{}let relativePath,name=entry.name,displayPrefix=rawPrefix;if(displayPrefix.endsWith("/"))relativePath=displayPrefix+
314
+ name;else if(displayPrefix.includes("/")||displayPrefix.includes("\\"))if(displayPrefix.startsWith("~/")){let homeRelativeDir=displayPrefix.slice(2),dir=dirname(homeRelativeDir);relativePath=`~/${dir==="."?name:join(dir,name)}`}else if(displayPrefix.startsWith("/")){let dir=dirname(displayPrefix);dir==="/"?relativePath=`/${name}`:relativePath=`${dir}/${name}`}else relativePath=join(dirname(displayPrefix),name),displayPrefix.startsWith("./")&&!relativePath.startsWith("./")&&(relativePath=`./${relativePath}`);else
315
+ displayPrefix.startsWith("~")?relativePath=`~/${name}`:relativePath=name;relativePath=toDisplayPath(relativePath);let pathValue=isDirectory?`${relativePath}/`:relativePath,value=buildCompletionValue(pathValue,{isDirectory,isAtPrefix,isQuotedPrefix});suggestions.push({value,label:name+(isDirectory?"/":"")})}return suggestions.sort((a3,b)=>{let aIsDir=a3.label.endsWith("/"),bIsDir=b.label.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a3.label.localeCompare(b.label)}),suggestions}catch{
316
+ return[]}}scoreEntry(filePath,query,isDirectory){let lowerFileName=basename(filePath).toLowerCase(),lowerQuery=query.toLowerCase(),score=0;return lowerFileName===lowerQuery?score=100:lowerFileName.startsWith(lowerQuery)?score=80:lowerFileName.includes(lowerQuery)?score=50:filePath.toLowerCase().includes(lowerQuery)&&(score=30),isDirectory&&score>0&&(score+=10),score}async getBaseDirSuggestions(baseDir,query,signal){return!this.fdPath||signal.aborted?[]:await walkDirectoryWithFd(baseDir,this.fdPath,
317
+ query,100,signal,1)}async getFuzzyFileSuggestions(query,options){if(!this.fdPath||options.signal.aborted)return[];try{let scopedQuery=this.resolveScopedFuzzyQuery(query),fdBaseDir=scopedQuery?.baseDir??this.basePath,fdQuery=scopedQuery?.query??query,results=isPlainFdQuery(fdQuery)?await this.getIndexedFdResults(fdBaseDir,fdQuery,options.tokenKey,options.signal):await this.runFdForQuery(fdBaseDir,fdQuery,options.signal);return options.signal.aborted?[]:this.rankFdResults(results.baseDirEntries,results.
318
+ recursiveEntries,fdQuery,scopedQuery,options)}catch{return[]}}async runFdForQuery(fdBaseDir,fdQuery,signal){let[baseDirEntries,recursive]=await Promise.all([this.getBaseDirSuggestions(fdBaseDir,fdQuery,signal),this.fdPath?runFdWalk(fdBaseDir,this.fdPath,fdQuery,FD_MAX_RESULTS,signal):void 0]);return{baseDirEntries,recursiveEntries:recursive?.entries??[],recursiveLineCount:recursive?.lineCount}}async getIndexedFdResults(fdBaseDir,fdQuery,tokenKey,signal){let index=this.fdIndexes.get(fdBaseDir);if(index)
319
+ this.fdIndexes.delete(fdBaseDir);else if(index=new FdFolderIndex(this.fdPath,fdBaseDir),this.fdIndexes.size>=FD_INDEX_MAX_FOLDERS){let oldest=this.fdIndexes.keys().next().value;this.fdIndexes.get(oldest)?.cancelListing(),this.fdIndexes.delete(oldest)}this.fdIndexes.set(fdBaseDir,index);let sessionKey=`${fdBaseDir}\0${tokenKey}`;sessionKey!==this.fdSessionKey&&(this.fdSessionIndex!==index&&this.fdSessionIndex?.cancelListing(),this.fdSessionKey=sessionKey,this.fdSessionIndex=index,index.startSession());
320
+ let ready=index.readyListFor(fdQuery);if(ready)return this.filterFdList(index,ready,fdQuery);let fdAbort=new AbortController,abortFd=()=>fdAbort.abort();signal.addEventListener("abort",abortFd,{once:!0});try{let walkedAt=Date.now(),viaFd=this.runFdForQuery(fdBaseDir,fdQuery,fdAbort.signal).then(results2=>({results:results2})),viaListing=index.pendingListing()?.then(list=>list?{list}:viaFd),first=await(viaListing?Promise.race([viaListing,viaFd]):viaFd);if(signal.aborted)return{baseDirEntries:[],recursiveEntries:[]};
321
+ if("list"in first)return fdAbort.abort(),this.filterFdList(index,first.list,fdQuery);let{results}=first;return results.recursiveLineCount!==void 0&&results.recursiveLineCount<FD_MAX_RESULTS&&index.setCompleteResult(fdQuery,results.recursiveEntries,walkedAt),results}finally{signal.removeEventListener("abort",abortFd)}}filterFdList(index,list,fdQuery){let matches=list.query===fdQuery?list.entries:list.entries.filter(createFdNameMatcher(fdQuery));return index.setNarrowed({...list,query:fdQuery,entries:matches}),
322
+ selectFdResults(matches,FD_MAX_RESULTS)}rankFdResults(baseDirEntries,recursiveEntries,fdQuery,scopedQuery,options){let seenPaths=new Set(baseDirEntries.map(entry=>entry.path)),scoredEntries=[...baseDirEntries,...recursiveEntries.filter(entry=>seenPaths.has(entry.path)?!1:(seenPaths.add(entry.path),!0))].map(entry=>({path:entry.path,isDirectory:entry.isDirectory,score:fdQuery?this.scoreEntry(entry.path,fdQuery,entry.isDirectory):1})).filter(entry=>entry.score>0);scoredEntries.sort((a3,b)=>{let scoreDiff=b.
323
+ score-a3.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(a3.path).split("/").filter(Boolean).length,bDepth=toDisplayPath(b.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a3.path.length-b.path.length;return lengthDiff!==0?lengthDiff:a3.path.localeCompare(b.path)});let topEntries=scoredEntries.slice(0,20),suggestions=[];for(let{path:entryPath,isDirectory}of topEntries){let pathWithoutSlash=isDirectory?entryPath.slice(
324
+ 0,-1):entryPath,displayPath=scopedQuery?this.scopedPathForDisplay(scopedQuery.displayBase,pathWithoutSlash):pathWithoutSlash,entryName=basename(pathWithoutSlash),completionPath=isDirectory?`${displayPath}/`:displayPath,value=buildCompletionValue(completionPath,{isDirectory,isAtPrefix:!0,isQuotedPrefix:options.isQuotedPrefix});suggestions.push({value,label:entryName+(isDirectory?"/":""),description:displayPath})}return suggestions}shouldTriggerFileCompletion(lines,cursorLine,cursorCol){let textBeforeCursor=(lines[cursorLine]||
325
+ "").slice(0,cursorCol);return!(textBeforeCursor.trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};import{performance as performance2}from"node:perf_hooks";var generation=0;function renderedMarkdownGeneration(){return generation}function invalidateRenderedMarkdown(){generation++}function hexToRgb(hex){let normalized=hex.startsWith("#")?hex.slice(1):hex,r=parseInt(normalized.slice(0,2),16),g=parseInt(normalized.slice(2,4),16),b=parseInt(normalized.slice(4,6),16);return{r,g,b}}function parseOscHexChannel(channel){if(!/^[0-9a-f]+$/i.test(channel))return;let max=16**channel.length-1;if(!(max<=0))return Math.round(parseInt(channel,16)/max*255)}var OSC_COLOR_RESPONSE_PATTERN=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,COLOR_SCHEME_REPORT_PATTERN=/^(?:\x1b\[\?997;(1|2)n)+$/;
312
326
  function parseOscColorResponse(data){let match=data.match(OSC_COLOR_RESPONSE_PATTERN);return match?{target:match[1]==="10"?"foreground":match[1]==="11"?"background":Number.parseInt(match[2],10),rgb:parseOscColorValue(match[3])}:void 0}function parseOscColorValue(rawValue){let value=rawValue.trim();if(value.startsWith("#")){let hex=value.slice(1);if(/^[0-9a-f]{6}$/i.test(hex))return hexToRgb(value);if(/^[0-9a-f]{12}$/i.test(hex)){let r2=parseOscHexChannel(hex.slice(0,4)),g2=parseOscHexChannel(hex.
313
327
  slice(4,8)),b2=parseOscHexChannel(hex.slice(8,12));return r2!==void 0&&g2!==void 0&&b2!==void 0?{r:r2,g:g2,b:b2}:void 0}return}let rgbValue=value.replace(/^rgba?:/i,""),[red,green,blue]=rgbValue.split("/");if(red===void 0||green===void 0||blue===void 0)return;let r=parseOscHexChannel(red),g=parseOscHexChannel(green),b=parseOscHexChannel(blue);return r!==void 0&&g!==void 0&&b!==void 0?{r,g,b}:void 0}function parseTerminalColorSchemeReport(data){let match=data.match(COLOR_SCHEME_REPORT_PATTERN);if(match)
314
328
  return match[1]==="2"?"light":"dark"}import{execFile}from"node:child_process";import{homedir as homedir2}from"node:os";import{isAbsolute}from"node:path";import{pathToFileURL}from"node:url";var cachedCapabilities=null,cachedBeforeTmuxAnswer=!1,capabilityOverrides={},capabilityChangeListeners=new Set,cellDimensions={widthPx:9,heightPx:18};function getCellDimensions(){return cellDimensions}function setCellDimensions(dims){cellDimensions=dims}var tmuxHyperlinks,tmuxProbeStarted=!1;function probeTmuxHyperlinks(){return tmuxHyperlinks!==
315
329
  void 0?tmuxHyperlinks:(tmuxProbeStarted||(tmuxProbeStarted=!0,startTmuxProbe()),!1)}function startTmuxProbe(){let deadline=performance.now()+250,answered=!1,answer=forwards=>{if(!answered&&(answered=!0,tmuxHyperlinks=forwards,!(!forwards||!cachedBeforeTmuxAnswer))){cachedCapabilities=null,cachedBeforeTmuxAnswer=!1;for(let listener of capabilityChangeListeners)listener()}};try{let child=execFile("tmux",["display-message","-p","#{client_termfeatures}"],{encoding:"utf8"},(error,stdout)=>{clearTimeout(
316
330
  timeout),answer(!error&&performance.now()<deadline&&stdout.split(",").map(feature=>feature.trim()).includes("hyperlinks"))}),timeout=setTimeout(()=>{answer(!1),child.kill()},Math.max(0,deadline-performance.now()));timeout.unref(),child.unref(),child.stdin?.end(),child.stdout?.unref(),child.stderr?.unref()}catch{answer(!1)}}function onCapabilitiesChange(listener){return capabilityChangeListeners.add(listener),()=>capabilityChangeListeners.delete(listener)}function detectCapabilitiesFromEnvironment(tmuxForwardsHyperlink){
317
331
  let termProgram=process.env.TERM_PROGRAM?.toLowerCase()||"",terminalEmulator=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",term=process.env.TERM?.toLowerCase()||"",colorTerm=process.env.COLORTERM?.toLowerCase()||"",hasTrueColorHint=colorTerm==="truecolor"||colorTerm==="24bit"||term.endsWith("-direct"),isWindowsConsole=process.platform==="win32";return process.env.TMUX||term.startsWith("tmux")?{images:null,trueColor:hasTrueColorHint,hyperlinks:tmuxForwardsHyperlink()}:term.startsWith("screen")?
318
- {images:null,trueColor:hasTrueColorHint,hyperlinks:!1}:termProgram==="herdr"?{images:"kitty",trueColor:hasTrueColorHint,hyperlinks:!0}:process.env.KITTY_WINDOW_ID||termProgram==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="ghostty"||term.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||termProgram==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="warpterminal"||process.env.WARP_SESSION_ID||
319
- process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||termProgram==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:termProgram==="alacritty"||termProgram==="vscode"||termProgram==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:terminalEmulator==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:isWindowsConsole?{images:null,trueColor:!0,hyperlinks:!1}:{
320
- images:null,trueColor:hasTrueColorHint,hyperlinks:!1}}function parseBooleanCapabilityOverride(value){return value==="1"?!0:value==="0"?!1:void 0}function detectCapabilities(tmuxForwardsHyperlink=probeTmuxHyperlinks){let hyperlinks=parseBooleanCapabilityOverride(process.env.HUMAIN_TERMINAL_HYPERLINKS??process.env.PI_HYPERLINKS),detected=detectCapabilitiesFromEnvironment(hyperlinks===void 0?tmuxForwardsHyperlink:()=>hyperlinks),imageProtocol=(process.env.HUMAIN_TERMINAL_IMAGE_PROTOCOL??process.env.
321
- PI_IMAGE_PROTOCOL)?.toLowerCase(),images=imageProtocol==="kitty"||imageProtocol==="iterm2"?imageProtocol:imageProtocol==="none"||imageProtocol==="0"?null:void 0,trueColor=parseBooleanCapabilityOverride(process.env.HUMAIN_TERMINAL_TRUE_COLOR??process.env.PI_TRUE_COLOR);return{...detected,...images!==void 0?{images}:{},...trueColor!==void 0?{trueColor}:{},...hyperlinks!==void 0?{hyperlinks}:{}}}function getCapabilities(){if(!cachedCapabilities){let hyperlinks=capabilityOverrides.hyperlinks,probePending=!1;
322
- cachedCapabilities={...detectCapabilities(hyperlinks===void 0?()=>{let forwards=probeTmuxHyperlinks();return probePending=tmuxHyperlinks===void 0,forwards}:()=>hyperlinks),...capabilityOverrides},cachedBeforeTmuxAnswer=probePending}return cachedCapabilities}function getTerminalColorMode(capabilities=getCapabilities()){return capabilities.trueColor?"truecolor":"256color"}function resetCapabilitiesCache(){cachedCapabilities=null,cachedBeforeTmuxAnswer=!1,tmuxHyperlinks=void 0,tmuxProbeStarted=!1}function setCapabilityOverrides(overrides){
323
- capabilityOverrides.images===overrides.images&&capabilityOverrides.trueColor===overrides.trueColor&&capabilityOverrides.hyperlinks===overrides.hyperlinks||(capabilityOverrides={...overrides},cachedCapabilities=null,cachedBeforeTmuxAnswer=!1)}function setCapabilities(caps){cachedCapabilities=caps,cachedBeforeTmuxAnswer=!1}var KITTY_PREFIX="\x1B_G",ITERM2_PREFIX="\x1B]1337;File=";function isImageLine(line){return line.startsWith(KITTY_PREFIX)||line.startsWith(ITERM2_PREFIX)?!0:line.includes(KITTY_PREFIX)||
324
- line.includes(ITERM2_PREFIX)}function allocateImageId(){return Math.floor(Math.random()*4294967294)+1}function encodeKitty(base64Data,options={}){let params=["a=T","f=100","q=2"];if(options.moveCursor===!1&&params.push("C=1"),options.columns&&params.push(`c=${options.columns}`),options.rows&&params.push(`r=${options.rows}`),options.imageId&&params.push(`i=${options.imageId}`),base64Data.length<=4096)return`\x1B_G${params.join(",")};${base64Data}\x1B\\`;let chunks=[],offset=0,isFirst=!0;for(;offset<
325
- base64Data.length;){let chunk=base64Data.slice(offset,offset+4096),isLast=offset+4096>=base64Data.length;isFirst?(chunks.push(`\x1B_G${params.join(",")},m=1;${chunk}\x1B\\`),isFirst=!1):isLast?chunks.push(`\x1B_Gm=0;${chunk}\x1B\\`):chunks.push(`\x1B_Gm=1;${chunk}\x1B\\`),offset+=4096}return chunks.join("")}function deleteKittyImage(imageId){return`\x1B_Ga=d,d=I,i=${imageId},q=2\x1B\\`}function deleteAllKittyImages(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}function deleteAllKittyPlacements(){return"\x1B_Ga\
326
- =d,d=a,q=2\x1B\\"}function encodeITerm2(base64Data,options={}){let params=[`inline=${options.inline!==!1?1:0}`,`size=${Buffer.byteLength(base64Data,"base64")}`];if(options.width!==void 0&&params.push(`width=${options.width}`),options.height!==void 0&&params.push(`height=${options.height}`),options.name){let nameBase64=Buffer.from(options.name).toString("base64");params.push(`name=${nameBase64}`)}return options.preserveAspectRatio===!1&&params.push("preserveAspectRatio=0"),`\x1B]1337;File=${params.
327
- join(";")}:${base64Data}\x07`}var kittyImageMetadata=new Map,kittyTransmissionGeneration=0;function registerKittyImageMetadata(metadata){if(kittyTransmissionGeneration+=1,kittyImageMetadata.delete(metadata.imageId),kittyImageMetadata.set(metadata.imageId,{...metadata,transmissionGeneration:kittyTransmissionGeneration}),kittyImageMetadata.size>1e3){let oldestImageId=kittyImageMetadata.keys().next().value;oldestImageId!==void 0&&kittyImageMetadata.delete(oldestImageId)}}function findKittyControls(line){
328
- let index=line.indexOf("\x1B_G");if(index===-1)return;let end=line.indexOf(";",index+3);if(end!==-1)return{index,controls:line.slice(index+3,end),length:end+1-index}}function getRegisteredKittyImageMetadataFromControls(controls){let imageId=/(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];return imageId===void 0?void 0:kittyImageMetadata.get(Number.parseInt(imageId,10))}function getRegisteredKittyImageMetadata(line){let controls=findKittyControls(line)?.controls;return controls===void 0?void 0:getRegisteredKittyImageMetadataFromControls(
329
- controls)}function getExplicitKittyImageRows(controls){let value=/(?:^|,)r=(\d+)(?:,|$)/.exec(controls)?.[1];if(value===void 0)return;let rows=Number.parseInt(value,10);return rows>0?rows:void 0}function getKittyImageRowsFromControls(controls,fallbackRows){return getExplicitKittyImageRows(controls)??fallbackRows}function getKittyImageMetadata(line){let metadata=getRegisteredKittyImageMetadata(line);if(metadata)return{imageId:metadata.imageId,columns:metadata.columns,rows:metadata.rows,widthPx:metadata.
330
- widthPx,heightPx:metadata.heightPx}}var KITTY_PLACEMENT_CONTROL_KEYS=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function getKittyImagePlacementRows(line){let controls=findKittyControls(line)?.controls;if(controls===void 0)return;let explicitRows=getExplicitKittyImageRows(controls);return explicitRows!==void 0?explicitRows:getRegisteredKittyImageMetadataFromControls(controls)?.rows}function getKittyImagePlacement(line){let match=findKittyControls(line);if(!match)
331
- return;let metadata=getRegisteredKittyImageMetadataFromControls(match.controls);if(!metadata)return;let commandStart=match.index,commandControls=match.controls,transmissionEnd;for(;;){let terminator=line.indexOf("\x1B\\",commandStart+KITTY_PREFIX.length);if(terminator===-1)return;if(transmissionEnd=terminator+2,!/(?:^|,)m=1(?:,|$)/.test(commandControls))break;if(commandStart=transmissionEnd,!line.startsWith(KITTY_PREFIX,commandStart))return;let controlsEnd=line.indexOf(";",commandStart+KITTY_PREFIX.
332
- length);if(controlsEnd===-1)return;commandControls=line.slice(commandStart+KITTY_PREFIX.length,controlsEnd)}let sequence=`\x1B_Ga=p,q=2,${match.controls.split(",").filter(control=>KITTY_PLACEMENT_CONTROL_KEYS.has(control.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:metadata.imageId,transmissionGeneration:metadata.transmissionGeneration,transmissionBytes:transmissionEnd-match.index,estimatedDecodedBytes:metadata.widthPx*metadata.heightPx*4,rows:getKittyImageRowsFromControls(match.controls,
333
- metadata.rows),sequence,replacementLine:`${line.slice(0,match.index)}${sequence}${line.slice(transmissionEnd)}`}}function cropKittyImageLine(line,hiddenRows,visibleRows){let metadata=getKittyImageMetadata(line),match=findKittyControls(line);if(!metadata||!match||hiddenRows<0||hiddenRows>=metadata.rows||visibleRows<=0)return line;let croppedRows=Math.min(visibleRows,metadata.rows-hiddenRows);if(hiddenRows===0&&croppedRows===metadata.rows)return line;let sourceY=Math.floor(metadata.heightPx*hiddenRows/
334
- metadata.rows),sourceEnd=Math.ceil(metadata.heightPx*(hiddenRows+croppedRows)/metadata.rows),sourceHeight=Math.max(1,Math.min(metadata.heightPx,sourceEnd)-sourceY),controls=match.controls.split(",").filter(control=>!/^[yhr]=/.test(control));return controls.push(`y=${sourceY}`,`h=${sourceHeight}`,`r=${croppedRows}`),`${line.slice(0,match.index)}\x1B_G${controls.join(",")};${line.slice(match.index+match.length)}`}function chooseLessDistortedCellCount(upperCount,idealCount){if(upperCount<=1)return upperCount;
335
- let lowerCount=upperCount-1,upperDistortion=Math.max(upperCount/idealCount,idealCount/upperCount);return Math.max(lowerCount/idealCount,idealCount/lowerCount)<upperDistortion?lowerCount:upperCount}function calculateImageCellSize(imageDimensions,maxWidthCells,maxHeightCells,cellDimensions2={widthPx:9,heightPx:18},optimizeAspectRatio=!1){let maxWidth=Math.max(1,Math.floor(maxWidthCells)),maxHeight=maxHeightCells===void 0?void 0:Math.max(1,Math.floor(maxHeightCells)),imageWidth=Math.max(1,imageDimensions.
336
- widthPx),imageHeight=Math.max(1,imageDimensions.heightPx),widthScale=maxWidth*cellDimensions2.widthPx/imageWidth,heightScale=maxHeight===void 0?widthScale:maxHeight*cellDimensions2.heightPx/imageHeight,scale=Math.min(widthScale,heightScale),scaledWidthPx=imageWidth*scale,scaledHeightPx=imageHeight*scale,columns=Math.max(1,Math.min(maxWidth,Math.ceil(scaledWidthPx/cellDimensions2.widthPx))),heightRows=scaledHeightPx/cellDimensions2.heightPx,rows=Math.max(1,Math.ceil(heightRows));if(maxHeight!==void 0&&
337
- (rows=Math.min(maxHeight,rows)),!optimizeAspectRatio)return{columns,rows};if(widthScale<=heightScale){let idealRows=columns*cellDimensions2.widthPx*imageHeight/(imageWidth*cellDimensions2.heightPx);rows=chooseLessDistortedCellCount(rows,idealRows)}else{let idealColumns=rows*cellDimensions2.heightPx*imageWidth/(imageHeight*cellDimensions2.widthPx);columns=chooseLessDistortedCellCount(columns,idealColumns)}return{columns,rows}}function calculateImageRows(imageDimensions,targetWidthCells,cellDimensions2={
332
+ {images:null,trueColor:hasTrueColorHint,hyperlinks:!1}:termProgram==="herdr"?{images:"kitty",trueColor:hasTrueColorHint,hyperlinks:!0}:termProgram==="rex"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.KITTY_WINDOW_ID||termProgram==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="ghostty"||term.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||termProgram==="wezterm"?{images:"kitty",trueColor:!0,
333
+ hyperlinks:!0}:termProgram==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||termProgram==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:termProgram==="alacritty"||termProgram==="vscode"||termProgram==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:terminalEmulator==="jetbrains-jediterm"?{images:null,trueColor:!0,
334
+ hyperlinks:!1}:isWindowsConsole?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}}function parseBooleanCapabilityOverride(value){return value==="1"?!0:value==="0"?!1:void 0}function detectCapabilities(tmuxForwardsHyperlink=probeTmuxHyperlinks){let hyperlinks=parseBooleanCapabilityOverride(process.env.HUMAIN_TERMINAL_HYPERLINKS??process.env.PI_HYPERLINKS),detected=detectCapabilitiesFromEnvironment(hyperlinks===void 0?tmuxForwardsHyperlink:()=>hyperlinks),
335
+ imageProtocol=(process.env.HUMAIN_TERMINAL_IMAGE_PROTOCOL??process.env.PI_IMAGE_PROTOCOL)?.toLowerCase(),images=imageProtocol==="kitty"||imageProtocol==="iterm2"?imageProtocol:imageProtocol==="none"||imageProtocol==="0"?null:void 0,trueColor=parseBooleanCapabilityOverride(process.env.HUMAIN_TERMINAL_TRUE_COLOR??process.env.PI_TRUE_COLOR);return{...detected,...images!==void 0?{images}:{},...trueColor!==void 0?{trueColor}:{},...hyperlinks!==void 0?{hyperlinks}:{}}}function getCapabilities(){if(!cachedCapabilities){
336
+ let hyperlinks=capabilityOverrides.hyperlinks,probePending=!1;cachedCapabilities={...detectCapabilities(hyperlinks===void 0?()=>{let forwards=probeTmuxHyperlinks();return probePending=tmuxHyperlinks===void 0,forwards}:()=>hyperlinks),...capabilityOverrides},cachedBeforeTmuxAnswer=probePending}return cachedCapabilities}function getTerminalColorMode(capabilities=getCapabilities()){return capabilities.trueColor?"truecolor":"256color"}function resetCapabilitiesCache(){cachedCapabilities=null,cachedBeforeTmuxAnswer=
337
+ !1,tmuxHyperlinks=void 0,tmuxProbeStarted=!1}function setCapabilityOverrides(overrides){capabilityOverrides.images===overrides.images&&capabilityOverrides.trueColor===overrides.trueColor&&capabilityOverrides.hyperlinks===overrides.hyperlinks||(capabilityOverrides={...overrides},cachedCapabilities=null,cachedBeforeTmuxAnswer=!1)}function setCapabilities(caps){cachedCapabilities=caps,cachedBeforeTmuxAnswer=!1}var KITTY_PREFIX="\x1B_G",ITERM2_PREFIX="\x1B]1337;File=";function isImageLine(line){return line.
338
+ startsWith(KITTY_PREFIX)||line.startsWith(ITERM2_PREFIX)?!0:line.includes(KITTY_PREFIX)||line.includes(ITERM2_PREFIX)}function allocateImageId(){return Math.floor(Math.random()*4294967294)+1}function encodeKitty(base64Data,options={}){let params=["a=T","f=100","q=2"];if(options.moveCursor===!1&&params.push("C=1"),options.columns&&params.push(`c=${options.columns}`),options.rows&&params.push(`r=${options.rows}`),options.imageId&&params.push(`i=${options.imageId}`),base64Data.length<=4096)return`\x1B\
339
+ _G${params.join(",")};${base64Data}\x1B\\`;let chunks=[],offset=0,isFirst=!0;for(;offset<base64Data.length;){let chunk=base64Data.slice(offset,offset+4096),isLast=offset+4096>=base64Data.length;isFirst?(chunks.push(`\x1B_G${params.join(",")},m=1;${chunk}\x1B\\`),isFirst=!1):isLast?chunks.push(`\x1B_Gm=0;${chunk}\x1B\\`):chunks.push(`\x1B_Gm=1;${chunk}\x1B\\`),offset+=4096}return chunks.join("")}function deleteKittyImage(imageId){return`\x1B_Ga=d,d=I,i=${imageId},q=2\x1B\\`}function deleteAllKittyImages(){
340
+ return"\x1B_Ga=d,d=A,q=2\x1B\\"}function deleteAllKittyPlacements(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function encodeITerm2(base64Data,options={}){let params=[`inline=${options.inline!==!1?1:0}`,`size=${Buffer.byteLength(base64Data,"base64")}`];if(options.width!==void 0&&params.push(`width=${options.width}`),options.height!==void 0&&params.push(`height=${options.height}`),options.name){let nameBase64=Buffer.from(options.name).toString("base64");params.push(`name=${nameBase64}`)}return options.preserveAspectRatio===
341
+ !1&&params.push("preserveAspectRatio=0"),`\x1B]1337;File=${params.join(";")}:${base64Data}\x07`}var kittyImageMetadata=new Map,kittyTransmissionGeneration=0;function registerKittyImageMetadata(metadata){if(kittyTransmissionGeneration+=1,kittyImageMetadata.delete(metadata.imageId),kittyImageMetadata.set(metadata.imageId,{...metadata,transmissionGeneration:kittyTransmissionGeneration}),kittyImageMetadata.size>1e3){let oldestImageId=kittyImageMetadata.keys().next().value;oldestImageId!==void 0&&kittyImageMetadata.
342
+ delete(oldestImageId)}}function findKittyControls(line){let index=line.indexOf("\x1B_G");if(index===-1)return;let end=line.indexOf(";",index+3);if(end!==-1)return{index,controls:line.slice(index+3,end),length:end+1-index}}function getRegisteredKittyImageMetadataFromControls(controls){let imageId=/(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];return imageId===void 0?void 0:kittyImageMetadata.get(Number.parseInt(imageId,10))}function getRegisteredKittyImageMetadata(line){let controls=findKittyControls(
343
+ line)?.controls;return controls===void 0?void 0:getRegisteredKittyImageMetadataFromControls(controls)}function getExplicitKittyImageRows(controls){let value=/(?:^|,)r=(\d+)(?:,|$)/.exec(controls)?.[1];if(value===void 0)return;let rows=Number.parseInt(value,10);return rows>0?rows:void 0}function getKittyImageRowsFromControls(controls,fallbackRows){return getExplicitKittyImageRows(controls)??fallbackRows}function getKittyImageMetadata(line){let metadata=getRegisteredKittyImageMetadata(line);if(metadata)
344
+ return{imageId:metadata.imageId,columns:metadata.columns,rows:metadata.rows,widthPx:metadata.widthPx,heightPx:metadata.heightPx}}var KITTY_PLACEMENT_CONTROL_KEYS=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function getKittyImagePlacementRows(line){let controls=findKittyControls(line)?.controls;if(controls===void 0)return;let explicitRows=getExplicitKittyImageRows(controls);return explicitRows!==void 0?explicitRows:getRegisteredKittyImageMetadataFromControls(controls)?.
345
+ rows}function getKittyImagePlacement(line){let match=findKittyControls(line);if(!match)return;let metadata=getRegisteredKittyImageMetadataFromControls(match.controls);if(!metadata)return;let commandStart=match.index,commandControls=match.controls,transmissionEnd;for(;;){let terminator=line.indexOf("\x1B\\",commandStart+KITTY_PREFIX.length);if(terminator===-1)return;if(transmissionEnd=terminator+2,!/(?:^|,)m=1(?:,|$)/.test(commandControls))break;if(commandStart=transmissionEnd,!line.startsWith(KITTY_PREFIX,
346
+ commandStart))return;let controlsEnd=line.indexOf(";",commandStart+KITTY_PREFIX.length);if(controlsEnd===-1)return;commandControls=line.slice(commandStart+KITTY_PREFIX.length,controlsEnd)}let sequence=`\x1B_Ga=p,q=2,${match.controls.split(",").filter(control=>KITTY_PLACEMENT_CONTROL_KEYS.has(control.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:metadata.imageId,transmissionGeneration:metadata.transmissionGeneration,transmissionBytes:transmissionEnd-match.index,estimatedDecodedBytes:metadata.
347
+ widthPx*metadata.heightPx*4,rows:getKittyImageRowsFromControls(match.controls,metadata.rows),sequence,replacementLine:`${line.slice(0,match.index)}${sequence}${line.slice(transmissionEnd)}`}}function cropKittyImageLine(line,hiddenRows,visibleRows){let metadata=getKittyImageMetadata(line),match=findKittyControls(line);if(!metadata||!match||hiddenRows<0||hiddenRows>=metadata.rows||visibleRows<=0)return line;let croppedRows=Math.min(visibleRows,metadata.rows-hiddenRows);if(hiddenRows===0&&croppedRows===
348
+ metadata.rows)return line;let sourceY=Math.floor(metadata.heightPx*hiddenRows/metadata.rows),sourceEnd=Math.ceil(metadata.heightPx*(hiddenRows+croppedRows)/metadata.rows),sourceHeight=Math.max(1,Math.min(metadata.heightPx,sourceEnd)-sourceY),controls=match.controls.split(",").filter(control=>!/^[yhr]=/.test(control));return controls.push(`y=${sourceY}`,`h=${sourceHeight}`,`r=${croppedRows}`),`${line.slice(0,match.index)}\x1B_G${controls.join(",")};${line.slice(match.index+match.length)}`}function chooseLessDistortedCellCount(upperCount,idealCount){
349
+ if(upperCount<=1)return upperCount;let lowerCount=upperCount-1,upperDistortion=Math.max(upperCount/idealCount,idealCount/upperCount);return Math.max(lowerCount/idealCount,idealCount/lowerCount)<upperDistortion?lowerCount:upperCount}function calculateImageCellSize(imageDimensions,maxWidthCells,maxHeightCells,cellDimensions2={widthPx:9,heightPx:18},optimizeAspectRatio=!1){let maxWidth=Math.max(1,Math.floor(maxWidthCells)),maxHeight=maxHeightCells===void 0?void 0:Math.max(1,Math.floor(maxHeightCells)),
350
+ imageWidth=Math.max(1,imageDimensions.widthPx),imageHeight=Math.max(1,imageDimensions.heightPx),widthScale=maxWidth*cellDimensions2.widthPx/imageWidth,heightScale=maxHeight===void 0?widthScale:maxHeight*cellDimensions2.heightPx/imageHeight,scale=Math.min(widthScale,heightScale),scaledWidthPx=imageWidth*scale,scaledHeightPx=imageHeight*scale,columns=Math.max(1,Math.min(maxWidth,Math.ceil(scaledWidthPx/cellDimensions2.widthPx))),heightRows=scaledHeightPx/cellDimensions2.heightPx,rows=Math.max(1,Math.
351
+ ceil(heightRows));if(maxHeight!==void 0&&(rows=Math.min(maxHeight,rows)),!optimizeAspectRatio)return{columns,rows};if(widthScale<=heightScale){let idealRows=columns*cellDimensions2.widthPx*imageHeight/(imageWidth*cellDimensions2.heightPx);rows=chooseLessDistortedCellCount(rows,idealRows)}else{let idealColumns=rows*cellDimensions2.heightPx*imageWidth/(imageHeight*cellDimensions2.widthPx);columns=chooseLessDistortedCellCount(columns,idealColumns)}return{columns,rows}}function calculateImageRows(imageDimensions,targetWidthCells,cellDimensions2={
338
352
  widthPx:9,heightPx:18}){return calculateImageCellSize(imageDimensions,targetWidthCells,void 0,cellDimensions2).rows}function getPngDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<24||buffer[0]!==137||buffer[1]!==80||buffer[2]!==78||buffer[3]!==71)return null;let width=buffer.readUInt32BE(16),height=buffer.readUInt32BE(20);return{widthPx:width,heightPx:height}}catch{return null}}function getJpegDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"b\
339
353
  ase64");if(buffer.length<2||buffer[0]!==255||buffer[1]!==216)return null;let offset=2;for(;offset<buffer.length-9;){if(buffer[offset]!==255){offset++;continue}let marker=buffer[offset+1];if(marker>=192&&marker<=194){let height=buffer.readUInt16BE(offset+5);return{widthPx:buffer.readUInt16BE(offset+7),heightPx:height}}if(offset+3>=buffer.length)return null;let length=buffer.readUInt16BE(offset+2);if(length<2)return null;offset+=2+length}return null}catch{return null}}function getGifDimensions(base64Data){
340
354
  try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<10)return null;let sig=buffer.slice(0,6).toString("ascii");if(sig!=="GIF87a"&&sig!=="GIF89a")return null;let width=buffer.readUInt16LE(6),height=buffer.readUInt16LE(8);return{widthPx:width,heightPx:height}}catch{return null}}function getWebpDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<30)return null;let riff=buffer.slice(0,4).toString("ascii"),webp=buffer.slice(8,12).toString("ascii");if(riff!==
@@ -343,61 +357,84 @@ buffer[25]<<8|buffer[26]<<16)+1,height=(buffer[27]|buffer[28]<<8|buffer[29]<<16)
343
357
  if(!caps.images)return null;let maxWidth=options.maxWidthCells??80,size=calculateImageCellSize(imageDimensions,maxWidth,options.maxHeightCells,getCellDimensions(),caps.images==="kitty");return caps.images==="kitty"?(options.imageId!==void 0&&registerKittyImageMetadata({imageId:options.imageId,columns:size.columns,rows:size.rows,widthPx:imageDimensions.widthPx,heightPx:imageDimensions.heightPx}),{sequence:encodeKitty(base64Data,{columns:size.columns,rows:size.rows,imageId:options.imageId,moveCursor:options.
344
358
  moveCursor}),columns:size.columns,rows:size.rows,imageId:options.imageId}):caps.images==="iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options.preserveAspectRatio??!0}),columns:size.columns,rows:size.rows}:null}function hyperlink(text,url){return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`}function shortenImagePath(filename){let home=homedir2();return home&&(filename===home||filename.startsWith(`${home}/`)||filename.startsWith(`${home}\\`))?`~${filename.
345
359
  slice(home.length)}`:filename}function imageFallback(mimeType,dimensions,filename){let parts=[];if(filename){let display=shortenImagePath(filename);getCapabilities().hyperlinks&&isAbsolute(filename)?parts.push(hyperlink(display,pathToFileURL(filename).href)):parts.push(display)}return parts.push(`[${mimeType}]`),dimensions&&parts.push(`${dimensions.widthPx}x${dimensions.heightPx}`),`[Image: ${parts.join(" ")}]`}function dispatchMouseEvent(component,event){let result=component.handleMouse?.(event);if(result){if("target"in result){let forwarded=result;return forwarded.focus&&component.handleInput?{...forwarded,focusTarget:component}:forwarded}if(!(!result.handled&&!result.capture&&!result.focus))return{...result,handled:!0,...result.focus?{focusTarget:component}:{},target:{component,originX:event.screenX-event.x,originY:event.screenY-event.y,width:event.width,height:event.height}}}}function retargetMouseEvent(event,target){
346
- return{...event,x:event.screenX-target.originX,y:event.screenY-target.originY,width:target.width,height:target.height}}var TERMINAL_PALETTE_SIZE=16,TERMINAL_COLOR_REPLY_COUNT=2+TERMINAL_PALETTE_SIZE,TERMINAL_COLOR_QUERY=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:TERMINAL_PALETTE_SIZE},(_2,index)=>`\x1B]4;${index};?\x07`).join("")}\x1B[c`,DEVICE_ATTRIBUTES_RESPONSE_PATTERN=/^\x1b\[\?[\d;]*c$/;function isFocusable(component){return component!==null&&"focused"in component}var CURSOR_MARKER="\x1B_\
347
- pi:c\x07",FAKE_CURSOR_START="\x1B_pi:fc\x07",FAKE_CURSOR_END="\x1B_pi:/fc\x07",FOCUSED_FAKE_CURSOR=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function renderFakeCursor(text){return`${FAKE_CURSOR_START}${text}${FAKE_CURSOR_END}`}function parseSizeValue(value,referenceSize){if(value===void 0)return;if(typeof value=="number")return value;let match=value.match(/^(\d+(?:\.\d+)?)%$/);if(match)return Math.floor(referenceSize*parseFloat(match[1])/100)}var stableRenders=new WeakSet;function markStableRender(componentClass){stableRenders.add(componentClass.prototype.render)}function isStableRender(component){return component instanceof Container&&component.render===Container.prototype.render||stableRenders.has(component.render)}
348
- function renderSharedLines(component,width){return component instanceof Container&&component.render===Container.prototype.render?component.renderShared(width):component.render(width)}function renderChildren(children,width,previous){let count=children.length,before=previous?.width===width?previous:void 0,index=0,offset=0,changedLines;if(before!==void 0){for(;index<count;index++){let child=children[index],lines=renderSharedLines(child,width);if(index>=before.children.length||before.children[index]!==
349
- child||!sameLines(child,lines,before,index,offset)){changedLines=lines;break}offset+=lines.length}if(index===count&&count===before.children.length)return before}let arrays=new Array(count),heights=new Array(count);for(let i=0;i<index;i++)arrays[i]=before.arrays[i],heights[i]=before.heights[i];let first=index;for(;index<count;index++){let lines=changedLines??renderSharedLines(children[index],width);changedLines=void 0,arrays[index]=lines,heights[index]=lines.length}let joined=before!==void 0&&offset>
350
- 0?before.lines.slice(0,offset):[];for(let i=first;i<count;i+=1024)joined=joined.concat(...arrays.slice(i,Math.min(count,i+1024)));return{width,children:children.slice(),arrays,heights,lines:joined}}function sameLines(child,lines,previous,index,offset){if(isStableRender(child))return lines===previous.arrays[index];let height=previous.heights[index];if(lines.length!==height)return!1;let joined=previous.lines;for(let i=0;i<height;i++)if(lines[i]!==joined[offset+i])return!1;return!0}var Container=class{children=[];rendered;addChild(component){
351
- this.children.push(component)}removeChild(component){let index=this.children.indexOf(component);index!==-1&&this.children.splice(index,1)}clear(){this.children=[]}invalidate(){this.rendered=void 0;for(let child of this.children)child.invalidate?.()}handleMouse(event){if(event.y<0||event.y>=event.height)return;let rendered=this.rendered?.width===event.width?this.rendered:void 0,children=rendered?.children??this.children,childY=0;for(let i=0;i<children.length;i++){let child=children[i],childHeight=rendered?
352
- rendered.heights[i]:child.render(event.width).length;if(event.y>=childY&&event.y<childY+childHeight){let result=dispatchMouseEvent(child,{...event,y:event.y-childY,height:childHeight});return result?.focus&&this.handleInput?{...result,focusTarget:this}:result}childY+=childHeight}}renderShared(width){return this.rendered=renderChildren(this.children,width,this.rendered),this.rendered.lines}render(width){return this.renderShared(width).slice()}},SEGMENT_RESET="\x1B[0m\x1B]8;;\x07";function compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth){
353
- if(isImageLine(baseLine))return baseLine;let afterStart=startCol+overlayWidth,base=extractSegments(baseLine,startCol,afterStart,totalWidth-afterStart,!0),overlay=sliceWithWidth(overlayLine,0,overlayWidth,!0),beforePad=Math.max(0,startCol-base.beforeWidth),overlayPad=Math.max(0,overlayWidth-overlay.width),actualBeforeWidth=Math.max(startCol,base.beforeWidth),actualOverlayWidth=Math.max(overlayWidth,overlay.width),afterTarget=Math.max(0,totalWidth-actualBeforeWidth-actualOverlayWidth),afterPad=Math.
354
- max(0,afterTarget-base.afterWidth),result=base.before+" ".repeat(beforePad)+SEGMENT_RESET+overlay.text+" ".repeat(overlayPad)+SEGMENT_RESET+base.after+" ".repeat(afterPad);return visibleWidth(result)<=totalWidth?result:sliceByColumn(result,0,totalWidth,!0)}var VIEWPORT_TUI=Symbol.for("@earendil-works/pi-tui/viewport");function isViewportTUI(tui){return tui[VIEWPORT_TUI]===!0}var TuiBase=class _TuiBase extends Container{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;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(){
355
- return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(terminal,showHardwareCursor,logDirectory){super(),this.terminal=terminal,this.logDirectory=logDirectory,showHardwareCursor!==void 0&&(this.showHardwareCursor=showHardwareCursor)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(_options){}afterTerminalStop(_options){}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(enabled){
356
- this.showHardwareCursor!==enabled&&(this.showHardwareCursor=enabled,enabled||this.hideTerminalCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(enabled){this.clearOnShrink=enabled}getFocusedComponent(){return this.focusedComponent}setFocus(component){this.setFocusInternal({component,overlayFocusRestore:"clear"})}setFocusInternal({component,overlayFocusRestore}){let previousFocus=this.focusedComponent,nextFocus=component,previousFocusedOverlay=previousFocus?
357
- this.overlayStack.find(entry=>entry.component===previousFocus&&this.isOverlayVisible(entry)):void 0,nextFocusIsOverlay=nextFocus?this.overlayStack.some(entry=>entry.component===nextFocus):!1,restoreState=this.getVisibleOverlayFocusRestore();nextFocus&&!nextFocusIsOverlay?restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?restoreState.resume.status==="focus-target"||!this.isComponentMounted(restoreState.blockedBy)?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):
358
- this.overlayFocusRestore={status:"blocked",overlay:restoreState.overlay,blockedBy:nextFocus,resume:restoreState.resume}:previousFocusedOverlay&&restoreState.status!=="inactive"&&restoreState.overlay===previousFocusedOverlay&&!this.isOverlayFocusAncestor(previousFocusedOverlay,nextFocus)&&(this.overlayFocusRestore={status:"blocked",overlay:previousFocusedOverlay,blockedBy:nextFocus,resume:{status:"restore-overlay"}}):nextFocus===null&&(restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?
359
- nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):overlayFocusRestore==="clear"&&this.clearOverlayFocusRestore()),isFocusable(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=nextFocus,isFocusable(nextFocus)&&(nextFocus.focused=!0);let focusedOverlay=nextFocus?this.overlayStack.find(entry=>entry.component===nextFocus&&this.isOverlayVisible(entry)):void 0;focusedOverlay&&(this.overlayFocusRestore={status:"eligible",overlay:focusedOverlay})}clearOverlayFocusRestore(){
360
- this.overlayFocusRestore={status:"inactive"}}clearOverlayFocusRestoreFor(overlay){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===overlay&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(restoreState){return restoreState.resume.status==="restore-overlay"?restoreState.overlay.component:(this.clearOverlayFocusRestore(),restoreState.resume.target)}getVisibleOverlayFocusRestore(){let restoreState=this.overlayFocusRestore;return restoreState.status===
361
- "inactive"?restoreState:!this.overlayStack.includes(restoreState.overlay)||!this.isOverlayVisible(restoreState.overlay)?{status:"inactive"}:restoreState}isOverlayFocusAncestor(entry,component){let visited=new Set,current=entry.preFocus;for(;current&&!visited.has(current);){if(visited.add(current),current===component)return!0;current=this.overlayStack.find(overlay=>overlay.component===current)?.preFocus??null}return!1}retargetOverlayPreFocus(removed){for(let overlay of this.overlayStack)overlay!==
362
- removed&&overlay.preFocus===removed.component&&(overlay.preFocus=removed.preFocus)}getMountedRoots(){return this.children}isComponentMounted(component){return this.getMountedRoots().some(child=>this.containsComponent(child,component))}containsComponent(root,target){return root===target?!0:root instanceof Container?root.children.some(child=>this.containsComponent(child,target)):!1}showOverlay(component,options){let entry={component,...options===void 0?{}:{options},preFocus:this.focusedComponent,hidden:!1,
363
- focusOrder:++this.focusOrderCounter};return this.overlayStack.push(entry),!options?.nonCapturing&&this.isOverlayVisible(entry)&&this.setFocus(component),this.hideTerminalCursor(),this.requestRender(),{hide:()=>{let index=this.overlayStack.indexOf(entry);if(index!==-1){if(this.clearOverlayFocusRestoreFor(entry),this.retargetOverlayPreFocus(entry),this.overlayStack.splice(index,1),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??
364
- entry.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}},setHidden:hidden=>{if(entry.hidden!==hidden){if(entry.hidden=hidden,hidden){if(this.clearOverlayFocusRestoreFor(entry),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}}else!options?.nonCapturing&&this.isOverlayVisible(entry)&&(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component));this.requestRender()}},
365
- isHidden:()=>entry.hidden,focus:()=>{!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component),this.requestRender())},unfocus:unfocusOptions=>{let isFocused=this.focusedComponent===component,restoreState=this.overlayFocusRestore,hasPendingRestore=restoreState.status!=="inactive"&&restoreState.overlay===entry;if(!(!isFocused&&!hasPendingRestore)){if(restoreState.status==="blocked"&&restoreState.overlay===entry&&this.focusedComponent===
366
- restoreState.blockedBy){unfocusOptions?this.overlayFocusRestore={status:"blocked",overlay:entry,blockedBy:restoreState.blockedBy,resume:{status:"focus-target",target:unfocusOptions.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(entry),isFocused||unfocusOptions){let topVisible=this.getTopmostVisibleOverlay(),fallbackTarget=topVisible&&topVisible!==entry?topVisible.component:entry.preFocus;this.setFocus(unfocusOptions?unfocusOptions.target:
367
- fallbackTarget)}this.requestRender()}},isFocused:()=>this.focusedComponent===component,getBounds:()=>{if(!(!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||!entry.bounds))return{...entry.bounds}}}}hideOverlay(){let overlay=this.overlayStack[this.overlayStack.length-1];if(overlay){if(this.clearOverlayFocusRestoreFor(overlay),this.retargetOverlayPreFocus(overlay),this.overlayStack.pop(),this.focusedComponent===overlay.component){let topVisible=this.getTopmostVisibleOverlay();this.
368
- setFocus(topVisible?.component??overlay.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor()}hasOverlay(){return this.overlayStack.some(o=>this.isOverlayVisible(o))}isOverlayFocused(){return this.overlayStack.some(entry=>entry.component===this.focusedComponent&&this.isOverlayVisible(entry))}resolveMouseFocusTarget(component){for(let index=this.overlayStack.length-1;index>=0;index--){let overlay=this.
369
- overlayStack[index];if(this.isOverlayVisible(overlay)&&this.containsComponent(overlay.component,component))return overlay.component}return component}dispatchMouseToOverlay(event){for(let index=this.renderedOverlayLayouts.length-1;index>=0;index--){let layout=this.renderedOverlayLayouts[index];if(event.screenX<layout.col||event.screenX>=layout.col+layout.width||event.screenY<layout.row||event.screenY>=layout.row+layout.height)continue;let result=dispatchMouseEvent(layout.entry.component,{...event,
370
- x:event.screenX-layout.col,y:event.screenY-layout.row,width:layout.width,height:layout.height});return result?{hit:!0,result:result.focus?{...result,focusTarget:layout.entry.component}:result}:{hit:!0}}return{hit:!1}}isOverlayVisible(entry){return entry.hidden?!1:entry.options?.visible?entry.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let topmost;for(let overlay of this.overlayStack)overlay.options?.nonCapturing||!this.isOverlayVisible(overlay)||(!topmost||
371
- overlay.focusOrder>topmost.focusOrder)&&(topmost=overlay);return topmost}invalidate(){invalidateRenderedMarkdown();for(let root of this.getMountedRoots())root.invalidate();for(let overlay of this.overlayStack)overlay.component.invalidate()}start(){this.stopped=!1,this.beforeTerminalStart(),this.terminal.start(data=>this.handleTerminalInput(data),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?203\
372
- 1h"),this.queryCellSize(),this.requestRender()}addInputListener(listener){return this.inputListeners.add(listener),()=>{this.inputListeners.delete(listener)}}removeInputListener(listener){this.inputListeners.delete(listener)}onTerminalColorSchemeChange(listener){return this.terminalColorSchemeListeners.add(listener),()=>{this.terminalColorSchemeListeners.delete(listener)}}setTerminalColorSchemeNotifications(enabled){this.terminalColorSchemeNotificationsEnabled!==enabled&&(this.terminalColorSchemeNotificationsEnabled=
373
- enabled,this.stopped||this.terminal.write(enabled?"\x1B[?2031h":"\x1B[?2031l"))}queryCellSize(){getCapabilities().images&&this.terminal.write("\x1B[16t")}stop(options={}){this.stopped=!0,this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(options),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(options)}renderNow(force=!1){force&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),
374
- this.lastRenderAt=performance2.now(),this.doRender()}requestRender(force=!1){if(force){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=!0,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=!0,process.nextTick(()=>{this.immediateRenderScheduled=!1,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),
375
- this.renderRequested=!1,this.lastRenderAt=performance2.now(),this.doRender())}))}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let elapsed=performance2.now()-this.lastRenderAt,delay=Math.max(0,_TuiBase.MIN_RENDER_INTERVAL_MS-elapsed);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=
376
- performance2.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},delay)}handleTerminalInput(data){if(this.consumeTerminalColorResponse(data)||this.consumeTerminalColorSchemeReport(data))return;if(this.inputListeners.size>0){let current=data;for(let listener of this.inputListeners){let result=listener(current);if(result?.consume)return;result?.data!==void 0&&(current=result.data)}if(current.length===0)return;data=current}if(this.consumeCellSizeResponse(data))return;if(matchesKey(data,
377
- "shift+ctrl+d")&&this.onDebug){this.onDebug();return}let focusedOverlay=this.overlayStack.find(o=>o.component===this.focusedComponent);if(focusedOverlay&&!this.isOverlayVisible(focusedOverlay)){let topVisible=this.getTopmostVisibleOverlay();topVisible?this.setFocus(topVisible.component):this.setFocusInternal({component:focusedOverlay.preFocus,overlayFocusRestore:"preserve"})}if(!this.overlayStack.some(o=>o.component===this.focusedComponent)){let restoreState=this.getVisibleOverlayFocusRestore();
378
- restoreState.status==="eligible"?this.setFocus(restoreState.overlay.component):restoreState.status==="blocked"&&restoreState.blockedBy!==this.focusedComponent&&(restoreState.resume.status==="restore-overlay"?this.setFocus(restoreState.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(restoreState.resume.target)))}if(this.focusedComponent?.handleInput){if(isKeyRelease(data)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(data),this.requestImmediateRender()}}consumeTerminalColorResponse(data){
379
- let query=this.pendingTerminalColorQueries[0];if(!query)return!1;if(DEVICE_ATTRIBUTES_RESPONSE_PATTERN.test(data))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(query),!0;let response=parseOscColorResponse(data);if(!response)return!1;let{target,rgb}=response,key=String(target);return!query.deliver||query.replied.has(key)||(query.replied.add(key),target==="foreground"?query.foreground=rgb:target==="background"?query.background=rgb:target<TERMINAL_PALETTE_SIZE&&(query.
380
- palette[target]=rgb),query.replied.size===TERMINAL_COLOR_REPLY_COUNT&&this.completeTerminalColorQuery(query)),!0}terminalColorQueryResult(query){let palette=query.palette.every(color=>color!==void 0)?query.palette:void 0;return{foreground:query.foreground,background:query.background,palette}}completeTerminalColorQuery(query){let deliver=query.deliver;query.deliver=void 0,clearTimeout(query.timer),deliver?.(this.terminalColorQueryResult(query))}consumeTerminalColorSchemeReport(data){let scheme=parseTerminalColorSchemeReport(
381
- data);if(!scheme)return!1;for(let listener of this.terminalColorSchemeListeners)listener(scheme);return!0}consumeCellSizeResponse(data){let match=data.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!match)return!1;let heightPx=parseInt(match[1],10),widthPx=parseInt(match[2],10);return heightPx<=0||widthPx<=0||(setCellDimensions({widthPx,heightPx}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(options,overlayHeight,termWidth,termHeight){let opt=options??{},margin=typeof opt.margin=="number"?
382
- {top:opt.margin,right:opt.margin,bottom:opt.margin,left:opt.margin}:opt.margin??{},marginTop=Math.max(0,margin.top??0),marginRight=Math.max(0,margin.right??0),marginBottom=Math.max(0,margin.bottom??0),marginLeft=Math.max(0,margin.left??0),availWidth=Math.max(1,termWidth-marginLeft-marginRight),availHeight=Math.max(1,termHeight-marginTop-marginBottom),width=parseSizeValue(opt.width,termWidth)??Math.min(80,availWidth);opt.minWidth!==void 0&&(width=Math.max(width,opt.minWidth)),width=Math.max(1,Math.
383
- min(width,availWidth));let maxHeight=parseSizeValue(opt.maxHeight,termHeight);maxHeight!==void 0&&(maxHeight=Math.max(1,Math.min(maxHeight,availHeight)));let effectiveHeight=maxHeight!==void 0?Math.min(overlayHeight,maxHeight):overlayHeight,row,col;if(opt.row!==void 0)if(typeof opt.row=="string"){let match=opt.row.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxRow=Math.max(0,availHeight-effectiveHeight),percent=parseFloat(match[1])/100;row=marginTop+Math.floor(maxRow*percent)}else row=this.resolveAnchorRow(
384
- "center",effectiveHeight,availHeight,marginTop)}else row=opt.row;else{let anchor=opt.anchor??"center";row=this.resolveAnchorRow(anchor,effectiveHeight,availHeight,marginTop)}if(opt.col!==void 0)if(typeof opt.col=="string"){let match=opt.col.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxCol=Math.max(0,availWidth-width),percent=parseFloat(match[1])/100;col=marginLeft+Math.floor(maxCol*percent)}else col=this.resolveAnchorCol("center",width,availWidth,marginLeft)}else col=opt.col;else{let anchor=opt.
385
- anchor??"center";col=this.resolveAnchorCol(anchor,width,availWidth,marginLeft)}return opt.offsetY!==void 0&&(row+=opt.offsetY),opt.offsetX!==void 0&&(col+=opt.offsetX),row=Math.max(marginTop,Math.min(row,termHeight-marginBottom-effectiveHeight)),col=Math.max(marginLeft,Math.min(col,termWidth-marginRight-width)),{width,row,col,maxHeight}}resolveAnchorRow(anchor,height,availHeight,marginTop){switch(anchor){case"top-left":case"top-center":case"top-right":return marginTop;case"bottom-left":case"bott\
386
- om-center":case"bottom-right":return marginTop+availHeight-height;case"left-center":case"center":case"right-center":return marginTop+Math.floor((availHeight-height)/2)}}resolveAnchorCol(anchor,width,availWidth,marginLeft){switch(anchor){case"top-left":case"left-center":case"bottom-left":return marginLeft;case"top-right":case"right-center":case"bottom-right":return marginLeft+availWidth-width;case"top-center":case"center":case"bottom-center":return marginLeft+Math.floor((availWidth-width)/2)}}compositeOverlays(lines,termWidth,termHeight){
387
- if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],lines;let result=[...lines];for(let entry of this.overlayStack)entry.bounds=void 0;let rendered=[],minLinesNeeded=result.length,visibleEntries=this.overlayStack.filter(e=>this.isOverlayVisible(e));visibleEntries.sort((a3,b)=>a3.focusOrder-b.focusOrder);for(let entry of visibleEntries){let{component,options}=entry,{width,maxHeight}=this.resolveOverlayLayout(options,0,termWidth,termHeight),overlayLines=this.resolveFakeCursors(component.
388
- render(width));maxHeight!==void 0&&overlayLines.length>maxHeight&&(overlayLines=overlayLines.slice(0,maxHeight));let{row,col}=this.resolveOverlayLayout(options,overlayLines.length,termWidth,termHeight);entry.bounds={row,col,width,height:overlayLines.length},rendered.push({entry,overlayLines,row,col,w:width}),minLinesNeeded=Math.max(minLinesNeeded,row+overlayLines.length)}this.renderedOverlayLayouts=rendered.map(({entry,row,col,w:w2,overlayLines})=>({entry,row,col,width:w2,height:overlayLines.length}));
389
- let workingHeight=Math.max(result.length,termHeight,minLinesNeeded);for(;result.length<workingHeight;)result.push("");let viewportStart=Math.max(0,workingHeight-termHeight);for(let{overlayLines,row,col,w:w2}of rendered)for(let i=0;i<overlayLines.length;i++){let idx=viewportStart+row+i;if(idx>=0&&idx<result.length){let truncatedOverlayLine=visibleWidth(overlayLines[i])>w2?sliceByColumn(overlayLines[i],0,w2,!0):overlayLines[i];result[idx]=this.compositeLineAt(result[idx],truncatedOverlayLine,col,w2,
390
- termWidth)}}return result}applyLineResets(lines){let reset=SEGMENT_RESET;for(let i=0;i<lines.length;i++){let line=lines[i];isImageLine(line)||(lines[i]=normalizeTerminalOutput(line)+reset)}return lines}compositeLineAt(baseLine,overlayLine,startCol,overlayWidth,totalWidth){return compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth)}extractCursorPosition(lines,height){let viewportTop=Math.max(0,lines.length-height);for(let row=lines.length-1;row>=viewportTop;row--){let line=lines[row],
391
- markerIndex=line.indexOf(CURSOR_MARKER);if(markerIndex!==-1){let beforeMarker=line.slice(0,markerIndex),col=visibleWidth(beforeMarker);return lines[row]=line.slice(0,markerIndex)+line.slice(markerIndex+CURSOR_MARKER.length),{row,col}}}return null}resolveFakeCursors(lines){return lines.map(line=>line.includes(FAKE_CURSOR_START)?(this.showHardwareCursor?line.replace(FOCUSED_FAKE_CURSOR,"$1$2"):line).replaceAll(FAKE_CURSOR_START,"\x1B[7m").replaceAll(FAKE_CURSOR_END,"\x1B[27m"):line)}queryTerminalColors({
392
- timeoutMs,onLateReply}){return new Promise(resolve=>{let query={palette:Array.from({length:TERMINAL_PALETTE_SIZE},()=>{}),replied:new Set,deliver:resolve,timer:void 0};query.timer=setTimeout(()=>{query.deliver=onLateReply,resolve(this.terminalColorQueryResult(query))},timeoutMs),this.pendingTerminalColorQueries.push(query),this.terminal.write(TERMINAL_COLOR_QUERY)})}};var Box=class{children=[];paddingX;paddingY;bgFn;cache;rendered;emptyLines=[];constructor(paddingX=1,paddingY=1,bgFn){this.paddingX=paddingX,this.paddingY=paddingY,this.bgFn=bgFn}addChild(component){this.children.push(component),this.invalidateCache()}removeChild(component){let index=this.children.indexOf(component);index!==-1&&(this.children.splice(index,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(bgFn){this.bgFn=bgFn}setPaddingX(paddingX){this.paddingX!==
393
- paddingX&&(this.paddingX=paddingX,this.invalidateCache())}invalidateCache(){this.cache=void 0,this.rendered=void 0}invalidate(){this.invalidateCache();for(let child of this.children)child.invalidate?.()}handleMouse(event){let contentWidth=Math.max(1,event.width-this.paddingX*2),contentY=event.y-this.paddingY,contentX=event.x-this.paddingX;if(contentY<0||contentX<0||contentX>=contentWidth)return;let rendered=this.rendered?.width===contentWidth?this.rendered:void 0,children=rendered?.children??this.
394
- children,childY=0;for(let i=0;i<children.length;i++){let child=children[i],childHeight=rendered?rendered.heights[i]:child.render(contentWidth).length;if(contentY>=childY&&contentY<childY+childHeight)return dispatchMouseEvent(child,{...event,x:contentX,y:contentY-childY,width:contentWidth,height:childHeight});childY+=childHeight}}render(width){if(this.children.length===0)return this.emptyLines;let contentWidth=Math.max(1,width-this.paddingX*2),leftPad=" ".repeat(this.paddingX),rendered=renderChildren(
395
- this.children,contentWidth,this.rendered);this.rendered=rendered;let childLines=rendered.lines;if(childLines.length===0)return this.emptyLines;let bgSample=this.bgFn?this.bgFn("test"):void 0,cache=this.cache&&this.cache.width===width&&this.cache.bgSample===bgSample?this.cache:void 0;if(cache?.childLines===childLines)return cache.lines;let result=[],reused=cache!==void 0&&cache.childLines.length===childLines.length;for(let i=0;i<this.paddingY;i++)result.push(cache?cache.lines[i]:this.applyBg("",width));
396
- for(let i=0;i<childLines.length;i++){let line=childLines[i];cache!==void 0&&i<cache.childLines.length&&cache.childLines[i]===line?result.push(cache.lines[this.paddingY+i]):(reused=!1,result.push(this.applyBg(leftPad+line,width)))}for(let i=0;i<this.paddingY;i++)result.push(cache?cache.lines[cache.lines.length-this.paddingY+i]:this.applyBg("",width));return reused?(cache.childLines=childLines,cache.lines):(flattenLines(result),this.cache={childLines,width,bgSample,lines:result},result)}applyBg(line,width){
397
- let visLen=visibleWidth(line),padNeeded=Math.max(0,width-visLen),padded=line+" ".repeat(padNeeded);return this.bgFn?this.bgFn(padded):padded}};markStableRender(Box);var Text=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(text="",paddingX=1,paddingY=1,customBgFn){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.customBgFn=customBgFn}setText(text){this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(customBgFn){this.customBgFn=customBgFn,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setPaddingX(paddingX){this.paddingX=paddingX,this.
398
- invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;if(!this.text||this.text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=this.text.replace(/\t/g," "),paddingX=Math.min(this.paddingX,Math.max(0,Math.floor((width-1)/2))),contentWidth=Math.max(1,width-
399
- paddingX*2),wrappedLines=wrapTextWithAnsi(normalizedText,contentWidth),leftMargin=" ".repeat(paddingX),rightMargin=" ".repeat(paddingX),contentLines=[];for(let line of wrappedLines){let lineWithMargins=leftMargin+line+rightMargin;if(this.customBgFn)contentLines.push(applyBackgroundToLine(lineWithMargins,width,this.customBgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);contentLines.push(lineWithMargins+" ".repeat(paddingNeeded))}}let emptyLine=" ".
400
- repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=this.customBgFn?applyBackgroundToLine(emptyLine,width,this.customBgFn):emptyLine;emptyLines.push(line)}let result=[...emptyLines,...contentLines,...emptyLines];return flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};markStableRender(Text);var DEFAULT_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],DEFAULT_INTERVAL_MS=80,Loader=class extends Text{frames=[...DEFAULT_FRAMES];intervalMs=DEFAULT_INTERVAL_MS;currentFrame=0;intervalId=null;ui=null;renderIndicatorVerbatim=!1;spinnerColorFn;messageColorFn;message="Loading...";displayText="";constructor(ui,spinnerColorFn,messageColorFn,message="Loading...",indicator){super("",1,0),this.ui=ui,this.spinnerColorFn=spinnerColorFn,this.messageColorFn=
360
+ return{...event,x:event.screenX-target.originX,y:event.screenY-target.originY,width:target.width,height:target.height}}var renderClock=()=>performance2.now();function setRenderClockForTest(clock){renderClock=clock??(()=>performance2.now())}var FRAME_SPACING_FACTOR=3,TERMINAL_PALETTE_SIZE=16,TERMINAL_COLOR_REPLY_COUNT=2+TERMINAL_PALETTE_SIZE,TERMINAL_COLOR_QUERY=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:TERMINAL_PALETTE_SIZE},(_2,index)=>`\x1B]4;${index};?\x07`).join("")}\x1B[c`,DEVICE_ATTRIBUTES_RESPONSE_PATTERN=/^\x1b\[\?[\d;]*c$/;
361
+ function isFocusable(component){return component!==null&&"focused"in component}var CURSOR_MARKER="\x1B_pi:c\x07",FAKE_CURSOR_START="\x1B_pi:fc\x07",FAKE_CURSOR_END="\x1B_pi:/fc\x07",FOCUSED_FAKE_CURSOR=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function renderFakeCursor(text){return`${FAKE_CURSOR_START}${text}${FAKE_CURSOR_END}`}function parseSizeValue(value,referenceSize){if(value===void 0)return;if(typeof value=="number")return value;let match=value.match(/^(\d+(?:\.\d+)?)%$/);if(match)return Math.floor(referenceSize*parseFloat(match[1])/100)}var stableRenders=new WeakSet;function markStableRender(componentClass){stableRenders.add(componentClass.prototype.render)}function isStableRender(component){return component instanceof Container&&component.render===Container.prototype.render||stableRenders.has(component.render)}
362
+ function renderSharedLines(component,width){return component instanceof Container&&component.render===Container.prototype.render?component.renderShared(width):component.render(width)}var LIVE_LINE_EDITS_KEPT=32,LiveLineArray=class{lines=[];revision=0;starts=[];changedSince(revision){if(revision===this.revision)return Number.POSITIVE_INFINITY;let changes=this.revision-revision;if(changes<0||changes>this.starts.length)return 0;let start=Number.POSITIVE_INFINITY;for(let i=this.starts.length-changes;i<
363
+ this.starts.length;i++)start=Math.min(start,this.starts[i]);return start}edit(start){this.lines.length=Math.min(this.lines.length,start),this.revision++,this.starts.push(start),this.starts.length>LIVE_LINE_EDITS_KEPT&&this.starts.shift()}},liveRenders=new WeakMap;function markLiveRender(key,renderLive){liveRenders.set(key,renderLive)}function renderLiveLines(component,width){let key=component instanceof Container&&component.render===Container.prototype.render?component.renderShared:component.render;
364
+ return liveRenders.get(key)?.call(component,width)}function renderChildren(children,width,previous){let count=children.length,before=previous?.width===width?previous:void 0,index=0,offset=0,changedLines;if(before!==void 0){for(;index<count;index++){let child=children[index],lines=renderSharedLines(child,width);if(index>=before.children.length||before.children[index]!==child||!sameLines(child,lines,before,index,offset)){changedLines=lines;break}offset+=lines.length}if(index===count&&count===before.
365
+ children.length)return before}let arrays=new Array(count),heights=new Array(count);for(let i=0;i<index;i++)arrays[i]=before.arrays[i],heights[i]=before.heights[i];let first=index;for(;index<count;index++){let lines=changedLines??renderSharedLines(children[index],width);changedLines=void 0,arrays[index]=lines,heights[index]=lines.length}let joined=before!==void 0&&offset>0?before.lines.slice(0,offset):[];for(let i=first;i<count;i+=1024)joined=joined.concat(...arrays.slice(i,Math.min(count,i+1024)));
366
+ return{width,children:children.slice(),arrays,heights,lines:joined}}function sameLines(child,lines,previous,index,offset){if(isStableRender(child))return lines===previous.arrays[index];let height=previous.heights[index];if(lines.length!==height)return!1;let joined=previous.lines;for(let i=0;i<height;i++)if(lines[i]!==joined[offset+i])return!1;return!0}var reportingRenders=new WeakSet,unreportedSubtrees=new WeakSet,renderOwners=new WeakMap,CHILD_CHANGED=Symbol("pi-tui.childChanged");function renderKey(component){
367
+ return component instanceof Container&&component.render===Container.prototype.render?component.renderShared:component.render}function markReportsChanges(componentClass){let prototype=componentClass.prototype;reportingRenders.add(prototype.render===Container.prototype.render?prototype.renderShared:prototype.render)}var changeReportsUsed=!0;function setChangeReportsForTest(enabled){changeReportsUsed=enabled}function reportsChanges(component){return changeReportsUsed&&reportingRenders.has(renderKey(
368
+ component))&&!unreportedSubtrees.has(component)}function setSubtreeReportsChanges(component,reports){reports?unreportedSubtrees.delete(component):unreportedSubtrees.add(component)}function setRenderOwner(child,owner){let owners=renderOwners.get(child);owners!==owner&&(owners===void 0?renderOwners.set(child,owner):Array.isArray(owners)?owners.includes(owner)||owners.push(owner):renderOwners.set(child,[owners,owner]))}function dropRenderOwner(child,owner){let owners=renderOwners.get(child);if(owners===
369
+ owner)renderOwners.delete(child);else if(Array.isArray(owners)){let index=owners.indexOf(owner);index!==-1&&owners.splice(index,1)}}function renderChildLines(owner,child,width){return setRenderOwner(child,owner),renderSharedLines(child,width)}function reportRenderChange(component){let owners=renderOwners.get(component);if(owners!==void 0)if(Array.isArray(owners))for(let owner of owners.slice())notifyOwner(owner,component);else notifyOwner(owners,component)}function notifyOwner(owner,child){owner instanceof
370
+ Container?owner[CHILD_CHANGED](child):reportRenderChange(owner)}var LISTED_CHANGES=64;function emptyContainerLines(width){return{width,children:[],arrays:[],lives:[],revisions:[],heights:[],offsets:[],reports:[],unreported:[],live:new LiveLineArray}}function sameLinesAt(lines,joined,offset,count){if(lines.length!==count)return!1;for(let i=0;i<count;i++)if(lines[i]!==joined[offset+i])return!1;return!0}function renderChildForContainer(owner,child,width){setRenderOwner(child,owner);let live=renderLiveLines(
371
+ child,width);return live===void 0?{lines:renderSharedLines(child,width),live:void 0,revision:-1}:{lines:live.lines,live,revision:live.revision}}function childChangedFrom(before,index,child,rendered,joined,offset){return index>=before.children.length?0:rendered.live!==void 0?before.lives[index]===rendered.live&&before.arrays[index]===rendered.lines?rendered.live.changedSince(before.revisions[index]):0:before.lives[index]!==void 0?0:before.children[index]===child&&before.arrays[index]===rendered.lines&&
372
+ isStableRender(child)||sameLinesAt(rendered.lines,joined,offset,before.heights[index])?Number.POSITIVE_INFINITY:0}var Container=class{childList=[];rendered;sharedLines;changedChildren=[];changesUnlisted=!1;childrenUsed=!1;changeReported=!1;get children(){return this.noteChildrenUsed(),this.childList}set children(children){this.childList=children,this.noteChildrenUsed()}ownChildren(){return Object.hasOwn(this,"children")?this.children:this.childList}noteChildrenUsed(){this.childrenUsed=!0,this.reportChange()}reportChange(){
373
+ this.changeReported||(this.changeReported=!0,reportRenderChange(this))}noteRendered(){this.changeReported=!1}[CHILD_CHANGED](child){if(this.rendered!==void 0&&!this.changesUnlisted){let changed=this.changedChildren;changed[changed.length-1]!==child&&(changed.length<LISTED_CHANGES?changed.push(child):this.changesUnlisted=!0)}this.reportChange()}addChild(component){this.ownChildren().push(component),this.noteChildrenUsed()}removeChild(component){let children=this.ownChildren(),index=children.indexOf(
374
+ component);index!==-1&&(children.splice(index,1),this.noteChildrenUsed())}clear(){Object.hasOwn(this,"children")?this.children=[]:this.childList=[],this.noteChildrenUsed()}invalidate(){this.rendered=void 0,this.sharedLines=void 0,this.changedChildren=[],this.changesUnlisted=!1;for(let child of this.ownChildren())child.invalidate?.();this.reportChange()}handleMouse(event){if(event.y<0||event.y>=event.height)return;let rendered=this.rendered?.width===event.width?this.rendered:void 0,children=rendered?.
375
+ children??this.ownChildren(),childY=0;for(let i=0;i<children.length;i++){let child=children[i],childHeight=rendered?rendered.heights[i]:child.render(event.width).length;if(event.y>=childY&&event.y<childY+childHeight){let result=dispatchMouseEvent(child,{...event,y:event.y-childY,height:childHeight});return result?.focus&&this.handleInput?{...result,focusTarget:this}:result}childY+=childHeight}}renderLiveChildren(width){this.changeReported=!1;let children=this.ownChildren(),shadowed=children!==this.
376
+ childList,count=children.length,state=this.rendered;(state===void 0||state.width!==width)&&(state=emptyContainerLines(width),this.rendered=state);let before=state,joined=before.live.lines,beforeCount=before.children.length,changed=this.changedChildren;changed.length>0&&(this.changedChildren=[]);let renderAll=this.changesUnlisted||shadowed;this.changesUnlisted=!1;let tail=count;if(this.childrenUsed||renderAll||beforeCount!==count){this.childrenUsed=!1;let common=Math.min(count,beforeCount),index=0;
377
+ for(;index<common&&children[index]===before.children[index];)index++;(index<common||count!==beforeCount)&&(tail=index)}let again;if(renderAll){again=[];for(let i=0;i<tail;i++)again.push(i)}else{again=[];for(let child of changed){let index=before.children.lastIndexOf(child);index===-1?dropRenderOwner(child,this):index<tail&&again.push(index)}for(let index of before.unreported){if(index>=tail)break;again.push(index)}again.length>1&&(again.sort((a3,b)=>a3-b),again=again.filter((index,i)=>i===0||index!==
378
+ again[i-1]))}let changeAt=Number.POSITIVE_INFINITY,firstChanged=tail,reportsChanged=!1;for(let index of again){let child=children[index],rendered=renderChildForContainer(this,child,width),changedFrom=childChangedFrom(before,index,child,rendered,joined,before.offsets[index]);changedFrom!==Number.POSITIVE_INFINITY&&(changeAt=Math.min(changeAt,before.offsets[index]+changedFrom)),rendered.lines.length!==before.heights[index]&&(firstChanged=Math.min(firstChanged,index)),before.arrays[index]=rendered.
379
+ lines,before.lives[index]=rendered.live,before.revisions[index]=rendered.revision,before.heights[index]=rendered.lines.length;let reports=reportsChanges(child);reports!==before.reports[index]&&(before.reports[index]=reports,reportsChanged=!0)}if(tail<count||tail<beforeCount){let moved=new Map;for(let i=beforeCount-1;i>=tail;i--)moved.set(before.children[i],i);let changedSet=changed.length>0?new Set(changed):void 0,tailChildren=[],tailLines=[],tailReports=[],offset=tail<beforeCount?before.offsets[tail]:
380
+ tail===0?0:before.offsets[tail-1]+before.heights[tail-1];for(let i=tail;i<count;i++){let child=children[i],from=moved.get(child),rendered,reports,live=from===void 0?void 0:before.lives[from];if(from!==void 0&&!renderAll&&before.reports[from]===!0&&changedSet?.has(child)!==!0&&(live===void 0||live.revision===before.revisions[from])?(moved.delete(child),rendered={lines:before.arrays[from],live,revision:before.revisions[from]},reports=!0):(from!==void 0&&moved.delete(child),rendered=renderChildForContainer(
381
+ this,child,width),reports=reportsChanges(child)),changeAt===Number.POSITIVE_INFINITY){let changedFrom=childChangedFrom(before,i,child,rendered,joined,offset);changedFrom!==Number.POSITIVE_INFINITY&&(changeAt=offset+changedFrom)}tailChildren.push(child),tailLines.push(rendered),tailReports.push(reports),offset+=rendered.lines.length}changeAt===Number.POSITIVE_INFINITY&&count!==beforeCount&&(changeAt=offset),before.children.length=tail,before.arrays.length=tail,before.lives.length=tail,before.revisions.
382
+ length=tail,before.heights.length=tail,before.offsets.length=tail,before.reports.length=tail;for(let i=0;i<tailChildren.length;i++){let rendered=tailLines[i];before.children.push(tailChildren[i]),before.arrays.push(rendered.lines),before.lives.push(rendered.live),before.revisions.push(rendered.revision),before.heights.push(rendered.lines.length),before.offsets.push(0),before.reports.push(tailReports[i])}reportsChanged=!0}if(changeAt!==Number.POSITIVE_INFINITY){let first=Math.min(firstChanged,count);
383
+ for(;first>0&&before.offsets[first-1]+before.heights[first-1]>changeAt;)first--;for(;first<count&&first<firstChanged&&before.offsets[first]+before.heights[first]<=changeAt;)first++;firstChanged=Math.min(firstChanged,first)}if(firstChanged<count){let offset=firstChanged===0?0:before.offsets[firstChanged-1]+before.heights[firstChanged-1];for(let i=firstChanged;i<count;i++){let live=before.lives[i];if(live!==void 0&&live.revision!==before.revisions[i]&&changeAt<=offset){let rendered=renderChildForContainer(
384
+ this,children[i],width);before.arrays[i]=rendered.lines,before.lives[i]=rendered.live,before.revisions[i]=rendered.revision,before.heights[i]=rendered.lines.length}before.offsets[i]=offset,offset+=before.heights[i]}}if(changeAt!==Number.POSITIVE_INFINITY){before.live.edit(changeAt);for(let i=firstChanged;i<count;i++){if(before.offsets[i]+before.heights[i]<=changeAt)continue;let lines=before.arrays[i];for(let j2=Math.max(0,changeAt-before.offsets[i]);j2<lines.length;j2++)joined.push(lines[j2])}}if(reportsChanged){
385
+ before.unreported.length=0;for(let i=0;i<count;i++)before.reports[i]||before.unreported.push(i)}return setSubtreeReportsChanges(this,!shadowed&&before.unreported.length===0),before.live}renderShared(width){let live=this.renderLiveChildren(width),shared=this.sharedLines;if(shared?.live===live&&shared.revision===live.revision)return shared.lines;let lines=live.lines.slice();return this.sharedLines={live,revision:live.revision,lines},lines}render(width){return this.renderShared(width).slice()}static renderLive(container,width){
386
+ return container.renderLiveChildren(width)}};markLiveRender(Container.prototype.renderShared,function(width){return Container.renderLive(this,width)});markReportsChanges(Container);var SEGMENT_RESET="\x1B[0m\x1B]8;;\x07";function compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth){if(isImageLine(baseLine))return baseLine;let afterStart=startCol+overlayWidth,base=extractSegments(baseLine,startCol,afterStart,totalWidth-afterStart,!0),overlay=sliceWithWidth(overlayLine,0,overlayWidth,
387
+ !0),beforePad=Math.max(0,startCol-base.beforeWidth),overlayPad=Math.max(0,overlayWidth-overlay.width),actualBeforeWidth=Math.max(startCol,base.beforeWidth),actualOverlayWidth=Math.max(overlayWidth,overlay.width),afterTarget=Math.max(0,totalWidth-actualBeforeWidth-actualOverlayWidth),afterPad=Math.max(0,afterTarget-base.afterWidth),result=base.before+" ".repeat(beforePad)+SEGMENT_RESET+overlay.text+" ".repeat(overlayPad)+SEGMENT_RESET+base.after+" ".repeat(afterPad);return visibleWidth(result)<=totalWidth?
388
+ result:sliceByColumn(result,0,totalWidth,!0)}var VIEWPORT_TUI=Symbol.for("@earendil-works/pi-tui/viewport");function isViewportTUI(tui){return tui[VIEWPORT_TUI]===!0}var TuiBase=class _TuiBase extends Container{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;lastFrameDuration=0;nextFrameUnspaced=!0;nextFrameForInput=!1;handlingInput=!1;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){
389
+ return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(terminal,showHardwareCursor,logDirectory){super(),this.terminal=terminal,this.logDirectory=logDirectory,showHardwareCursor!==void 0&&(this.showHardwareCursor=showHardwareCursor)}renderFrame(){let start=renderClock();this.doRender(),this.lastFrameDuration=this.nextFrameUnspaced?0:renderClock()-start,this.nextFrameUnspaced=!1,this.nextFrameForInput=!1}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(_options){}afterTerminalStop(_options){}getExitRestorePrefix(){
390
+ 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(enabled){this.showHardwareCursor!==enabled&&(this.showHardwareCursor=enabled,enabled||this.hideTerminalCursor(),this.requestRender())}getClearOnShrink(){
391
+ return this.clearOnShrink}setClearOnShrink(enabled){this.clearOnShrink=enabled}getFocusedComponent(){return this.focusedComponent}setFocus(component){this.setFocusInternal({component,overlayFocusRestore:"clear"})}setFocusInternal({component,overlayFocusRestore}){let previousFocus=this.focusedComponent,nextFocus=component,previousFocusedOverlay=previousFocus?this.overlayStack.find(entry=>entry.component===previousFocus&&this.isOverlayVisible(entry)):void 0,nextFocusIsOverlay=nextFocus?this.overlayStack.
392
+ some(entry=>entry.component===nextFocus):!1,restoreState=this.getVisibleOverlayFocusRestore();nextFocus&&!nextFocusIsOverlay?restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?restoreState.resume.status==="focus-target"||!this.isComponentMounted(restoreState.blockedBy)?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):this.overlayFocusRestore={status:"blocked",overlay:restoreState.overlay,blockedBy:nextFocus,resume:restoreState.resume}:previousFocusedOverlay&&restoreState.
393
+ status!=="inactive"&&restoreState.overlay===previousFocusedOverlay&&!this.isOverlayFocusAncestor(previousFocusedOverlay,nextFocus)&&(this.overlayFocusRestore={status:"blocked",overlay:previousFocusedOverlay,blockedBy:nextFocus,resume:{status:"restore-overlay"}}):nextFocus===null&&(restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):overlayFocusRestore==="clear"&&this.clearOverlayFocusRestore()),isFocusable(this.focusedComponent)&&
394
+ (this.focusedComponent.focused=!1),this.focusedComponent=nextFocus,isFocusable(nextFocus)&&(nextFocus.focused=!0);let focusedOverlay=nextFocus?this.overlayStack.find(entry=>entry.component===nextFocus&&this.isOverlayVisible(entry)):void 0;focusedOverlay&&(this.overlayFocusRestore={status:"eligible",overlay:focusedOverlay})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"}}clearOverlayFocusRestoreFor(overlay){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.
395
+ overlay===overlay&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(restoreState){return restoreState.resume.status==="restore-overlay"?restoreState.overlay.component:(this.clearOverlayFocusRestore(),restoreState.resume.target)}getVisibleOverlayFocusRestore(){let restoreState=this.overlayFocusRestore;return restoreState.status==="inactive"?restoreState:!this.overlayStack.includes(restoreState.overlay)||!this.isOverlayVisible(restoreState.overlay)?{status:"inactive"}:restoreState}isOverlayFocusAncestor(entry,component){
396
+ let visited=new Set,current=entry.preFocus;for(;current&&!visited.has(current);){if(visited.add(current),current===component)return!0;current=this.overlayStack.find(overlay=>overlay.component===current)?.preFocus??null}return!1}retargetOverlayPreFocus(removed){for(let overlay of this.overlayStack)overlay!==removed&&overlay.preFocus===removed.component&&(overlay.preFocus=removed.preFocus)}getMountedRoots(){return this.children}isComponentMounted(component){return this.getMountedRoots().some(child=>this.
397
+ containsComponent(child,component))}containsComponent(root,target){return root===target?!0:root instanceof Container?root.children.some(child=>this.containsComponent(child,target)):!1}showOverlay(component,options){let entry={component,...options===void 0?{}:{options},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(entry),!options?.nonCapturing&&this.isOverlayVisible(entry)&&this.setFocus(component),this.hideTerminalCursor(),this.requestRender(),
398
+ {hide:()=>{let index=this.overlayStack.indexOf(entry);if(index!==-1){if(this.clearOverlayFocusRestoreFor(entry),this.retargetOverlayPreFocus(entry),this.overlayStack.splice(index,1),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}},setHidden:hidden=>{if(entry.hidden!==hidden){if(entry.hidden=hidden,hidden){if(this.clearOverlayFocusRestoreFor(
399
+ entry),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}}else!options?.nonCapturing&&this.isOverlayVisible(entry)&&(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component));this.requestRender()}},isHidden:()=>entry.hidden,focus:()=>{!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component),this.requestRender())},unfocus:unfocusOptions=>{
400
+ let isFocused=this.focusedComponent===component,restoreState=this.overlayFocusRestore,hasPendingRestore=restoreState.status!=="inactive"&&restoreState.overlay===entry;if(!(!isFocused&&!hasPendingRestore)){if(restoreState.status==="blocked"&&restoreState.overlay===entry&&this.focusedComponent===restoreState.blockedBy){unfocusOptions?this.overlayFocusRestore={status:"blocked",overlay:entry,blockedBy:restoreState.blockedBy,resume:{status:"focus-target",target:unfocusOptions.target}}:this.clearOverlayFocusRestore(),
401
+ this.requestRender();return}if(this.clearOverlayFocusRestoreFor(entry),isFocused||unfocusOptions){let topVisible=this.getTopmostVisibleOverlay(),fallbackTarget=topVisible&&topVisible!==entry?topVisible.component:entry.preFocus;this.setFocus(unfocusOptions?unfocusOptions.target:fallbackTarget)}this.requestRender()}},isFocused:()=>this.focusedComponent===component,getBounds:()=>{if(!(!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||!entry.bounds))return{...entry.bounds}}}}hideOverlay(){
402
+ let overlay=this.overlayStack[this.overlayStack.length-1];if(overlay){if(this.clearOverlayFocusRestoreFor(overlay),this.retargetOverlayPreFocus(overlay),this.overlayStack.pop(),this.focusedComponent===overlay.component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??overlay.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor()}hasOverlay(){return this.overlayStack.
403
+ some(o=>this.isOverlayVisible(o))}isOverlayFocused(){return this.overlayStack.some(entry=>entry.component===this.focusedComponent&&this.isOverlayVisible(entry))}resolveMouseFocusTarget(component){for(let index=this.overlayStack.length-1;index>=0;index--){let overlay=this.overlayStack[index];if(this.isOverlayVisible(overlay)&&this.containsComponent(overlay.component,component))return overlay.component}return component}dispatchMouseToOverlay(event){for(let index=this.renderedOverlayLayouts.length-
404
+ 1;index>=0;index--){let layout=this.renderedOverlayLayouts[index];if(event.screenX<layout.col||event.screenX>=layout.col+layout.width||event.screenY<layout.row||event.screenY>=layout.row+layout.height)continue;let result=dispatchMouseEvent(layout.entry.component,{...event,x:event.screenX-layout.col,y:event.screenY-layout.row,width:layout.width,height:layout.height});return result?{hit:!0,result:result.focus?{...result,focusTarget:layout.entry.component}:result}:{hit:!0}}return{hit:!1}}isOverlayVisible(entry){
405
+ return entry.hidden?!1:entry.options?.visible?entry.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let topmost;for(let overlay of this.overlayStack)overlay.options?.nonCapturing||!this.isOverlayVisible(overlay)||(!topmost||overlay.focusOrder>topmost.focusOrder)&&(topmost=overlay);return topmost}invalidate(){invalidateRenderedMarkdown();for(let root of this.getMountedRoots())root.invalidate();for(let overlay of this.overlayStack)overlay.component.invalidate()}start(){
406
+ this.stopped=!1,this.nextFrameUnspaced=!0,process.off("exit",this.exitRestoreHandler),process.on("exit",this.exitRestoreHandler),this.beforeTerminalStart(),this.terminal.start(data=>{this.handlingInput=!0;try{this.handleTerminalInput(data)}finally{this.handlingInput=!1}},()=>{this.nextFrameUnspaced=!0,this.requestRender()}),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.requestRender()}addInputListener(listener){
407
+ return this.inputListeners.add(listener),()=>{this.inputListeners.delete(listener)}}removeInputListener(listener){this.inputListeners.delete(listener)}onTerminalColorSchemeChange(listener){return this.terminalColorSchemeListeners.add(listener),()=>{this.terminalColorSchemeListeners.delete(listener)}}setTerminalColorSchemeNotifications(enabled){this.terminalColorSchemeNotificationsEnabled!==enabled&&(this.terminalColorSchemeNotificationsEnabled=enabled,this.stopped||this.terminal.write(enabled?"\x1B\
408
+ [?2031h":"\x1B[?2031l"))}queryCellSize(){getCapabilities().images&&this.terminal.write("\x1B[16t")}stop(options={}){this.stopped=!0,process.off("exit",this.exitRestoreHandler),this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(options),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(options)}renderNow(force=!1){force&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.
409
+ lastRenderAt=renderClock(),this.renderFrame()}requestRender(force=!1){if(force){this.resetRenderState(),this.nextFrameUnspaced=!0,this.requestImmediateRender();return}this.handlingInput&&!this.nextFrameForInput&&(this.nextFrameForInput=!0,this.renderTimer&&(this.cancelRenderTimer(),process.nextTick(()=>this.scheduleRender()))),!this.renderRequested&&(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=!0,!this.
410
+ immediateRenderScheduled&&(this.immediateRenderScheduled=!0,process.nextTick(()=>{this.immediateRenderScheduled=!1,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),this.renderRequested=!1,this.lastRenderAt=renderClock(),this.renderFrame())}))}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let elapsed=renderClock()-this.lastRenderAt,spacing=this.nextFrameUnspaced||
411
+ this.nextFrameForInput?0:FRAME_SPACING_FACTOR*this.lastFrameDuration,delay=Math.max(0,Math.max(_TuiBase.MIN_RENDER_INTERVAL_MS,spacing)-elapsed);this.renderTimer=setTimeout(()=>this.renderTimedFrame(),delay)}renderTimedFrame(){this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=renderClock(),this.renderFrame(),this.renderRequested&&this.scheduleRender())}handleTerminalInput(data){if(this.consumeTerminalColorResponse(data)||this.consumeTerminalColorSchemeReport(
412
+ data))return;if(this.inputListeners.size>0){let current=data;for(let listener of this.inputListeners){let result=listener(current);if(result?.consume)return;result?.data!==void 0&&(current=result.data)}if(current.length===0)return;data=current}if(this.consumeCellSizeResponse(data))return;if(matchesKey(data,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let focusedOverlay=this.overlayStack.find(o=>o.component===this.focusedComponent);if(focusedOverlay&&!this.isOverlayVisible(focusedOverlay)){
413
+ let topVisible=this.getTopmostVisibleOverlay();topVisible?this.setFocus(topVisible.component):this.setFocusInternal({component:focusedOverlay.preFocus,overlayFocusRestore:"preserve"})}if(!this.overlayStack.some(o=>o.component===this.focusedComponent)){let restoreState=this.getVisibleOverlayFocusRestore();restoreState.status==="eligible"?this.setFocus(restoreState.overlay.component):restoreState.status==="blocked"&&restoreState.blockedBy!==this.focusedComponent&&(restoreState.resume.status==="res\
414
+ tore-overlay"?this.setFocus(restoreState.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(restoreState.resume.target)))}if(this.focusedComponent?.handleInput){if(isKeyRelease(data)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(data),this.requestImmediateRender()}}consumeTerminalColorResponse(data){let query=this.pendingTerminalColorQueries[0];if(!query)return!1;if(DEVICE_ATTRIBUTES_RESPONSE_PATTERN.test(data))return this.pendingTerminalColorQueries.
415
+ shift(),this.completeTerminalColorQuery(query),!0;let response=parseOscColorResponse(data);if(!response)return!1;let{target,rgb}=response,key=String(target);return!query.deliver||query.replied.has(key)||(query.replied.add(key),target==="foreground"?query.foreground=rgb:target==="background"?query.background=rgb:target<TERMINAL_PALETTE_SIZE&&(query.palette[target]=rgb),query.replied.size===TERMINAL_COLOR_REPLY_COUNT&&this.completeTerminalColorQuery(query)),!0}terminalColorQueryResult(query){let palette=query.
416
+ palette.every(color=>color!==void 0)?query.palette:void 0;return{foreground:query.foreground,background:query.background,palette}}completeTerminalColorQuery(query){let deliver=query.deliver;query.deliver=void 0,clearTimeout(query.timer),deliver?.(this.terminalColorQueryResult(query))}consumeTerminalColorSchemeReport(data){let scheme=parseTerminalColorSchemeReport(data);if(!scheme)return!1;for(let listener of this.terminalColorSchemeListeners)listener(scheme);return!0}consumeCellSizeResponse(data){
417
+ let match=data.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!match)return!1;let heightPx=parseInt(match[1],10),widthPx=parseInt(match[2],10);return heightPx<=0||widthPx<=0||(setCellDimensions({widthPx,heightPx}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(options,overlayHeight,termWidth,termHeight){let opt=options??{},margin=typeof opt.margin=="number"?{top:opt.margin,right:opt.margin,bottom:opt.margin,left:opt.margin}:opt.margin??{},marginTop=Math.max(0,margin.top??0),marginRight=Math.
418
+ max(0,margin.right??0),marginBottom=Math.max(0,margin.bottom??0),marginLeft=Math.max(0,margin.left??0),availWidth=Math.max(1,termWidth-marginLeft-marginRight),availHeight=Math.max(1,termHeight-marginTop-marginBottom),width=parseSizeValue(opt.width,termWidth)??Math.min(80,availWidth);opt.minWidth!==void 0&&(width=Math.max(width,opt.minWidth)),width=Math.max(1,Math.min(width,availWidth));let maxHeight=parseSizeValue(opt.maxHeight,termHeight);maxHeight!==void 0&&(maxHeight=Math.max(1,Math.min(maxHeight,
419
+ availHeight)));let effectiveHeight=maxHeight!==void 0?Math.min(overlayHeight,maxHeight):overlayHeight,row,col;if(opt.row!==void 0)if(typeof opt.row=="string"){let match=opt.row.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxRow=Math.max(0,availHeight-effectiveHeight),percent=parseFloat(match[1])/100;row=marginTop+Math.floor(maxRow*percent)}else row=this.resolveAnchorRow("center",effectiveHeight,availHeight,marginTop)}else row=opt.row;else{let anchor=opt.anchor??"center";row=this.resolveAnchorRow(anchor,
420
+ effectiveHeight,availHeight,marginTop)}if(opt.col!==void 0)if(typeof opt.col=="string"){let match=opt.col.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxCol=Math.max(0,availWidth-width),percent=parseFloat(match[1])/100;col=marginLeft+Math.floor(maxCol*percent)}else col=this.resolveAnchorCol("center",width,availWidth,marginLeft)}else col=opt.col;else{let anchor=opt.anchor??"center";col=this.resolveAnchorCol(anchor,width,availWidth,marginLeft)}return opt.offsetY!==void 0&&(row+=opt.offsetY),opt.offsetX!==
421
+ void 0&&(col+=opt.offsetX),row=Math.max(marginTop,Math.min(row,termHeight-marginBottom-effectiveHeight)),col=Math.max(marginLeft,Math.min(col,termWidth-marginRight-width)),{width,row,col,maxHeight}}resolveAnchorRow(anchor,height,availHeight,marginTop){switch(anchor){case"top-left":case"top-center":case"top-right":return marginTop;case"bottom-left":case"bottom-center":case"bottom-right":return marginTop+availHeight-height;case"left-center":case"center":case"right-center":return marginTop+Math.floor(
422
+ (availHeight-height)/2)}}resolveAnchorCol(anchor,width,availWidth,marginLeft){switch(anchor){case"top-left":case"left-center":case"bottom-left":return marginLeft;case"top-right":case"right-center":case"bottom-right":return marginLeft+availWidth-width;case"top-center":case"center":case"bottom-center":return marginLeft+Math.floor((availWidth-width)/2)}}compositeOverlays(lines,termWidth,termHeight){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],lines;let result=[...lines];for(let entry of this.
423
+ overlayStack)entry.bounds=void 0;let rendered=[],minLinesNeeded=result.length,visibleEntries=this.overlayStack.filter(e=>this.isOverlayVisible(e));visibleEntries.sort((a3,b)=>a3.focusOrder-b.focusOrder);for(let entry of visibleEntries){let{component,options}=entry,{width,maxHeight}=this.resolveOverlayLayout(options,0,termWidth,termHeight),overlayLines=this.resolveFakeCursors(component.render(width));maxHeight!==void 0&&overlayLines.length>maxHeight&&(overlayLines=overlayLines.slice(0,maxHeight));
424
+ let{row,col}=this.resolveOverlayLayout(options,overlayLines.length,termWidth,termHeight);entry.bounds={row,col,width,height:overlayLines.length},rendered.push({entry,overlayLines,row,col,w:width}),minLinesNeeded=Math.max(minLinesNeeded,row+overlayLines.length)}this.renderedOverlayLayouts=rendered.map(({entry,row,col,w:w2,overlayLines})=>({entry,row,col,width:w2,height:overlayLines.length}));let workingHeight=Math.max(result.length,termHeight,minLinesNeeded);for(;result.length<workingHeight;)result.
425
+ push("");let viewportStart=Math.max(0,workingHeight-termHeight);for(let{overlayLines,row,col,w:w2}of rendered)for(let i=0;i<overlayLines.length;i++){let idx=viewportStart+row+i;if(idx>=0&&idx<result.length){let truncatedOverlayLine=visibleWidth(overlayLines[i])>w2?sliceByColumn(overlayLines[i],0,w2,!0):overlayLines[i];result[idx]=this.compositeLineAt(result[idx],truncatedOverlayLine,col,w2,termWidth)}}return result}applyLineResets(lines){let reset=SEGMENT_RESET;for(let i=0;i<lines.length;i++){let line=lines[i];
426
+ isImageLine(line)||(lines[i]=normalizeTerminalOutput(line)+reset)}return lines}compositeLineAt(baseLine,overlayLine,startCol,overlayWidth,totalWidth){return compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth)}extractCursorPosition(lines,height){let viewportTop=Math.max(0,lines.length-height);for(let row=lines.length-1;row>=viewportTop;row--){let line=lines[row],markerIndex=line.indexOf(CURSOR_MARKER);if(markerIndex!==-1){let beforeMarker=line.slice(0,markerIndex),col=visibleWidth(
427
+ beforeMarker);return lines[row]=line.slice(0,markerIndex)+line.slice(markerIndex+CURSOR_MARKER.length),{row,col}}}return null}resolveFakeCursors(lines){return lines.map(line=>line.includes(FAKE_CURSOR_START)?(this.showHardwareCursor?line.replace(FOCUSED_FAKE_CURSOR,"$1$2"):line).replaceAll(FAKE_CURSOR_START,"\x1B[7m").replaceAll(FAKE_CURSOR_END,"\x1B[27m"):line)}queryTerminalColors({timeoutMs,onLateReply}){return new Promise(resolve=>{let query={palette:Array.from({length:TERMINAL_PALETTE_SIZE},
428
+ ()=>{}),replied:new Set,deliver:resolve,timer:void 0};query.timer=setTimeout(()=>{query.deliver=onLateReply,resolve(this.terminalColorQueryResult(query))},timeoutMs),this.pendingTerminalColorQueries.push(query),this.terminal.write(TERMINAL_COLOR_QUERY)})}};var Box=class{childList=[];paddingX;paddingY;bgFn;backgroundReported=!1;cache;rendered;emptyLines=[];constructor(paddingX=1,paddingY=1,bgFn){this.paddingX=paddingX,this.paddingY=paddingY,this.bgFn=bgFn}get children(){return reportRenderChange(this),this.childList}set children(children){this.childList=children,reportRenderChange(this)}ownChildren(){return Object.hasOwn(this,"children")?this.children:this.childList}addChild(component){this.ownChildren().push(component),this.invalidateCache()}removeChild(component){
429
+ let children=this.ownChildren(),index=children.indexOf(component);index!==-1&&(children.splice(index,1),this.invalidateCache())}clear(){Object.hasOwn(this,"children")?this.children=[]:this.childList=[],this.invalidateCache()}setBgFn(bgFn){this.bgFn=bgFn,reportRenderChange(this)}setBackgroundReported(reported){this.backgroundReported=reported,reportRenderChange(this)}setPaddingX(paddingX){this.paddingX!==paddingX&&(this.paddingX=paddingX,this.invalidateCache())}invalidateCache(){this.cache=void 0,
430
+ this.rendered=void 0,reportRenderChange(this)}invalidate(){this.invalidateCache();for(let child of this.ownChildren())child.invalidate?.()}handleMouse(event){let contentWidth=Math.max(1,event.width-this.paddingX*2),contentY=event.y-this.paddingY,contentX=event.x-this.paddingX;if(contentY<0||contentX<0||contentX>=contentWidth)return;let rendered=this.rendered?.width===contentWidth?this.rendered:void 0,children=rendered?.children??this.ownChildren(),childY=0;for(let i=0;i<children.length;i++){let child=children[i],
431
+ childHeight=rendered?rendered.heights[i]:child.render(contentWidth).length;if(contentY>=childY&&contentY<childY+childHeight)return dispatchMouseEvent(child,{...event,x:contentX,y:contentY-childY,width:contentWidth,height:childHeight});childY+=childHeight}}render(width){let children=this.ownChildren();if(children.length===0)return setSubtreeReportsChanges(this,children===this.childList),this.emptyLines;let contentWidth=Math.max(1,width-this.paddingX*2),leftPad=" ".repeat(this.paddingX),rendered=renderChildren(
432
+ children,contentWidth,this.rendered);this.rendered=rendered;let reports=children===this.childList&&(this.bgFn===void 0||this.backgroundReported);for(let child of children)setRenderOwner(child,this),reportsChanges(child)||(reports=!1);setSubtreeReportsChanges(this,reports);let childLines=rendered.lines;if(childLines.length===0)return this.emptyLines;let bgSample=this.bgFn?this.bgFn("test"):void 0,cache=this.cache&&this.cache.width===width&&this.cache.bgSample===bgSample?this.cache:void 0;if(cache?.
433
+ childLines===childLines)return cache.lines;let result=[],reused=cache!==void 0&&cache.childLines.length===childLines.length;for(let i=0;i<this.paddingY;i++)result.push(cache?cache.lines[i]:this.applyBg("",width));for(let i=0;i<childLines.length;i++){let line=childLines[i];cache!==void 0&&i<cache.childLines.length&&cache.childLines[i]===line?result.push(cache.lines[this.paddingY+i]):(reused=!1,result.push(this.applyBg(leftPad+line,width)))}for(let i=0;i<this.paddingY;i++)result.push(cache?cache.lines[cache.
434
+ lines.length-this.paddingY+i]:this.applyBg("",width));return reused?(cache.childLines=childLines,cache.lines):(flattenLines(result),this.cache={childLines,width,bgSample,lines:result},result)}applyBg(line,width){let visLen=visibleWidth(line),padNeeded=Math.max(0,width-visLen),padded=line+" ".repeat(padNeeded);return this.bgFn?this.bgFn(padded):padded}};markStableRender(Box);markReportsChanges(Box);var Text=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(text="",paddingX=1,paddingY=1,customBgFn){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.customBgFn=customBgFn}setText(text){this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,reportRenderChange(this)}setCustomBgFn(customBgFn){this.customBgFn=customBgFn,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,reportRenderChange(this)}setPaddingX(paddingX){
435
+ this.paddingX=paddingX,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,reportRenderChange(this)}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;if(!this.text||this.text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=this.text.replace(/\t/g," "),paddingX=Math.min(this.paddingX,Math.max(0,Math.
436
+ floor((width-1)/2))),contentWidth=Math.max(1,width-paddingX*2),wrappedLines=wrapTextWithAnsi(normalizedText,contentWidth),leftMargin=" ".repeat(paddingX),rightMargin=" ".repeat(paddingX),contentLines=[];for(let line of wrappedLines){let lineWithMargins=leftMargin+line+rightMargin;if(this.customBgFn)contentLines.push(applyBackgroundToLine(lineWithMargins,width,this.customBgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);contentLines.push(lineWithMargins+
437
+ " ".repeat(paddingNeeded))}}let emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=this.customBgFn?applyBackgroundToLine(emptyLine,width,this.customBgFn):emptyLine;emptyLines.push(line)}let result=[...emptyLines,...contentLines,...emptyLines];return flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};markStableRender(Text);markReportsChanges(Text);var DEFAULT_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],DEFAULT_INTERVAL_MS=80,Loader=class extends Text{frames=[...DEFAULT_FRAMES];intervalMs=DEFAULT_INTERVAL_MS;currentFrame=0;intervalId=null;ui=null;renderIndicatorVerbatim=!1;spinnerColorFn;messageColorFn;message="Loading...";displayText="";constructor(ui,spinnerColorFn,messageColorFn,message="Loading...",indicator){super("",1,0),this.ui=ui,this.spinnerColorFn=spinnerColorFn,this.messageColorFn=
401
438
  messageColorFn,this.message=message,this.setIndicator(indicator)}render(width){return["",...super.render(width)]}start(){this.updateDisplay(),this.restartAnimation()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}setText(text){this.displayText=text,super.setText(text)}getDisplayText(){return this.displayText}setMessage(message){this.message=message,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}setIndicator(indicator){this.renderIndicatorVerbatim=
402
439
  indicator!==void 0,this.frames=indicator?.frames!==void 0?[...indicator.frames]:[...DEFAULT_FRAMES],this.intervalMs=indicator?.intervalMs&&indicator.intervalMs>0?indicator.intervalMs:DEFAULT_INTERVAL_MS,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 frame=this.frames[this.currentFrame]??"";return this.
403
440
  renderIndicatorVerbatim?frame:this.spinnerColorFn(frame)}updateDisplay(){let renderedFrame=this.getRenderedIndicator(),indicator=renderedFrame.length>0?`${renderedFrame} `:"";this.setText(`${indicator}${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender()}};var CancellableLoader=class extends Loader{abortController=new AbortController;onAbort;get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(data){getKeybindings().matches(data,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var KillRing=class{ring=[];push(text,opts){if(text)if(opts.accumulate&&this.ring.length>0){let last=this.ring.pop();this.ring.push(opts.prepend?text+last:last+text)}else this.ring.push(text)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let last=this.ring.pop();this.ring.unshift(last)}}get length(){return this.ring.length}};var UndoStack=class{stack=[];clone;constructor(clone=state=>structuredClone(state)){this.clone=clone}push(state){this.stack.push(this.clone(state))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};var wordSegmenter2=getWordSegmenter();function findWordBackward(text,cursor,options){if(cursor<=0)return 0;let textBeforeCursor=text.slice(0,cursor),segmentFn=options?.segment,isAtomic=options?.isAtomicSegment,segments=segmentFn?[...segmentFn(textBeforeCursor)]:[...wordSegmenter2.segment(textBeforeCursor)],newCursor=cursor;for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||
@@ -417,32 +454,41 @@ this.theme.selectedText(`${prefix}${truncatedValue}`):prefix+truncatedValue}getP
417
454
  minPrimaryColumnWidth??DEFAULT_PRIMARY_COLUMN_WIDTH;return{min:Math.max(1,Math.min(rawMin,rawMax)),max:Math.max(1,Math.max(rawMin,rawMax))}}truncatePrimary(item,isSelected,maxWidth,columnWidth){let displayValue=this.getDisplayValue(item),truncatedValue=this.layout.truncatePrimary?this.layout.truncatePrimary({text:displayValue,maxWidth,columnWidth,item,isSelected}):truncateToWidth(displayValue,maxWidth,"");return truncateToWidth(truncatedValue,maxWidth,"")}getDisplayValue(item){return item.label||
418
455
  item.value}notifySelectionChange(){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelectionChange&&this.onSelectionChange(selectedItem)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};var graphemeSegmenter2=getGraphemeSegmenter(),wordSegmenter3=getWordSegmenter(),PASTE_MARKER_REGEX=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,PASTE_MARKER_SINGLE=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function isPasteMarker(segment){return segment.length>=10&&PASTE_MARKER_SINGLE.test(segment)}function segmentWithMarkers(text,baseSegmenter,validIds){if(validIds.size===0||!text.includes("[paste #"))return baseSegmenter.segment(text);let markers=[];for(let m of text.matchAll(PASTE_MARKER_REGEX)){
419
456
  let id=Number.parseInt(m[1],10);validIds.has(id)&&markers.push({start:m.index,end:m.index+m[0].length})}if(markers.length===0)return baseSegmenter.segment(text);let baseSegments=baseSegmenter.segment(text),result=[],markerIdx=0;for(let seg of baseSegments){for(;markerIdx<markers.length&&markers[markerIdx].end<=seg.index;)markerIdx++;let marker=markerIdx<markers.length?markers[markerIdx]:null;if(marker&&seg.index>=marker.start&&seg.index<marker.end){if(seg.index===marker.start){let markerText=text.
420
- slice(marker.start,marker.end);result.push({segment:markerText,index:marker.start,input:text})}}else result.push(seg)}return result}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(visibleWidth(line)<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],segments=preSegmented??[...graphemeSegmenter2.segment(line)],currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0;for(let i=0;i<segments.length;i++){
421
- let seg=segments[i],grapheme=seg.segment,gWidth=visibleWidth(grapheme),charIndex=seg.index,isWs=!isPasteMarker(grapheme)&&isWhitespaceChar(grapheme);if(currentWidth+gWidth>maxWidth&&(wrapOppIndex>=0&&currentWidth-wrapOppWidth+gWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<charIndex&&(chunks.push({text:line.slice(chunkStart,charIndex),startIndex:chunkStart,endIndex:charIndex}),
422
- chunkStart=charIndex,currentWidth=0),wrapOppIndex=-1),gWidth>maxWidth&&preSegmented){let subChunks=wordWrapLine(grapheme,maxWidth);for(let j2=0;j2<subChunks.length-1;j2++){let sc=subChunks[j2];chunks.push({text:sc.text,startIndex:charIndex+sc.startIndex,endIndex:charIndex+sc.endIndex})}let last=subChunks[subChunks.length-1];chunkStart=charIndex+last.startIndex,currentWidth=visibleWidth(last.text),wrapOppIndex=-1;continue}currentWidth+=gWidth;let next=segments[i+1];if(isWs&&next&&(isPasteMarker(next.
423
- segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=next.index,wrapOppWidth=currentWidth;else if(!isWs&&next&&!isWhitespaceChar(next.segment)){let isCjk=!isPasteMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isPasteMarker(next.segment)&&cjkBreakRegex.test(next.segment);(isCjk||nextIsCjk)&&(wrapOppIndex=next.index,wrapOppWidth=currentWidth)}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:line.length}),chunks}function cloneEditorSnapshot(snapshot){return{
424
- state:{lines:[...snapshot.state.lines],cursorLine:snapshot.state.cursorLine,cursorCol:snapshot.state.cursorCol},pastes:new Map(snapshot.pastes),pasteCounter:snapshot.pasteCounter}}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#"],unquotedAutocompleteSuffixRegex=new RegExp(`(?:(?!${autocompleteSeparatorRegex.source}).)*`,"u"),autocompleteTokenStartSource=`${autocompleteBoundaryRegex.
425
- source}[([{<\`]*`;function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`${autocompleteTokenStartSource}(?:@"[^"]*|[${triggerCharacters.map(escapeCharacterClass).join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!=="@").map(escapeCharacterClass);return new RegExp(`${autocompleteTokenStartSource}\
426
- (?:@(?:"[^"]*|${unquotedAutocompleteSuffixRegex.source})|[${escapedWithoutAt.join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function createScrollBorder(direction,hiddenLineCount,width){let availableWidth=Math.max(0,width),label=` ${direction} ${hiddenLineCount} more `,labelWidth=visibleWidth(label);if(labelWidth+2<=availableWidth){let leftWidth=Math.floor((availableWidth-labelWidth)/2);return"\u2500".repeat(leftWidth)+label+"\u2500".repeat(availableWidth-leftWidth-labelWidth)}let indicator=`\
427
- \u2500\u2500\u2500 ${direction} ${hiddenLineCount} more `,remaining=availableWidth-visibleWidth(indicator);if(remaining>=0)return indicator+"\u2500".repeat(remaining);let ellipsis="...".slice(0,availableWidth),indicatorWidth=availableWidth-visibleWidth(ellipsis);return sliceByColumn(indicator,0,indicatorWidth,!0)+ellipsis}var Editor=class{state={lines:[""],cursorLine:0,cursorCol:0};focused=!1;tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[
457
+ slice(marker.start,marker.end);result.push({segment:markerText,index:marker.start,input:text})}}else result.push(seg)}return result}function graphemeAt(text,index){let code=text.charCodeAt(index);if(code>=55296&&code<=56319){let next=text.charCodeAt(index+1);if(next>=56320&&next<=57343)return graphemeSegmenter2.segment(text).containing(index+1)}return graphemeSegmenter2.segment(text).containing(index)}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,
458
+ endIndex:0}];if(!preSegmented){let standaloneWidth=standaloneTextWidth(line);if(canWrapStandalone(line,standaloneWidth,maxWidth))return wordWrapStandaloneLine(line,maxWidth,standaloneWidth)}if(visibleWidth(line)<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],segments=preSegmented??[...graphemeSegmenter2.segment(line)],currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0;for(let i=0;i<segments.length;i++){let seg=segments[i],grapheme=seg.segment,gWidth=visibleWidth(
459
+ grapheme),charIndex=seg.index,isWs=!isPasteMarker(grapheme)&&isWhitespaceChar(grapheme);if(currentWidth+gWidth>maxWidth&&(wrapOppIndex>=0&&currentWidth-wrapOppWidth+gWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<charIndex&&(chunks.push({text:line.slice(chunkStart,charIndex),startIndex:chunkStart,endIndex:charIndex}),chunkStart=charIndex,currentWidth=0),wrapOppIndex=
460
+ -1),gWidth>maxWidth&&preSegmented){let subChunks=wordWrapLine(grapheme,maxWidth);for(let j2=0;j2<subChunks.length-1;j2++){let sc=subChunks[j2];chunks.push({text:sc.text,startIndex:charIndex+sc.startIndex,endIndex:charIndex+sc.endIndex})}let last=subChunks[subChunks.length-1];chunkStart=charIndex+last.startIndex,currentWidth=visibleWidth(last.text),wrapOppIndex=-1;continue}currentWidth+=gWidth;let next=segments[i+1];if(isWs&&next&&(isPasteMarker(next.segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=
461
+ next.index,wrapOppWidth=currentWidth;else if(!isWs&&next&&!isWhitespaceChar(next.segment)){let isCjk=!isPasteMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isPasteMarker(next.segment)&&cjkBreakRegex.test(next.segment);(isCjk||nextIsCjk)&&(wrapOppIndex=next.index,wrapOppWidth=currentWidth)}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:line.length}),chunks}function standaloneCharWidth(code){return code<12288?code>=32&&code<=126||code>=160&&code<=767&&code!==
462
+ 173||code>=8208&&code<=8231||code>=8592&&code<=8959||code>=9472&&code<=9724?1:0:code<=12329||code>=12353&&code<=12438||code>=12445&&code<=12447||code>=12449&&code<=12543||code>=13312&&code<=19903||code>=19968&&code<=40959||code>=44032&&code<=55203||code>=65281&&code<=65376||code>=65504&&code<=65510?2:0}function standaloneTextWidth(text){let width=0;for(let i=0;i<text.length;i++){let charWidth=standaloneCharWidth(text.charCodeAt(i));if(charWidth===0)return-1;width+=charWidth}return width}function canWrapStandalone(line,lineWidth,maxWidth){
463
+ return lineWidth>=0&&(maxWidth>=2||lineWidth===line.length)}function editorLineWidth(line){let width=standaloneTextWidth(line);return width>=0?width:visibleWidth(line)}function isStandaloneWhitespace(line,i,code){return code===32||code>126&&isWhitespaceChar(line[i])}function wordWrapStandaloneLine(line,maxWidth,lineWidth){let length=line.length;if(length===0||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(lineWidth<=maxWidth)return[{text:line,startIndex:0,endIndex:length}];let chunks=[],
464
+ currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0,code=line.charCodeAt(0),isWs=isStandaloneWhitespace(line,0,code);for(let i=0;i<length;i++){let charWidth=code<12288?1:2;if(currentWidth+charWidth>maxWidth&&(wrapOppIndex>=0&&currentWidth-wrapOppWidth+charWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<i&&(chunks.push({text:line.slice(chunkStart,i),startIndex:chunkStart,
465
+ endIndex:i}),chunkStart=i,currentWidth=0),wrapOppIndex=-1),currentWidth+=charWidth,i+1<length){let nextCode=line.charCodeAt(i+1),nextIsWs=isStandaloneWhitespace(line,i+1,nextCode);isWs?nextIsWs||(wrapOppIndex=i+1,wrapOppWidth=currentWidth):!nextIsWs&&(code>126||nextCode>126)&&(cjkBreakRegex.test(line[i])||cjkBreakRegex.test(line[i+1]))&&(wrapOppIndex=i+1,wrapOppWidth=currentWidth),code=nextCode,isWs=nextIsWs}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:length}),
466
+ chunks}function cloneEditorSnapshot(snapshot){return{state:{lines:[...snapshot.state.lines],cursorLine:snapshot.state.cursorLine,cursorCol:snapshot.state.cursorCol},pastes:new Map(snapshot.pastes),pasteCounter:snapshot.pasteCounter}}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#"],unquotedAutocompleteSuffixRegex=new RegExp(`(?:(?!${autocompleteSeparatorRegex.source}).)\
467
+ *`,"u"),autocompleteTokenStartSource=`${autocompleteBoundaryRegex.source}[([{<\`]*`;function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`${autocompleteTokenStartSource}(?:@"[^"]*|[${triggerCharacters.map(escapeCharacterClass).join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!==
468
+ "@").map(escapeCharacterClass);return new RegExp(`${autocompleteTokenStartSource}(?:@(?:"[^"]*|${unquotedAutocompleteSuffixRegex.source})|[${escapedWithoutAt.join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function createScrollBorder(direction,hiddenLineCount,width){let availableWidth=Math.max(0,width),label=` ${direction} ${hiddenLineCount} more `,labelWidth=visibleWidth(label);if(labelWidth+2<=availableWidth){let leftWidth=Math.floor((availableWidth-labelWidth)/2);return"\u2500".repeat(
469
+ leftWidth)+label+"\u2500".repeat(availableWidth-leftWidth-labelWidth)}let indicator=`\u2500\u2500\u2500 ${direction} ${hiddenLineCount} more `,remaining=availableWidth-visibleWidth(indicator);if(remaining>=0)return indicator+"\u2500".repeat(remaining);let ellipsis="...".slice(0,availableWidth),indicatorWidth=availableWidth-visibleWidth(ellipsis);return sliceByColumn(indicator,0,indicatorWidth,!0)+ellipsis}var Editor=class{state={lines:[""],cursorLine:0,cursorCol:0};focused=!1;tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[
428
470
  ...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];autocompleteTriggerPattern=buildTriggerPattern(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=buildDebouncePattern(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 KillRing;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new UndoStack(
429
471
  cloneEditorSnapshot);onSubmit;onChange;disableSubmit=!1;constructor(tui,theme2,options={}){this.tui=tui,this.theme=theme2,this.borderColor=theme2.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}wrapCache={width:-1,pasteIds:"",lines:[]};wrapCacheFor(width){let pasteIds=[...this.
430
- pastes.keys()].join(","),cache=this.wrapCache;return cache.width!==width||cache.pasteIds!==pasteIds?this.wrapCache={width,pasteIds,lines:[]}:cache.lines.length>this.state.lines.length&&(cache.lines.length=this.state.lines.length),this.wrapCache.lines}wrapLine(cache,index,line,width){let known=cache[index];if(known!==void 0&&known.text===line)return known.chunks;let chunks=wordWrapLine(line,width,[...this.segment(line,"grapheme")]);return cache[index]={text:line,chunks},chunks}validPasteIds(){return new Set(
431
- this.pastes.keys())}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter3:graphemeSegmenter2,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(padding){let newPadding=Number.isFinite(padding)?Math.max(0,Math.floor(padding)):0;this.paddingX!==newPadding&&(this.paddingX=newPadding,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(maxVisible){let newMaxVisible=Number.isFinite(maxVisible)?Math.
432
- max(3,Math.min(20,Math.floor(maxVisible))):5;this.autocompleteMaxVisible!==newMaxVisible&&(this.autocompleteMaxVisible=newMaxVisible,this.tui.requestRender())}setAutocompleteProvider(provider){this.cancelAutocomplete(),this.autocompleteProvider=provider,this.setAutocompleteTriggerCharacters(provider.triggerCharacters??[])}addToHistory(text){let trimmed=text.trim();trimmed&&(this.history.length>0&&this.history[0]===trimmed||(this.history.unshift(trimmed),this.history.length>100&&this.history.pop()))}isEditorEmpty(){
433
- return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===0}isOnLastVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===visualLines.length-1}navigateHistory(direction){if(this.lastAction=null,this.history.length===0)return;let newIndex=this.historyIndex-direction;if(!(newIndex<-1||newIndex>=this.history.
434
- length))if(this.historyIndex===-1&&newIndex>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=newIndex,this.historyIndex===-1){let draft=this.historyDraft;this.historyDraft=null,draft?(this.state=draft,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("")}else this.setTextInternal(this.history[this.historyIndex]||"",direction===-1?"start":"end")}exitHistoryBrowsing(){
435
- this.historyIndex=-1,this.historyDraft=null}setTextInternal(text,cursorPlacement="end"){let lines=text.split(`
436
- `);this.state.lines=lines.length===0?[""]:lines,this.state.cursorLine=cursorPlacement==="start"?0:this.state.lines.length-1,this.setCursorCol(cursorPlacement==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}renderTopBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2191",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderBottomBorder(width,hiddenLineCount){
437
- let border=hiddenLineCount>0?createScrollBorder("\u2193",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}render(width){let maxPadding=Math.max(0,Math.floor((width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),contentWidth=Math.max(1,width-paddingX*2),layoutWidth=Math.max(1,contentWidth-(paddingX?0:1));this.lastWidth=layoutWidth;let layoutLines=this.layoutText(layoutWidth),terminalRows=this.tui.terminal.rows,maxVisibleLines=Math.max(5,Math.floor(terminalRows*.3)),
438
- cursorLineIndex=layoutLines.findIndex(line=>line.hasCursor);cursorLineIndex===-1&&(cursorLineIndex=0),cursorLineIndex<this.scrollOffset?this.scrollOffset=cursorLineIndex:cursorLineIndex>=this.scrollOffset+maxVisibleLines&&(this.scrollOffset=cursorLineIndex-maxVisibleLines+1);let maxScrollOffset=Math.max(0,layoutLines.length-maxVisibleLines);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,maxScrollOffset));let visibleLines=layoutLines.slice(this.scrollOffset,this.scrollOffset+maxVisibleLines);
439
- this.renderedVisibleLineCount=visibleLines.length;let result=[],leftPadding=" ".repeat(paddingX),rightPadding=leftPadding;result.push(this.renderTopBorder(width,this.scrollOffset));let emitCursorMarker=this.focused;for(let layoutLine of visibleLines){let displayText=layoutLine.text,lineVisibleWidth=visibleWidth(layoutLine.text),cursorInPadding=!1;if(layoutLine.hasCursor&&layoutLine.cursorPos!==void 0){let before=displayText.slice(0,layoutLine.cursorPos),after=displayText.slice(layoutLine.cursorPos),
440
- marker=emitCursorMarker?CURSOR_MARKER:"";if(after.length>0){let firstGrapheme=[...this.segment(after,"grapheme")][0]?.segment||"",restAfter=after.slice(firstGrapheme.length),cursor=renderFakeCursor(firstGrapheme);displayText=before+marker+cursor+restAfter}else{let cursor=renderFakeCursor(" ");displayText=before+marker+cursor,lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>contentWidth&&paddingX>0&&(cursorInPadding=!0)}}let padding=" ".repeat(Math.max(0,contentWidth-lineVisibleWidth)),lineRightPadding=cursorInPadding?
441
- rightPadding.slice(1):rightPadding;result.push(`${leftPadding}${displayText}${padding}${lineRightPadding}`)}let linesBelow=layoutLines.length-(this.scrollOffset+visibleLines.length);if(result.push(this.renderBottomBorder(width,linesBelow)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let autocompleteResult=this.autocompleteList.render(contentWidth);this.renderedAutocompleteHeight=autocompleteResult.length;for(let line of autocompleteResult){let lineWidth=visibleWidth(
442
- line),linePadding=" ".repeat(Math.max(0,contentWidth-lineWidth));result.push(`${leftPadding}${line}${linePadding}${rightPadding}`)}}return result}handleMouse(event){let autocompleteStartRow=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&event.y>=autocompleteStartRow&&event.y<autocompleteStartRow+this.renderedAutocompleteHeight){let maxPadding2=Math.max(0,Math.floor((event.width-1)/2)),paddingX2=Math.min(this.paddingX,maxPadding2),contentWidth=Math.max(1,event.width-
443
- paddingX2*2),result=this.autocompleteList.handleMouse?.({...event,x:event.x-paddingX2,y:event.y-autocompleteStartRow,width:contentWidth,height:this.renderedAutocompleteHeight});return result?{...result,focus:!0}:void 0}if(event.type!=="click"||event.button!=="left")return;if(event.y<=0||event.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let visualLines=this.buildVisualLineMap(this.lastWidth),visualLineIndex=this.scrollOffset+event.y-1,visualLine=visualLines[visualLineIndex];if(!visualLine)
444
- return{handled:!0,focus:!0};let logicalLine=this.state.lines[visualLine.logicalLine]??"",chunkEnd=visualLine.startCol+visualLine.length,chunk=logicalLine.slice(visualLine.startCol,chunkEnd),maxPadding=Math.max(0,Math.floor((event.width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),targetColumn=Math.max(0,event.x-paddingX),visibleColumn=0,targetIndex=chunk.length,lastGraphemeIndex=0;for(let grapheme of this.segment(chunk,"grapheme")){let nextColumn=visibleColumn+visibleWidth(grapheme.segment);
445
- if(lastGraphemeIndex=grapheme.index,targetColumn<nextColumn){targetIndex=grapheme.index;break}visibleColumn=nextColumn}return!(visualLineIndex===visualLines.length-1||visualLines[visualLineIndex+1]?.logicalLine!==visualLine.logicalLine)&&targetIndex===chunk.length&&chunk.length>0&&(targetIndex=lastGraphemeIndex),this.state.cursorLine=visualLine.logicalLine,this.setCursorCol(visualLine.startCol+targetIndex),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),
472
+ pastes.keys()].join(","),cache=this.wrapCache;return cache.width!==width||cache.pasteIds!==pasteIds?this.wrapCache={width,pasteIds,lines:[]}:cache.lines.length>this.state.lines.length&&(cache.lines.length=this.state.lines.length),this.wrapCache.lines}wrapLine(cache,index,line,width){let known=cache[index];if(known!==void 0&&known.text===line)return known.chunks;let standaloneWidth=this.hasNoPasteMarkers(line)?standaloneTextWidth(line):-1,chunks=canWrapStandalone(line,standaloneWidth,width)?wordWrapStandaloneLine(
473
+ line,width,standaloneWidth):wordWrapLine(line,width,[...this.segment(line,"grapheme")]);return cache[index]={text:line,chunks},chunks}validPasteIds(){return new Set(this.pastes.keys())}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter3:graphemeSegmenter2,this.validPasteIds())}hasNoPasteMarkers(text){return this.pastes.size===0||!text.includes("[paste #")}firstGrapheme(text){return this.hasNoPasteMarkers(text)?graphemeAt(text,0):[...this.segment(text,"grapheme")][0]}lastGrapheme(text){
474
+ if(this.hasNoPasteMarkers(text))return graphemeAt(text,text.length-1);let graphemes=[...this.segment(text,"grapheme")];return graphemes[graphemes.length-1]}graphemeContaining(text,index){if(!(index<0||index>=text.length)){if(this.hasNoPasteMarkers(text))return graphemeAt(text,index);for(let seg of this.segment(text,"grapheme")){if(seg.index>index)break;if(index<seg.index+seg.segment.length)return seg}}}getPaddingX(){return this.paddingX}setPaddingX(padding){let newPadding=Number.isFinite(padding)?
475
+ Math.max(0,Math.floor(padding)):0;this.paddingX!==newPadding&&(this.paddingX=newPadding,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(maxVisible){let newMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5;this.autocompleteMaxVisible!==newMaxVisible&&(this.autocompleteMaxVisible=newMaxVisible,this.tui.requestRender())}setAutocompleteProvider(provider){this.cancelAutocomplete(),this.autocompleteProvider=
476
+ provider,this.setAutocompleteTriggerCharacters(provider.triggerCharacters??[])}addToHistory(text){let trimmed=text.trim();trimmed&&(this.history.length>0&&this.history[0]===trimmed||(this.history.unshift(trimmed),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===0}isOnLastVisualLine(){let visualLines=this.
477
+ buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===visualLines.length-1}navigateHistory(direction){if(this.lastAction=null,this.history.length===0)return;let newIndex=this.historyIndex-direction;if(!(newIndex<-1||newIndex>=this.history.length))if(this.historyIndex===-1&&newIndex>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=newIndex,this.historyIndex===-1){let draft=this.historyDraft;this.historyDraft=null,draft?(this.
478
+ state=draft,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("")}else this.setTextInternal(this.history[this.historyIndex]||"",direction===-1?"start":"end")}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(text,cursorPlacement="end"){let lines=text.split(`
479
+ `);this.state.lines=lines.length===0?[""]:lines,this.state.cursorLine=cursorPlacement==="start"?0:this.state.lines.length-1,this.setCursorCol(cursorPlacement==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){this.renderedText=void 0}renderTopBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2191",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderBottomBorder(width,hiddenLineCount){
480
+ let border=hiddenLineCount>0?createScrollBorder("\u2193",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderedText;isRenderedText(known,width,terminalRows,pasteIds){let lines=this.state.lines;if(known.width!==width||known.paddingX!==this.paddingX||known.terminalRows!==terminalRows||known.focused!==this.focused||known.pasteIds!==pasteIds||known.cursorLine!==this.state.cursorLine||known.cursorCol!==this.state.cursorCol||known.scrollOffset!==this.scrollOffset||known.
481
+ lines.length!==lines.length)return!1;for(let i=0;i<lines.length;i++)if(known.lines[i]!==lines[i])return!1;return!0}render(width){let maxPadding=Math.max(0,Math.floor((width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),contentWidth=Math.max(1,width-paddingX*2),layoutWidth=Math.max(1,contentWidth-(paddingX?0:1));this.lastWidth=layoutWidth;let terminalRows=this.tui.terminal.rows,showAutocomplete=!!(this.autocompleteState&&this.autocompleteList),known=this.renderedText;if(!showAutocomplete&&known!==
482
+ void 0){let pasteIds=this.pastes.size===0?"":[...this.pastes.keys()].join(",");if(this.isRenderedText(known,width,terminalRows,pasteIds)){this.renderedVisibleLineCount=known.visibleLineCount,this.renderedAutocompleteHeight=0;let top=this.renderTopBorder(width,this.scrollOffset),bottom=this.renderBottomBorder(width,known.linesBelow),result2=known.result;if(top===result2[0]&&bottom===result2[result2.length-1])return result2.slice();let lines=[top,...known.textLines,bottom];return known.result=lines,
483
+ lines.slice()}}this.renderedText=void 0;let layoutLines=this.layoutText(layoutWidth),maxVisibleLines=Math.max(5,Math.floor(terminalRows*.3)),cursorLineIndex=layoutLines.findIndex(line=>line.hasCursor);cursorLineIndex===-1&&(cursorLineIndex=0),cursorLineIndex<this.scrollOffset?this.scrollOffset=cursorLineIndex:cursorLineIndex>=this.scrollOffset+maxVisibleLines&&(this.scrollOffset=cursorLineIndex-maxVisibleLines+1);let maxScrollOffset=Math.max(0,layoutLines.length-maxVisibleLines);this.scrollOffset=
484
+ Math.max(0,Math.min(this.scrollOffset,maxScrollOffset));let visibleLines=layoutLines.slice(this.scrollOffset,this.scrollOffset+maxVisibleLines);this.renderedVisibleLineCount=visibleLines.length;let result=[],leftPadding=" ".repeat(paddingX),rightPadding=leftPadding;result.push(this.renderTopBorder(width,this.scrollOffset));let emitCursorMarker=this.focused;for(let layoutLine of visibleLines){let displayText=layoutLine.text,lineVisibleWidth=visibleWidth(layoutLine.text),cursorInPadding=!1;if(layoutLine.
485
+ hasCursor&&layoutLine.cursorPos!==void 0){let before=displayText.slice(0,layoutLine.cursorPos),after=displayText.slice(layoutLine.cursorPos),marker=emitCursorMarker?CURSOR_MARKER:"";if(after.length>0){let firstGrapheme=this.firstGrapheme(after)?.segment||"",restAfter=after.slice(firstGrapheme.length),cursor=renderFakeCursor(firstGrapheme);displayText=before+marker+cursor+restAfter}else{let cursor=renderFakeCursor(" ");displayText=before+marker+cursor,lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>
486
+ contentWidth&&paddingX>0&&(cursorInPadding=!0)}}let padding=" ".repeat(Math.max(0,contentWidth-lineVisibleWidth)),lineRightPadding=cursorInPadding?rightPadding.slice(1):rightPadding;result.push(`${leftPadding}${displayText}${padding}${lineRightPadding}`)}let linesBelow=layoutLines.length-(this.scrollOffset+visibleLines.length);if(result.push(this.renderBottomBorder(width,linesBelow)),showAutocomplete||(this.renderedText={width,paddingX:this.paddingX,terminalRows,focused:this.focused,pasteIds:this.
487
+ pastes.size===0?"":[...this.pastes.keys()].join(","),lines:this.state.lines.slice(),cursorLine:this.state.cursorLine,cursorCol:this.state.cursorCol,scrollOffset:this.scrollOffset,visibleLineCount:visibleLines.length,linesBelow,textLines:result.slice(1,-1),result:result.slice()}),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let autocompleteResult=this.autocompleteList.render(contentWidth);this.renderedAutocompleteHeight=autocompleteResult.length;for(let line of autocompleteResult){
488
+ let lineWidth=visibleWidth(line),linePadding=" ".repeat(Math.max(0,contentWidth-lineWidth));result.push(`${leftPadding}${line}${linePadding}${rightPadding}`)}}return result}handleMouse(event){let autocompleteStartRow=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&event.y>=autocompleteStartRow&&event.y<autocompleteStartRow+this.renderedAutocompleteHeight){let maxPadding2=Math.max(0,Math.floor((event.width-1)/2)),paddingX2=Math.min(this.paddingX,maxPadding2),contentWidth=Math.
489
+ max(1,event.width-paddingX2*2),result=this.autocompleteList.handleMouse?.({...event,x:event.x-paddingX2,y:event.y-autocompleteStartRow,width:contentWidth,height:this.renderedAutocompleteHeight});return result?{...result,focus:!0}:void 0}if(event.type!=="click"||event.button!=="left")return;if(event.y<=0||event.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let visualLines=this.buildVisualLineMap(this.lastWidth),visualLineIndex=this.scrollOffset+event.y-1,visualLine=visualLines[visualLineIndex];
490
+ if(!visualLine)return{handled:!0,focus:!0};let logicalLine=this.state.lines[visualLine.logicalLine]??"",chunkEnd=visualLine.startCol+visualLine.length,chunk=logicalLine.slice(visualLine.startCol,chunkEnd),maxPadding=Math.max(0,Math.floor((event.width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),targetColumn=Math.max(0,event.x-paddingX),visibleColumn=0,targetIndex=chunk.length,lastGraphemeIndex=0;for(let grapheme of this.segment(chunk,"grapheme")){let nextColumn=visibleColumn+visibleWidth(grapheme.
491
+ segment);if(lastGraphemeIndex=grapheme.index,targetColumn<nextColumn){targetIndex=grapheme.index;break}visibleColumn=nextColumn}return!(visualLineIndex===visualLines.length-1||visualLines[visualLineIndex+1]?.logicalLine!==visualLine.logicalLine)&&targetIndex===chunk.length&&chunk.length>0&&(targetIndex=lastGraphemeIndex),this.state.cursorLine=visualLine.logicalLine,this.setCursorCol(visualLine.startCol+targetIndex),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),
446
492
  {handled:!0,focus:!0}}handleInput(data){let kb=getKeybindings();if(this.jumpMode!==null){if(kb.matches(data,"tui.editor.jumpForward")||kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode=null;return}let printable2=decodePrintableKey(data)??(data.charCodeAt(0)>=32?data:void 0);if(printable2!==void 0){let direction=this.jumpMode;this.jumpMode=null,this.jumpToChar(printable2,direction);return}this.jumpMode=null}if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace(
447
493
  "\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);pasteContent.length>0&&this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining.length>0&&this.handleInput(remaining);return}return}if(kb.matches(data,"tui.input.copy"))return;if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&
448
494
  this.autocompleteList){if(kb.matches(data,"tui.select.cancel")){this.cancelAutocomplete();return}if(kb.matches(data,"tui.select.up")||kb.matches(data,"tui.select.down")){this.autocompleteList.handleInput(data);return}if(kb.matches(data,"tui.input.tab")){let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,
@@ -454,7 +500,7 @@ orWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cur
454
500
  `&&data.length===1){if(this.shouldSubmitOnBackslashEnter(data,kb)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(kb.matches(data,"tui.input.submit")){if(this.disableSubmit)return;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&currentLine[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(kb.matches(data,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||
455
501
  this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(kb.matches(data,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(kb.matches(data,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(kb.matches(data,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(kb.matches(
456
502
  data,"tui.editor.pageUp")){this.pageScroll(-1);return}if(kb.matches(data,"tui.editor.pageDown")){this.pageScroll(1);return}if(kb.matches(data,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(matchesKey(data,"shift+space")){this.insertCharacter(" ");return}let printable=decodePrintableKey(data);if(printable!==void 0){this.insertCharacter(printable);return}data.charCodeAt(0)>=32&&this.insertCharacter(data)}layoutText(contentWidth){
457
- let layoutLines=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return layoutLines.push({text:"",hasCursor:!0,cursorPos:0}),layoutLines;let wrapCache=this.wrapCacheFor(contentWidth);for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",isCurrentLine=i===this.state.cursorLine;if(visibleWidth(line)<=contentWidth)isCurrentLine?layoutLines.push({text:line,hasCursor:!0,cursorPos:this.state.cursorCol}):layoutLines.push({text:line,hasCursor:!1});else{
503
+ let layoutLines=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return layoutLines.push({text:"",hasCursor:!0,cursorPos:0}),layoutLines;let wrapCache=this.wrapCacheFor(contentWidth);for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",isCurrentLine=i===this.state.cursorLine;if(editorLineWidth(line)<=contentWidth)isCurrentLine?layoutLines.push({text:line,hasCursor:!0,cursorPos:this.state.cursorCol}):layoutLines.push({text:line,hasCursor:!1});else{
458
504
  let chunks=this.wrapLine(wrapCache,i,line,contentWidth);for(let chunkIndex=0;chunkIndex<chunks.length;chunkIndex++){let chunk=chunks[chunkIndex];if(!chunk)continue;let cursorPos=this.state.cursorCol,isLastChunk=chunkIndex===chunks.length-1,hasCursorInChunk=!1,adjustedCursorPos=0;isCurrentLine&&(isLastChunk?(hasCursorInChunk=cursorPos>=chunk.startIndex,adjustedCursorPos=cursorPos-chunk.startIndex):(hasCursorInChunk=cursorPos>=chunk.startIndex&&cursorPos<chunk.endIndex,hasCursorInChunk&&(adjustedCursorPos=
459
505
  cursorPos-chunk.startIndex,adjustedCursorPos>chunk.text.length&&(adjustedCursorPos=chunk.text.length)))),hasCursorInChunk?layoutLines.push({text:chunk.text,hasCursor:!0,cursorPos:adjustedCursorPos}):layoutLines.push({text:chunk.text,hasCursor:!1})}}}return layoutLines}getText(){return this.state.lines.join(`
460
506
  `)}expandPasteMarkers(text){let result=text;for(let[pasteId,pasteContent]of this.pastes){let markerRegex=new RegExp(`\\[paste #${pasteId}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");result=result.replace(markerRegex,()=>pasteContent)}return result}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(`
@@ -464,24 +510,24 @@ insertTextAtCursorInternal(text))}normalizeText(text){return text.replace(/\r\n/
464
510
  `).replace(/\t/g," ")}insertTextAtCursorInternal(text){if(!text)return;let normalized=this.normalizeText(text),insertedLines=normalized.split(`
465
511
  `),currentLine=this.state.lines[this.state.cursorLine]||"",beforeCursor=currentLine.slice(0,this.state.cursorCol),afterCursor=currentLine.slice(this.state.cursorCol);insertedLines.length===1?(this.state.lines[this.state.cursorLine]=beforeCursor+normalized+afterCursor,this.setCursorCol(this.state.cursorCol+normalized.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),beforeCursor+insertedLines[0],...insertedLines.slice(1,-1),insertedLines[insertedLines.length-1]+afterCursor,
466
512
  ...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=insertedLines.length-1,this.setCursorCol((insertedLines[insertedLines.length-1]||"").length)),this.onChange&&this.onChange(this.getText())}insertCharacter(char,skipUndoCoalescing){this.exitHistoryBrowsing(),skipUndoCoalescing||((isWhitespaceChar(char)||this.lastAction!=="type-word")&&this.pushUndoSnapshot(),this.lastAction="type-word");let line=this.state.lines[this.state.cursorLine]||"",before=line.slice(0,this.state.cursorCol),
467
- after=line.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=before+char+after,this.setCursorCol(this.state.cursorCol+char.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(char==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.autocompleteTriggerPattern.
468
- test(textBeforeCursor)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(char)||cjkBreakRegex.test(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}handlePaste(pastedText){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();
469
- let decodedText=pastedText.replace(/\x1b\[(\d+);5u/g,(match,code)=>{let cp=Number(code);return cp>=97&&cp<=122?String.fromCharCode(cp-96):cp>=65&&cp<=90?String.fromCharCode(cp-64):match}),filteredText=this.normalizeText(decodedText).split("").filter(char=>char===`
513
+ after=line.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=before+char+after,this.setCursorCol(this.state.cursorCol+char.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(char==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.matchesAutocompleteTrigger(
514
+ textBeforeCursor)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(char)||cjkBreakRegex.test(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.matchesAutocompleteTrigger(textBeforeCursor)&&this.tryTriggerAutocomplete()}}handlePaste(pastedText){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let decodedText=pastedText.
515
+ replace(/\x1b\[(\d+);5u/g,(match,code)=>{let cp=Number(code);return cp>=97&&cp<=122?String.fromCharCode(cp-96):cp>=65&&cp<=90?String.fromCharCode(cp-64):match}),filteredText=this.normalizeText(decodedText).split("").filter(char=>char===`
470
516
  `||char.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(filteredText)){let currentLine=this.state.lines[this.state.cursorLine]||"",charBeforeCursor=this.state.cursorCol>0?currentLine[this.state.cursorCol-1]:"";charBeforeCursor&&/\w/.test(charBeforeCursor)&&(filteredText=` ${filteredText}`)}let pastedLines=filteredText.split(`
471
517
  `),totalChars=filteredText.length;if(pastedLines.length>10||totalChars>1e3){this.pasteCounter++;let pasteId=this.pasteCounter;this.pastes.set(pasteId,filteredText);let marker=pastedLines.length>10?`[paste #${pasteId} +${pastedLines.length} lines]`:`[paste #${pasteId} ${totalChars} chars]`;this.insertTextAtCursorInternal(marker);return}if(pastedLines.length===1){this.insertTextAtCursorInternal(filteredText);return}this.insertTextAtCursorInternal(filteredText)}addNewLine(){this.cancelAutocomplete(),
472
518
  this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before,this.state.lines.splice(this.state.cursorLine+1,0,after),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(data,kb){if(this.disableSubmit||!matchesKey(data,"\
473
519
  enter"))return!1;let submitKeys=kb.getKeys("tui.input.submit");if(!(submitKeys.includes("shift+enter")||submitKeys.includes("shift+return")))return!1;let currentLine=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&currentLine[this.state.cursorCol-1]==="\\"}submitValue(){this.cancelAutocomplete();let result=this.expandPasteMarkers(this.state.lines.join(`
474
- `)).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(result)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let line=this.state.lines[this.state.cursorLine]||"",beforeCursor=line.slice(0,this.state.cursorCol),graphemes=[...this.segment(
475
- beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.length-1],graphemeLength=lastGrapheme?lastGrapheme.segment.length:1,isPastedSegmented=PASTE_MARKER_SINGLE.exec(lastGrapheme.segment);if(isPastedSegmented){let targetId=Number(isPastedSegmented[1]);this.pastes.delete(targetId),this.pasteCounter--;let higherIds=[...this.pastes.keys()].filter(id=>id>targetId).sort((a3,b)=>a3-b);for(let id of higherIds)this.pastes.set(id-1,this.pastes.get(id)),this.pastes.delete(id);this.state.lines=this.state.
476
- lines.map(line2=>line2.replace(PASTE_MARKER_REGEX,(fullMatch,idGroup,suffixGroup)=>{let x2=Number(idGroup);return x2<=targetId?fullMatch:`[paste #${x2-1}${suffixGroup}]`}))}line=this.state.lines[this.state.cursorLine]||"";let before=line.slice(0,this.state.cursorCol-graphemeLength),after=line.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-graphemeLength)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let currentLine=this.
477
- state.lines[this.state.cursorLine]||"",previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(
478
- textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}setCursorCol(col){this.state.cursorCol=col,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(visualLines,currentVisualLine,targetVisualLine){let currentVL=visualLines[currentVisualLine],targetVL=visualLines[targetVisualLine];if(!(currentVL&&targetVL))return;let currentVisualCol;if(this.snappedFromCursorCol!==null){let vlIndex=this.findVisualLineAt(
479
- visualLines,currentVL.logicalLine,this.snappedFromCursorCol);currentVisualCol=this.snappedFromCursorCol-visualLines[vlIndex].startCol}else currentVisualCol=this.state.cursorCol-currentVL.startCol;let sourceMaxVisualCol=currentVisualLine===visualLines.length-1||visualLines[currentVisualLine+1]?.logicalLine!==currentVL.logicalLine?currentVL.length:Math.max(0,currentVL.length-1),targetMaxVisualCol=targetVisualLine===visualLines.length-1||visualLines[targetVisualLine+1]?.logicalLine!==targetVL.logicalLine?
480
- targetVL.length:Math.max(0,targetVL.length-1),moveToVisualCol=this.computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol);this.state.cursorLine=targetVL.logicalLine;let targetCol=targetVL.startCol+moveToVisualCol,logicalLine=this.state.lines[targetVL.logicalLine]||"";this.state.cursorCol=Math.min(targetCol,logicalLine.length);let segments=[...this.segment(logicalLine,"grapheme")];for(let seg of segments){if(seg.index>this.state.cursorCol)break;if(!(seg.segment.length<=
481
- 1)&&this.state.cursorCol<seg.index+seg.segment.length){let isContinuation=seg.index<targetVL.startCol,isMovingDown=targetVisualLine>currentVisualLine;if(isContinuation&&isMovingDown){let segEnd=seg.index+seg.segment.length,next=targetVisualLine+1;for(;next<visualLines.length&&visualLines[next].logicalLine===targetVL.logicalLine&&visualLines[next].startCol<segEnd;)next++;if(next<visualLines.length){this.moveToVisualLine(visualLines,currentVisualLine,next);return}}this.snappedFromCursorCol=this.state.
482
- cursorCol,this.state.cursorCol=seg.index;return}}this.snappedFromCursorCol=null}computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol){let hasPreferred=this.preferredVisualCol!==null,cursorInMiddle=currentVisualCol<sourceMaxVisualCol,targetTooShort=targetMaxVisualCol<currentVisualCol;if(!hasPreferred||cursorInMiddle)return targetTooShort?(this.preferredVisualCol=currentVisualCol,targetMaxVisualCol):(this.preferredVisualCol=null,currentVisualCol);let targetCantFitPreferred=targetMaxVisualCol<
483
- this.preferredVisualCol;if(targetTooShort||targetCantFitPreferred)return targetMaxVisualCol;let result=this.preferredVisualCol;return this.preferredVisualCol=null,result}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(currentLine.length)}deleteToStartOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){
484
- this.pushUndoSnapshot();let deletedText=currentLine.slice(0,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
520
+ `)).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(result)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let line=this.state.lines[this.state.cursorLine]||"",beforeCursor=line.slice(0,this.state.cursorCol),lastGrapheme=this.lastGrapheme(
521
+ beforeCursor),graphemeLength=lastGrapheme?lastGrapheme.segment.length:1,isPastedSegmented=PASTE_MARKER_SINGLE.exec(lastGrapheme.segment);if(isPastedSegmented){let targetId=Number(isPastedSegmented[1]);this.pastes.delete(targetId),this.pasteCounter--;let higherIds=[...this.pastes.keys()].filter(id=>id>targetId).sort((a3,b)=>a3-b);for(let id of higherIds)this.pastes.set(id-1,this.pastes.get(id)),this.pastes.delete(id);this.state.lines=this.state.lines.map(line2=>line2.replace(PASTE_MARKER_REGEX,(fullMatch,idGroup,suffixGroup)=>{
522
+ let x2=Number(idGroup);return x2<=targetId?fullMatch:`[paste #${x2-1}${suffixGroup}]`}))}line=this.state.lines[this.state.cursorLine]||"";let before=line.slice(0,this.state.cursorCol-graphemeLength),after=line.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-graphemeLength)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let currentLine=this.state.lines[this.state.cursorLine]||"",previousLine=this.state.lines[this.state.
523
+ cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.matchesAutocompleteTrigger(
524
+ textBeforeCursor)&&this.tryTriggerAutocomplete()}}setCursorCol(col){this.state.cursorCol=col,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(visualLines,currentVisualLine,targetVisualLine){let currentVL=visualLines[currentVisualLine],targetVL=visualLines[targetVisualLine];if(!(currentVL&&targetVL))return;let currentVisualCol;if(this.snappedFromCursorCol!==null){let vlIndex=this.findVisualLineAt(visualLines,currentVL.logicalLine,this.snappedFromCursorCol);currentVisualCol=
525
+ this.snappedFromCursorCol-visualLines[vlIndex].startCol}else currentVisualCol=this.state.cursorCol-currentVL.startCol;let sourceMaxVisualCol=currentVisualLine===visualLines.length-1||visualLines[currentVisualLine+1]?.logicalLine!==currentVL.logicalLine?currentVL.length:Math.max(0,currentVL.length-1),targetMaxVisualCol=targetVisualLine===visualLines.length-1||visualLines[targetVisualLine+1]?.logicalLine!==targetVL.logicalLine?targetVL.length:Math.max(0,targetVL.length-1),moveToVisualCol=this.computeVerticalMoveColumn(
526
+ currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol);this.state.cursorLine=targetVL.logicalLine;let targetCol=targetVL.startCol+moveToVisualCol,logicalLine=this.state.lines[targetVL.logicalLine]||"";this.state.cursorCol=Math.min(targetCol,logicalLine.length);let seg=this.graphemeContaining(logicalLine,this.state.cursorCol);if(seg&&seg.segment.length>1){let isContinuation=seg.index<targetVL.startCol,isMovingDown=targetVisualLine>currentVisualLine;if(isContinuation&&isMovingDown){let segEnd=seg.
527
+ index+seg.segment.length,next=targetVisualLine+1;for(;next<visualLines.length&&visualLines[next].logicalLine===targetVL.logicalLine&&visualLines[next].startCol<segEnd;)next++;if(next<visualLines.length){this.moveToVisualLine(visualLines,currentVisualLine,next);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=seg.index;return}this.snappedFromCursorCol=null}computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol){let hasPreferred=this.preferredVisualCol!==
528
+ null,cursorInMiddle=currentVisualCol<sourceMaxVisualCol,targetTooShort=targetMaxVisualCol<currentVisualCol;if(!hasPreferred||cursorInMiddle)return targetTooShort?(this.preferredVisualCol=currentVisualCol,targetMaxVisualCol):(this.preferredVisualCol=null,currentVisualCol);let targetCantFitPreferred=targetMaxVisualCol<this.preferredVisualCol;if(targetTooShort||targetCantFitPreferred)return targetMaxVisualCol;let result=this.preferredVisualCol;return this.preferredVisualCol=null,result}moveToLineStart(){
529
+ this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(currentLine.length)}deleteToStartOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let deletedText=currentLine.slice(0,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.
530
+ state.lines[this.state.cursorLine]=currentLine.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
485
531
  `,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.
486
532
  length){this.pushUndoSnapshot();let deletedText=currentLine.slice(this.state.cursorCol);this.killRing.push(deletedText,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
487
533
  `,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(
@@ -490,36 +536,35 @@ length){this.pushUndoSnapshot();let deletedText=currentLine.slice(this.state.cur
490
536
  let deletedText=currentLine.slice(deleteFrom,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,deleteFrom)+currentLine.slice(this.state.cursorCol),this.setCursorCol(deleteFrom)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){if(this.
491
537
  state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
492
538
  `,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let wasKill=this.lastAction==="kill",oldCursorCol=this.state.cursorCol;this.moveWordForwards();let deleteTo=this.state.cursorCol;this.setCursorCol(oldCursorCol);let deletedText=currentLine.slice(this.state.cursorCol,deleteTo);
493
- this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)+currentLine.slice(deleteTo)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.length){this.pushUndoSnapshot();let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=[
494
- ...this.segment(afterCursor,"grapheme")][0],graphemeLength=firstGrapheme?firstGrapheme.segment.length:1,before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol+graphemeLength);this.state.lines[this.state.cursorLine]=before+after}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.
495
- cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(width){let visualLines=[],wrapCache=this.wrapCacheFor(width);for(let i=0;i<this.state.lines.length;i++){
496
- let line=this.state.lines[i]||"",lineVisWidth=visibleWidth(line);if(line.length===0)visualLines.push({logicalLine:i,startCol:0,length:0});else if(lineVisWidth<=width)visualLines.push({logicalLine:i,startCol:0,length:line.length});else{let chunks=this.wrapLine(wrapCache,i,line,width);for(let chunk of chunks)visualLines.push({logicalLine:i,startCol:chunk.startIndex,length:chunk.endIndex-chunk.startIndex})}}return visualLines}findVisualLineAt(visualLines,line,col){for(let i=0;i<visualLines.length;i++){
497
- let vl=visualLines[i];if(!vl||vl.logicalLine!==line)continue;let offset=col-vl.startCol,isLastSegmentOfLine=i===visualLines.length-1||visualLines[i+1]?.logicalLine!==vl.logicalLine;if(offset>=0&&(offset<vl.length||isLastSegmentOfLine&&offset===vl.length))return i}return visualLines.length-1}findCurrentVisualLine(visualLines){return this.findVisualLineAt(visualLines,this.state.cursorLine,this.state.cursorCol)}moveCursor(deltaLine,deltaCol){this.lastAction=null;let visualLines=this.buildVisualLineMap(
498
- this.lastWidth),currentVisualLine=this.findCurrentVisualLine(visualLines);if(deltaLine!==0){let targetVisualLine=currentVisualLine+deltaLine;targetVisualLine>=0&&targetVisualLine<visualLines.length&&this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}if(deltaCol!==0){let currentLine=this.state.lines[this.state.cursorLine]||"";if(deltaCol>0)if(this.state.cursorCol<currentLine.length){let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=[...this.segment(afterCursor,
499
- "grapheme")][0];this.setCursorCol(this.state.cursorCol+(firstGrapheme?firstGrapheme.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let currentVL=visualLines[currentVisualLine];currentVL&&(this.preferredVisualCol=this.state.cursorCol-currentVL.startCol)}else if(this.state.cursorCol>0){let beforeCursor=currentLine.slice(0,this.state.cursorCol),graphemes=[...this.segment(beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.
500
- length-1];this.setCursorCol(this.state.cursorCol-(lastGrapheme?lastGrapheme.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(direction){this.lastAction=null;let terminalRows=this.tui.terminal.rows,pageSize=Math.max(5,Math.floor(terminalRows*.3)),visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.
501
- findCurrentVisualLine(visualLines),targetVisualLine=Math.max(0,Math.min(visualLines.length-1,currentVisualLine+direction*pageSize));this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}moveWordBackwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}return}this.setCursorCol(
502
- findWordBackward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}insertYankedText(text){
503
- this.exitHistoryBrowsing();let lines=text.split(`
539
+ this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)+currentLine.slice(deleteTo)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.length){this.pushUndoSnapshot();let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=this.
540
+ firstGrapheme(afterCursor),graphemeLength=firstGrapheme?firstGrapheme.segment.length:1,before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol+graphemeLength);this.state.lines[this.state.cursorLine]=before+after}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}
541
+ if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.matchesAutocompleteTrigger(textBeforeCursor)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(width){let visualLines=[],wrapCache=this.wrapCacheFor(width);for(let i=0;i<this.state.lines.length;i++){let line=this.state.
542
+ lines[i]||"",lineVisWidth=editorLineWidth(line);if(line.length===0)visualLines.push({logicalLine:i,startCol:0,length:0});else if(lineVisWidth<=width)visualLines.push({logicalLine:i,startCol:0,length:line.length});else{let chunks=this.wrapLine(wrapCache,i,line,width);for(let chunk of chunks)visualLines.push({logicalLine:i,startCol:chunk.startIndex,length:chunk.endIndex-chunk.startIndex})}}return visualLines}findVisualLineAt(visualLines,line,col){for(let i=0;i<visualLines.length;i++){let vl=visualLines[i];
543
+ if(!vl||vl.logicalLine!==line)continue;let offset=col-vl.startCol,isLastSegmentOfLine=i===visualLines.length-1||visualLines[i+1]?.logicalLine!==vl.logicalLine;if(offset>=0&&(offset<vl.length||isLastSegmentOfLine&&offset===vl.length))return i}return visualLines.length-1}findCurrentVisualLine(visualLines){return this.findVisualLineAt(visualLines,this.state.cursorLine,this.state.cursorCol)}moveCursor(deltaLine,deltaCol){this.lastAction=null;let visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.
544
+ findCurrentVisualLine(visualLines);if(deltaLine!==0){let targetVisualLine=currentVisualLine+deltaLine;targetVisualLine>=0&&targetVisualLine<visualLines.length&&this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}if(deltaCol!==0){let currentLine=this.state.lines[this.state.cursorLine]||"";if(deltaCol>0)if(this.state.cursorCol<currentLine.length){let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=this.firstGrapheme(afterCursor);this.setCursorCol(this.state.cursorCol+
545
+ (firstGrapheme?firstGrapheme.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let currentVL=visualLines[currentVisualLine];currentVL&&(this.preferredVisualCol=this.state.cursorCol-currentVL.startCol)}else if(this.state.cursorCol>0){let beforeCursor=currentLine.slice(0,this.state.cursorCol),lastGrapheme=this.lastGrapheme(beforeCursor);this.setCursorCol(this.state.cursorCol-(lastGrapheme?lastGrapheme.segment.length:1))}else if(this.
546
+ state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(direction){this.lastAction=null;let terminalRows=this.tui.terminal.rows,pageSize=Math.max(5,Math.floor(terminalRows*.3)),visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.findCurrentVisualLine(visualLines),targetVisualLine=Math.max(0,Math.min(visualLines.length-1,currentVisualLine+
547
+ direction*pageSize));this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}moveWordBackwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}return}this.setCursorCol(findWordBackward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}yank(){
548
+ if(this.killRing.length===0)return;this.pushUndoSnapshot();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}insertYankedText(text){this.exitHistoryBrowsing();let lines=text.split(`
504
549
  `);if(lines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+text+after,this.setCursorCol(this.state.cursorCol+text.length)}else{let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+(lines[0]||
505
550
  "");for(let i=1;i<lines.length-1;i++)this.state.lines.splice(this.state.cursorLine+i,0,lines[i]||"");let lastLineIndex=this.state.cursorLine+lines.length-1;this.state.lines.splice(lastLineIndex,0,(lines[lines.length-1]||"")+after),this.state.cursorLine=lastLineIndex,this.setCursorCol((lines[lines.length-1]||"").length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){let yankedText=this.killRing.peek();if(!yankedText)return;let yankLines=yankedText.split(`
506
551
  `);if(yankLines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",deleteLen=yankedText.length,before=currentLine.slice(0,this.state.cursorCol-deleteLen),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-deleteLen)}else{let startLine=this.state.cursorLine-(yankLines.length-1),startCol=(this.state.lines[startLine]||"").length-(yankLines[0]||"").length,afterCursor=(this.state.lines[this.state.
507
552
  cursorLine]||"").slice(this.state.cursorCol),beforeYank=(this.state.lines[startLine]||"").slice(0,startCol);this.state.lines.splice(startLine,yankLines.length,beforeYank+afterCursor),this.state.cursorLine=startLine,this.setCursorCol(startCol)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let snapshot=this.undoStack.pop();snapshot&&(Object.assign(this.state,
508
553
  snapshot.state),this.pastes=snapshot.pastes,this.pasteCounter=snapshot.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(char,direction){this.lastAction=null;let isForward=direction==="forward",lines=this.state.lines,end=isForward?lines.length:-1,step=isForward?1:-1;for(let lineIdx=this.state.cursorLine;lineIdx!==end;lineIdx+=step){let line=lines[lineIdx]||"",searchFrom=lineIdx===this.state.cursorLine?isForward?this.state.cursorCol+
509
554
  1:this.state.cursorCol-1:void 0,idx=isForward?line.indexOf(char,searchFrom):line.lastIndexOf(char,searchFrom);if(idx!==-1){this.state.cursorLine=lineIdx,this.setCursorCol(idx);return}}}moveWordForwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(findWordForward(currentLine,this.state.cursorCol,
510
- {segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return beforeCursor.trim()===""||beforeCursor.trim()==="/"}isInSlashCommandContext(textBeforeCursor){return this.isSlashMenuAllowed()&&textBeforeCursor.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(items,prefix){
511
- if(!prefix)return-1;let firstPrefixIndex=-1;for(let i=0;i<items.length;i++){let value=items[i].value;if(value===prefix)return i;firstPrefixIndex===-1&&value.startsWith(prefix)&&(firstPrefixIndex=i)}return firstPrefixIndex}createAutocompleteList(prefix,items){let layout=prefix.startsWith("/")?SLASH_COMMAND_SELECT_LIST_LAYOUT:void 0,list=new SelectList(items,this.autocompleteMaxVisible,this.theme.selectList,layout);return list.onSelect=selected=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),
512
- this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},list}tryTriggerAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!1,explicitTab})}handleTabCompletion(){if(!this.autocompleteProvider)return;let beforeCursor=(this.
513
- state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(beforeCursor)&&!beforeCursor.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!0,explicitTab})}requestAutocomplete(options){if(!this.autocompleteProvider||options.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||
514
- this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let startToken=++this.autocompleteStartToken,debounceMs=this.getAutocompleteDebounceMs(options);if(debounceMs>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(startToken,options)},debounceMs);return}this.startAutocompleteRequest(startToken,options)}async startAutocompleteRequest(startToken,options){
515
- let previousTask=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await previousTask,startToken!==this.autocompleteStartToken||!this.autocompleteProvider)return;let controller=new AbortController;this.autocompleteAbort=controller;let requestId=++this.autocompleteRequestId,snapshotText=this.getText(),snapshotLine=this.state.cursorLine,snapshotCol=this.state.cursorCol;await this.runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options)})(),await this.
516
- autocompleteRequestTask}setAutocompleteTriggerCharacters(triggerCharacters){let next=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];for(let character of triggerCharacters)character.length!==1||character==="/"||isWhitespaceChar(character)||next.includes(character)||next.push(character);this.autocompleteTriggerCharacters=next,this.autocompleteTriggerPattern=buildTriggerPattern(next),this.autocompleteDebouncePattern=buildDebouncePattern(next)}getAutocompleteDebounceMs(options){if(options.explicitTab||
517
- options.force)return 0;let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(textBeforeCursor)?ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS:0}async runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options){if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:controller.signal,
518
- force:options.force});if(this.isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol)){if(this.autocompleteAbort=void 0,!suggestions||!Array.isArray(suggestions.items)||suggestions.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(options.force&&options.explicitTab&&suggestions.items.length===1){let item=suggestions.items[0];this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,
519
- this.state.cursorLine,this.state.cursorCol,item,suggestions.prefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(suggestions,options.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol){return!controller.signal.aborted&&requestId===this.autocompleteRequestId&&
520
- this.getText()===snapshotText&&this.state.cursorLine===snapshotLine&&this.state.cursorCol===snapshotCol}applyAutocompleteSuggestions(suggestions,state){this.autocompletePrefix=suggestions.prefix,this.autocompleteList=this.createAutocompleteList(suggestions.prefix,suggestions.items);let bestMatchIndex=this.getBestAutocompleteMatchIndex(suggestions.items,suggestions.prefix);bestMatchIndex>=0&&this.autocompleteList.setSelectedIndex(bestMatchIndex),this.autocompleteState=state}cancelAutocompleteRequest(){
521
- 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||
522
- !this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var LAYOUT_NODE=Symbol.for("@earendil-works/pi-tui/layout-node");function getLayoutNode(component){let candidate=component;return typeof candidate[LAYOUT_NODE]=="function"?candidate[LAYOUT_NODE]():void 0}function isStackEntry(child){return!("render"in child)}function normalizeSize(value,fallback){return value===void 0||!Number.isFinite(value)?fallback:Math.max(0,Math.floor(value))}var Stack=class extends Container{entries=[];gap;align;constructor(children=[],options={}){super(),this.gap=normalizeSize(options.gap,0),this.align=options.align??"stretch";for(let child of children)isStackEntry(child)?this.addChild(child.component,child):this.addChild(child)}addChild(component,options={}){super.addChild(
555
+ {segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return beforeCursor.trim()===""||beforeCursor.trim()==="/"}matchesAutocompleteTrigger(textBeforeCursor){let triggerCharacters=this.autocompleteTriggerCharacters;for(let i=0;i<triggerCharacters.length;i++)if(textBeforeCursor.
556
+ includes(triggerCharacters[i]))return this.autocompleteTriggerPattern.test(textBeforeCursor);return!1}isInSlashCommandContext(textBeforeCursor){return this.isSlashMenuAllowed()&&textBeforeCursor.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(items,prefix){if(!prefix)return-1;let firstPrefixIndex=-1;for(let i=0;i<items.length;i++){let value=items[i].value;if(value===prefix)return i;firstPrefixIndex===-1&&value.startsWith(prefix)&&(firstPrefixIndex=i)}return firstPrefixIndex}createAutocompleteList(prefix,items){
557
+ let layout=prefix.startsWith("/")?SLASH_COMMAND_SELECT_LIST_LAYOUT:void 0,list=new SelectList(items,this.autocompleteMaxVisible,this.theme.selectList,layout);return list.onSelect=selected=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(
558
+ result.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},list}tryTriggerAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!1,explicitTab})}handleTabCompletion(){if(!this.autocompleteProvider)return;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(beforeCursor)&&!beforeCursor.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){
559
+ this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!0,explicitTab})}requestAutocomplete(options){if(!this.autocompleteProvider||options.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let startToken=++this.autocompleteStartToken,debounceMs=this.getAutocompleteDebounceMs(
560
+ options);if(debounceMs>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(startToken,options)},debounceMs);return}this.startAutocompleteRequest(startToken,options)}async startAutocompleteRequest(startToken,options){let previousTask=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await previousTask,startToken!==this.autocompleteStartToken||!this.autocompleteProvider)return;let controller=new AbortController;
561
+ this.autocompleteAbort=controller;let requestId=++this.autocompleteRequestId,snapshotText=this.getText(),snapshotLine=this.state.cursorLine,snapshotCol=this.state.cursorCol;await this.runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(triggerCharacters){let next=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];for(let character of triggerCharacters)character.length!==1||character==="/"||isWhitespaceChar(
562
+ character)||next.includes(character)||next.push(character);this.autocompleteTriggerCharacters=next,this.autocompleteTriggerPattern=buildTriggerPattern(next),this.autocompleteDebouncePattern=buildDebouncePattern(next)}getAutocompleteDebounceMs(options){if(options.explicitTab||options.force)return 0;let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(textBeforeCursor)?ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS:0}async runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options){
563
+ if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:controller.signal,force:options.force});if(this.isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol)){if(this.autocompleteAbort=void 0,!suggestions||!Array.isArray(suggestions.items)||suggestions.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(options.force&&options.
564
+ explicitTab&&suggestions.items.length===1){let item=suggestions.items[0];this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,item,suggestions.prefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(suggestions,options.force?"\
565
+ force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol){return!controller.signal.aborted&&requestId===this.autocompleteRequestId&&this.getText()===snapshotText&&this.state.cursorLine===snapshotLine&&this.state.cursorCol===snapshotCol}applyAutocompleteSuggestions(suggestions,state){this.autocompletePrefix=suggestions.prefix,this.autocompleteList=this.createAutocompleteList(suggestions.prefix,suggestions.items);let bestMatchIndex=this.
566
+ getBestAutocompleteMatchIndex(suggestions.items,suggestions.prefix);bestMatchIndex>=0&&this.autocompleteList.setSelectedIndex(bestMatchIndex),this.autocompleteState=state}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=
567
+ ""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var LAYOUT_NODE=Symbol.for("@earendil-works/pi-tui/layout-node");function getLayoutNode(component){let candidate=component;return typeof candidate[LAYOUT_NODE]=="function"?candidate[LAYOUT_NODE]():void 0}function isStackEntry(child){return!("render"in child)}function normalizeSize(value,fallback){return value===void 0||!Number.isFinite(value)?fallback:Math.max(0,Math.floor(value))}var Stack=class extends Container{entries=[];gap;align;constructor(children=[],options={}){super(),this.gap=normalizeSize(options.gap,0),this.align=options.align??"stretch";for(let child of children)isStackEntry(child)?this.addChild(child.component,child):this.addChild(child)}addChild(component,options={}){super.addChild(
523
568
  component),this.entries.push({component,...options.basis===void 0?{}:{basis:options.basis},...options.grow===void 0?{}:{grow:normalizeSize(options.grow,0)},...options.shrink===void 0?{}:{shrink:normalizeSize(options.shrink,1)},...options.minSize===void 0?{}:{minSize:normalizeSize(options.minSize,0)},...options.maxSize===void 0?{}:{maxSize:normalizeSize(options.maxSize,Number.MAX_SAFE_INTEGER)},...options.visible===void 0?{}:{visible:options.visible}})}removeChild(component){super.removeChild(component);
524
569
  let index=this.entries.findIndex(entry=>entry.component===component);index!==-1&&this.entries.splice(index,1)}clear(){super.clear(),this.entries.length=0}[LAYOUT_NODE](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function visibleStackEntries(entries,viewport){return entries.filter(entry=>entry.visible?.(viewport)??!0)}function clampSize(size,entry){let min=Math.max(0,Math.floor(entry.minSize??0)),max=Math.max(min,Math.floor(entry.maxSize??Number.MAX_SAFE_INTEGER));
525
570
  return Math.max(min,Math.min(max,Math.max(0,Math.floor(size))))}function distribute(sizes,entries,amount,mode){let remaining=amount;for(;remaining>0;){let candidates=entries.map((entry,index)=>({entry,index})).filter(({entry,index})=>mode==="grow"?(entry.grow??0)>0&&sizes[index]<(entry.maxSize??Number.MAX_SAFE_INTEGER):(entry.shrink??1)>0&&sizes[index]>(entry.minSize??0));if(candidates.length===0)return;let totalWeight=candidates.reduce((sum,{entry,index})=>sum+(mode==="grow"?entry.grow??0:(entry.
@@ -528,10 +573,10 @@ delta)}if(distributed===0)return}}function allocateStackSizes(entries,intrinsicS
528
573
  distribute(sizes,entries,total-contentSize,"shrink"),sizes}var HStack=class extends Stack{layoutType="hstack";constructor(children=[],options={}){super(children,options)}render(width){let safeWidth=Math.max(1,width),viewport={width:safeWidth,height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport);if(entries.length===0)return[];let intrinsicWidths=entries.map(entry=>entry.component.render(safeWidth).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,this.gap),rendered=entries.
529
574
  map((entry,index)=>widths[index]===0?[]:entry.component.render(widths[index])),height=rendered.reduce((max,lines)=>Math.max(max,lines.length),0),result=Array.from({length:height},()=>""),x2=0;for(let index=0;index<rendered.length;index++){let lines=rendered[index],childWidth=widths[index],offset=0;this.align==="center"?offset=Math.floor((height-lines.length)/2):this.align==="end"&&(offset=height-lines.length);for(let row=0;row<lines.length;row++){let target=row+offset;target<0||target>=result.length||
530
575
  (result[target]=compositeTuiLine(result[target],lines[row],x2,childWidth,safeWidth))}x2+=childWidth+this.gap}return result}};var imageTranscoder,pngCache=new Map;function setImageTranscoder(transcoder){imageTranscoder=transcoder,pngCache.clear()}function toPng(base64Data,mimeType){if(!imageTranscoder)return null;let cached=pngCache.get(base64Data),png=cached===void 0?imageTranscoder(base64Data,mimeType):cached;return pngCache.delete(base64Data),pngCache.set(base64Data,png),pngCache.size>32&&pngCache.delete(pngCache.keys().next().value),png}var Image=class{base64Data;mimeType;dimensions;theme;options;imageId;pngData;cachedLines;cachedWidth;constructor(base64Data,mimeType,theme2,options={},dimensions){
531
- this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme2,this.options=options,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(width){if(this.cachedLines&&this.cachedWidth===width)return this.cachedLines;let maxWidth=Math.max(1,Math.min(width-2,this.options.maxWidthCells??60)),cellDimensions2=getCellDimensions(),
576
+ this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme2,this.options=options,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0,reportRenderChange(this)}render(width){if(this.cachedLines&&this.cachedWidth===width)return this.cachedLines;let maxWidth=Math.max(1,Math.min(width-2,this.options.maxWidthCells??60)),cellDimensions2=getCellDimensions(),
532
577
  defaultMaxHeight=Math.max(1,Math.ceil(maxWidth*cellDimensions2.widthPx/cellDimensions2.heightPx)),maxHeight=this.options.maxHeightCells??defaultMaxHeight,caps=getCapabilities(),data=this.base64Data,dimensions=this.dimensions;caps.images==="kitty"&&this.mimeType!=="image/png"&&(this.pngData??=toPng(this.base64Data,this.mimeType)??void 0,data=this.pngData??null,data&&(dimensions=getPngDimensions(data)??dimensions));let lines;if(caps.images&&data){caps.images==="kitty"&&this.imageId===void 0&&(this.
533
578
  imageId=allocateImageId());let result=renderImage(data,dimensions,{maxWidthCells:maxWidth,maxHeightCells:maxHeight,imageId:this.imageId,moveCursor:!1});if(result)if(result.imageId&&(this.imageId=result.imageId),caps.images==="kitty"){lines=[result.sequence];for(let i=0;i<result.rows-1;i++)lines.push("")}else{lines=[];for(let i=0;i<result.rows-1;i++)lines.push("");let rowOffset=result.rows-1,moveUp=rowOffset>0?`\x1B[${rowOffset}A`:"";lines.push(moveUp+result.sequence)}else{let fallback=imageFallback(
534
- this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}return this.cachedLines=lines,this.cachedWidth=width,lines}};markStableRender(Image);var segmenter=getGraphemeSegmenter(),Input=class{value="";cursor=0;prompt;placeholder;placeholderStyle;mask;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new KillRing;lastAction=null;undoStack=new UndoStack;constructor(options={}){this.prompt=options.prompt??"> ",this.placeholder=options.placeholder??"",this.placeholderStyle=options.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,
579
+ this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}return this.cachedLines=lines,this.cachedWidth=width,lines}};markStableRender(Image);markReportsChanges(Image);var segmenter=getGraphemeSegmenter(),Input=class{value="";cursor=0;prompt;placeholder;placeholderStyle;mask;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new KillRing;lastAction=null;undoStack=new UndoStack;constructor(options={}){this.prompt=options.prompt??"> ",this.placeholder=options.placeholder??"",this.placeholderStyle=options.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,
535
580
  value.length)}setMask(mask){this.mask=mask}reset(){this.value="",this.cursor=0,this.mask=void 0,this.pasteBuffer="",this.isInPaste=!1,this.killRing=new KillRing,this.lastAction=null,this.undoStack.clear()}handleInput(data){if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);this.handlePaste(
536
581
  pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining&&this.handleInput(remaining)}return}let kb=getKeybindings();if(kb.matches(data,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(kb.matches(data,"tui.input.submit")||data===`
537
582
  `){this.onSubmit&&this.onSubmit(this.value);return}if(kb.matches(data,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(kb.matches(data,"tui.e\
@@ -550,7 +595,21 @@ mask?[...segmenter.segment(this.value)].map(()=>this.mask).join(""):this.value,d
550
595
  slice(atCursor2.length),marker2=this.focused?CURSOR_MARKER:"",cursorChar2=renderFakeCursor(this.placeholderStyle(atCursor2)),textWithCursor2=marker2+cursorChar2+this.placeholderStyle(afterCursor2),padding2=" ".repeat(Math.max(0,availableWidth-visibleWidth(textWithCursor2)));return[this.prompt+textWithCursor2+padding2]}let visibleText="",cursorDisplay=displayCursor;this.renderedStartColumn=0;let totalWidth=visibleWidth(displayValue);if(totalWidth<availableWidth)visibleText=displayValue;else{let scrollWidth=this.
551
596
  cursor===this.value.length?availableWidth-1:availableWidth,cursorCol=visibleWidth(displayValue.slice(0,displayCursor));if(scrollWidth>0){let halfWidth=Math.floor(scrollWidth/2),startCol=0;cursorCol<halfWidth?startCol=0:cursorCol>totalWidth-halfWidth?startCol=Math.max(0,totalWidth-scrollWidth):startCol=Math.max(0,cursorCol-halfWidth),this.renderedStartColumn=startCol,visibleText=sliceByColumn(displayValue,startCol,scrollWidth,!0),cursorDisplay=sliceByColumn(displayValue,startCol,Math.max(0,cursorCol-
552
597
  startCol),!0).length}else visibleText="",cursorDisplay=0}let cursorGrapheme=[...segmenter.segment(visibleText.slice(cursorDisplay))][0],beforeCursor=visibleText.slice(0,cursorDisplay),atCursor=cursorGrapheme?.segment??" ",afterCursor=visibleText.slice(cursorDisplay+atCursor.length),marker=this.focused?CURSOR_MARKER:"",cursorChar=renderFakeCursor(atCursor),textWithCursor=beforeCursor+marker+cursorChar+afterCursor,visualLength=visibleWidth(textWithCursor),padding=" ".repeat(Math.max(0,availableWidth-
553
- visualLength));return[this.prompt+textWithCursor+padding]}};var SYMBOLS={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",
598
+ visualLength));return[this.prompt+textWithCursor+padding]}};var CJK="\\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\
599
+ }\\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}",cjkTest=new RegExp(
600
+ `[${CJK}]`,"u"),punctuationCjk=new RegExp(`^((?![*_])[\\s\\p{P}\\p{S}${CJK}])`,"u");function buildRDelimAst(punct,punctSpace,notPunctSpace){return new RegExp(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)${punct}(\\*+)(?=[\\s]|$)|${notPunctSpace}(\\*+)(?!\\*)(?=${punctSpace}|$)|(?!\\*)${punctSpace}(\\*+)(?=${notPunctSpace})|[\\s](\\*+)(?!\\*)(?=${punct})|(?!\\*)${punct}(\\*+)(?!\\*)(?=${punct})|${notPunctSpace}(\\*+)(?=${notPunctSpace})`,"gu")}function buildRDelimUnd(punct,punctSpace,notPunctSpace){
601
+ return new RegExp(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)${punct}(_+)(?=[\\s]|$)|${notPunctSpace}(_+)(?!_)(?=${punctSpace}|$)|(?!_)${punctSpace}(_+)(?=${notPunctSpace})|[\\s](_+)(?!_)(?=${punct})|(?!_)${punct}(_+)(?!_)(?=${punct})`,"gu")}function buildRDelimDel(punct,punctSpace,notPunctSpace){return new RegExp(`^[^~]+(?=[^~])|(?!~)${punct}(~~?)(?=[\\s]|$)|${notPunctSpace}(~~?)(?!~)(?=${punctSpace}|$)|(?!~)${punctSpace}(~~?)(?=${notPunctSpace})|[\\s](~~?)(?!~)(?=${punct})|(?!\
602
+ ~)${punct}(~~?)(?!~)(?=${punct})|${notPunctSpace}(~~?)(?=${notPunctSpace})`,"gu")}var cjkPunct=`[\\p{P}\\p{S}${CJK}]`,cjkPunctSpace=`[\\s\\p{P}\\p{S}${CJK}]`,cjkNotPunctSpace=`[^\\s\\p{P}\\p{S}${CJK}]`,cjkDelPunct=`(?![*_])[\\p{P}\\p{S}${CJK}]`,cjkDelPunctSpace=`(?![*_])[\\s\\p{P}\\p{S}${CJK}]`,cjkDelNotPunctSpace=`(?:[^\\s\\p{P}\\p{S}${CJK}]|[*_])`,cjkPunctGfm=`(?!~)[\\p{P}\\p{S}${CJK}]`,cjkPunctSpaceGfm=`(?!~)[\\s\\p{P}\\p{S}${CJK}]`,cjkNotPunctSpaceGfm=`(?:[^\\s\\p{P}\\p{S}${CJK}]|~)`,emStrongRDelimAstCjk=buildRDelimAst(
603
+ cjkPunct,cjkPunctSpace,cjkNotPunctSpace),emStrongRDelimAstCjkGfm=buildRDelimAst(cjkPunctGfm,cjkPunctSpaceGfm,cjkNotPunctSpaceGfm),emStrongRDelimUndCjk=buildRDelimUnd(cjkPunct,cjkPunctSpace,cjkNotPunctSpace),delRDelimCjk=buildRDelimDel(cjkDelPunct,cjkDelPunctSpace,cjkDelNotPunctSpace);function isPrevCharCjk(prevChar,maskedSrc,src){let prevIsCjk=punctuationCjk.test(prevChar);if(!prevIsCjk&&prevChar){let prevIdx=maskedSrc.length-src.length;if(prevIdx>=1){let idx=prevIdx-1,code=maskedSrc.charCodeAt(
604
+ idx);if(code>=65024&&code<=65038&&idx>=1&&(idx--,code=maskedSrc.charCodeAt(idx)),(code&64512)===56320&&idx>=1){let cp=maskedSrc.codePointAt(idx-1);cp!==void 0&&cp>65535&&(cp>=917760&&cp<=917999?prevIsCjk=!0:prevIsCjk=cjkTest.test(String.fromCodePoint(cp)))}else prevIsCjk=cjkTest.test(String.fromCharCode(code))}}return prevIsCjk}function isCjkAdjacentToDelimiter(rightMatch,clippedMaskedSrc){if(!(rightMatch[1]||rightMatch[2]||rightMatch[3]||rightMatch[4]))return!1;let charBefore=String.fromCodePoint(
605
+ rightMatch[0].codePointAt(0)),afterPos=rightMatch.index+rightMatch[0].length,charAfter=afterPos<clippedMaskedSrc.length?String.fromCodePoint(clippedMaskedSrc.codePointAt(afterPos)):"";return cjkTest.test(charBefore)||cjkTest.test(charAfter)}function usesModernEmStrongLayout(match){return match.length>=5}function hasEmStrongLeadContent(match){return!!(match[1]||match[2]||match[3]||match[4])}function isEmStrongUnderscoreWordChar(match){return usesModernEmStrongLayout(match)?!!match[4]:!!match[3]}function getEmStrongOpeningPunctuation(match){
606
+ return usesModernEmStrongLayout(match)?match[1]||match[3]||"":match[1]||match[2]||""}function codePointCount(str){let result=str.length,end=result-1;for(let i=0;i<end;){let bmpOrHigh=str.charCodeAt(i++);if(bmpOrHigh<55296||56320<=bmpOrHigh)continue;let low=str.charCodeAt(i);low<56320||57344<=low||(i++,result--)}return result}function markedCjkFriendly(){return{tokenizer:{emStrong(src,maskedSrc,prevChar=""){let{rules}=this,match=rules.inline.emStrongLDelim.exec(src);if(!match)return!1;let modernEmStrongLayout=usesModernEmStrongLayout(
607
+ match);if(modernEmStrongLayout&&!hasEmStrongLeadContent(match))return;if(isEmStrongUnderscoreWordChar(match)&&prevChar.match(rules.other.unicodeAlphaNumeric))return!1;let nextChar=getEmStrongOpeningPunctuation(match),prevIsCjk=isPrevCharCjk(prevChar,maskedSrc,src);if(!nextChar||!prevChar||rules.inline.punctuation.exec(prevChar)||prevIsCjk||cjkTest.test(nextChar)){let lLength=codePointCount(match[0])-1,rDelim,rLength,delimTotal=lLength,midDelimTotal=0,prevCharIsSameDelimiter=modernEmStrongLayout&&
608
+ prevChar===match[0][0],isGfm=rules.inline.emStrongRDelimAst.source.includes("(?!~)"),endReg;match[0][0]==="*"?endReg=isGfm?emStrongRDelimAstCjkGfm:emStrongRDelimAstCjk:endReg=emStrongRDelimUndCjk,endReg.lastIndex=0;let clippedMaskedSrc=maskedSrc.slice(-1*src.length+lLength),rMatch;for(;(rMatch=endReg.exec(clippedMaskedSrc))!=null;){if(rDelim=rMatch[1]||rMatch[2]||rMatch[3]||rMatch[4]||rMatch[5]||rMatch[6],!rDelim)continue;rLength=codePointCount(rDelim);let isCjkAdjacent=isCjkAdjacentToDelimiter(
609
+ rMatch,clippedMaskedSrc),isLeftOnly=!!(rMatch[3]||rMatch[4]),isBoth=!!(rMatch[5]||rMatch[6]);if(isLeftOnly&&!isCjkAdjacent){delimTotal+=rLength;continue}if(isBoth||isCjkAdjacent){if(lLength%3&&!((lLength+rLength)%3)){midDelimTotal+=rLength;continue}if(prevCharIsSameDelimiter&&isBoth)break}if(delimTotal-=rLength,delimTotal>0)continue;rLength=Math.min(rLength,rLength+delimTotal+midDelimTotal);let lastCharLength=rMatch[0].codePointAt(0)>65535?2:1,raw=src.slice(0,lLength+rMatch.index+lastCharLength+
610
+ rLength);if(Math.min(lLength,rLength)%2){let text2=raw.slice(1,-1);return{type:"em",raw,text:text2,tokens:this.lexer.inlineTokens(text2)}}let text=raw.slice(2,-2);return{type:"strong",raw,text,tokens:this.lexer.inlineTokens(text)}}}},del(src,maskedSrc,prevChar=""){let{rules}=this,match=rules.inline.delLDelim.exec(src);if(!match)return!1;let nextChar=match[1]||"",prevIsCjk=isPrevCharCjk(prevChar,maskedSrc,src);if(!nextChar||!prevChar||rules.inline.punctuation.exec(prevChar)||prevIsCjk||cjkTest.test(
611
+ nextChar)){let lLength=codePointCount(match[0])-1,rDelim,rLength,delimTotal=lLength;delRDelimCjk.lastIndex=0;let clippedMaskedSrc=maskedSrc.slice(-1*src.length+lLength),rMatch;for(;(rMatch=delRDelimCjk.exec(clippedMaskedSrc))!=null;){if(rDelim=rMatch[1]||rMatch[2]||rMatch[3]||rMatch[4]||rMatch[5]||rMatch[6],!rDelim||(rLength=codePointCount(rDelim),rLength!==lLength))continue;let isCjkAdjacent=isCjkAdjacentToDelimiter(rMatch,clippedMaskedSrc);if((rMatch[3]||rMatch[4])&&!isCjkAdjacent){delimTotal+=
612
+ rLength;continue}if(delimTotal-=rLength,delimTotal>0)continue;rLength=Math.min(rLength,rLength+delimTotal);let lastCharLength=rMatch[0].codePointAt(0)>65535?2:1,raw=src.slice(0,lLength+rMatch.index+lastCharLength+rLength),text=raw.slice(lLength,-lLength);return{type:"del",raw,text,tokens:this.lexer.inlineTokens(text)}}}}}}}var SYMBOLS={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",
554
613
  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",
555
614
  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",
556
615
  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",
@@ -616,37 +675,50 @@ slice(indentation).trimEnd()).join(`
616
675
  let index=source2.indexOf(closing,start);for(;index>=0&&isEscaped(source2,index);)index=source2.indexOf(closing,index+closing.length);return index}function looksLikePendingDollarMath(source2){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(source2)}function tokenizeInlineLatex(source2){let opening="",closing="";if(source2.startsWith("$$"))opening="$$",closing="$$";else if(source2.startsWith("\\("))opening="\\(",closing="\\)";else if(source2.startsWith("\\["))opening=
617
676
  "\\[",closing="\\]";else if(source2.startsWith("$")&&!/^\$\s/.test(source2))opening="$",closing="$";else return;let closingIndex=findClosingDelimiter(source2,closing,opening.length);if(closingIndex>=0&&opening==="$"&&(/\s$/.test(source2.slice(opening.length,closingIndex))||/^\d/.test(source2.slice(closingIndex+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(source2.slice(opening.length,closingIndex))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(source2.slice(closingIndex+1))||source2.slice(opening.length,
618
677
  closingIndex).includes("`")))return;if(closingIndex<0){let pendingSource=source2.slice(opening.length);return opening.startsWith("\\")||looksLikePendingDollarMath(pendingSource)?{type:"latex",raw:source2,text:pendingSource,pending:!0}:void 0}let text=source2.slice(opening.length,closingIndex);return!text||text.includes(`
619
- `)?void 0:{type:"latex",raw:source2.slice(0,closingIndex+closing.length),text}}function tokenizeBlockLatex(source2){let dollarMatch=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source2);if(dollarMatch?.[1])return{type:"latexBlock",raw:dollarMatch[0],text:dollarMatch[1].trim()};let bracketMatch=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(source2);if(bracketMatch?.[1])return{type:"latexBlock",raw:bracketMatch[0],text:bracketMatch[1].trim()};let pendingBracket=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.
620
- exec(source2);if(pendingBracket)return{type:"latexBlock",raw:pendingBracket[0],text:pendingBracket[1],pending:!0};let pendingDollar=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source2);if(pendingDollar?.[1]&&looksLikePendingDollarMath(pendingDollar[1]))return{type:"latexBlock",raw:pendingDollar[0],text:pendingDollar[1],pending:!0}}var LATEX_MARKDOWN_EXTENSIONS=[{name:"latexBlock",level:"block",start(source2){let match=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source2);return match?match.index+(match[0].startsWith(
621
- `
678
+ `)?void 0:{type:"latex",raw:source2.slice(0,closingIndex+closing.length),text}}var TABLE_DELIMITER_ROW_REGEX=/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;function containsTableStart(source2){let lines=source2.split(`
679
+ `);for(let index=0;index<lines.length-1;index++){let delimiterRow=lines[index+1];if((delimiterRow.includes("|")||lines[index].includes("|"))&&TABLE_DELIMITER_ROW_REGEX.test(delimiterRow))return!0}return!1}function tokenizeBlockLatex(source2){let dollarMatch=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source2);if(dollarMatch?.[1]&&!containsTableStart(dollarMatch[1]))return{type:"latexBlock",raw:dollarMatch[0],text:dollarMatch[1].trim()};let bracketMatch=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.
680
+ exec(source2);if(bracketMatch?.[1]&&!containsTableStart(bracketMatch[1]))return{type:"latexBlock",raw:bracketMatch[0],text:bracketMatch[1].trim()};let pendingBracket=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(source2);if(pendingBracket?.[1]&&!containsTableStart(pendingBracket[1]))return{type:"latexBlock",raw:pendingBracket[0],text:pendingBracket[1],pending:!0};let pendingDollar=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source2);if(pendingDollar?.[1]&&looksLikePendingDollarMath(pendingDollar[1])&&
681
+ !containsTableStart(pendingDollar[1]))return{type:"latexBlock",raw:pendingDollar[0],text:pendingDollar[1],pending:!0}}var LATEX_MARKDOWN_EXTENSIONS=[{name:"latexBlock",level:"block",start(source2){let match=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source2);return match?match.index+(match[0].startsWith(`
622
682
  `)?1:0):void 0},tokenizer:tokenizeBlockLatex},{name:"latex",level:"inline",start(source2){let indices=[source2.indexOf("$"),source2.indexOf("\\("),source2.indexOf("\\[")].filter(index=>index>=0);return indices.length>0?Math.min(...indices):void 0},tokenizer:tokenizeInlineLatex}];function trimPartialClosingFences(tokens){let token=tokens[tokens.length-1];if(token?.type==="list"){trimPartialClosingFences(token.items[token.items.length-1]?.tokens??[]);return}if(token?.type==="blockquote"){trimPartialClosingFences(
623
- token.tokens??[]);return}if(token?.type!=="code")return;let marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1],lastLine=token.raw.split(`
624
- `).pop();!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)||(token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,""))}var markdownParser=new U;markdownParser.setOptions({tokenizer:new StrictStrikethroughTokenizer});markdownParser.use({extensions:[...LATEX_MARKDOWN_EXTENSIONS]});var lexedMarkdown=[],LEXED_MARKDOWN_KEPT=8,lexedFrom=new WeakMap;function hasLinkDefinitions(tokens){let links=tokens.links;return links!==void 0&&Object.keys(links).
625
- length>0}function lexAddedMarkdown(previous,source2){let last=previous.tokens.length;for(let blocks=0;blocks<2;blocks++)for(last--;last>=0&&previous.tokens[last].type==="space";)last--;if(last<=0)return;let offset=previous.source.length;for(let i=last;i<previous.tokens.length;i++)offset-=previous.tokens[i].raw.length;let added=markdownParser.lexer(JSON.parse(JSON.stringify(source2.slice(offset))));if(hasLinkDefinitions(added))return;let tokens=previous.tokens.slice(0,last),length=offset;for(let token of added)
626
- tokens.push(token),length+=token.raw.length;if(length===source2.length)return lexedFrom.set(tokens,{tokens:new WeakRef(previous.tokens),shared:last}),tokens}function lexMarkdown(source2,complete=!0){if(!markdownCaching){let tokens2=markdownParser.lexer(source2);return trimPartialClosingFences(tokens2),tokens2}let previous=-1;for(let i=lexedMarkdown.length-1;i>=0;i--){let entry=lexedMarkdown[i];if(entry.source===source2){if(lexedMarkdown.splice(i,1),complete&&entry.pieced)break;return lexedMarkdown.
627
- push(entry),entry.tokens}!complete&&entry.resumable&&source2.length>entry.source.length&&(previous<0||entry.source.length>lexedMarkdown[previous].source.length)&&source2.startsWith(entry.source)&&(previous=i)}let tokens=previous>=0?lexAddedMarkdown(lexedMarkdown[previous],source2):void 0,pieced=tokens!==void 0,resumable=pieced;if(!tokens){tokens=markdownParser.lexer(source2);let length=0;for(let token of tokens)length+=token.raw.length;resumable=!hasLinkDefinitions(tokens)&&length===source2.length}
628
- return trimPartialClosingFences(tokens),previous>=0&&lexedMarkdown.splice(previous,1),lexedMarkdown.push({source:source2,tokens,resumable,pieced}),lexedMarkdown.length>LEXED_MARKDOWN_KEPT&&lexedMarkdown.shift(),tokens}var textsWithoutTabs=[],TEXTS_WITHOUT_TABS_KEPT=4;function replaceTabs(text){if(!text.includes(" "))return text;if(!markdownCaching)return text.replace(/\t/g," ");let replaced;for(let i=textsWithoutTabs.length-1;i>=0&&replaced===void 0;i--){let entry=textsWithoutTabs[i];text.length>=
629
- entry.text.length&&text.startsWith(entry.text)&&(replaced=text.length===entry.text.length?entry.replaced:entry.replaced+text.slice(entry.text.length).replace(/\t/g," "),textsWithoutTabs.splice(i,1))}return replaced??=text.replace(/\t/g," "),textsWithoutTabs.push({text,replaced}),textsWithoutTabs.length>TEXTS_WITHOUT_TABS_KEPT&&textsWithoutTabs.shift(),replaced}function sameSettings(a3,b){return a3===b||a3.generation===b.generation&&a3.width===b.width&&a3.paddingX===b.paddingX&&a3.theme===b.theme&&
630
- a3.color===b.color&&a3.bgColor===b.bgColor&&a3.bold===b.bold&&a3.italic===b.italic&&a3.strikethrough===b.strikethrough&&a3.underline===b.underline&&a3.preserveOrderedListMarkers===b.preserveOrderedListMarkers&&a3.preserveBackslashEscapes===b.preserveBackslashEscapes&&a3.renderLatex===b.renderLatex&&a3.capabilities===b.capabilities}var renderedBlocks=new WeakMap,renderedTokens=new WeakMap,markdownCaching=!0;var Markdown=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;cachedTokens;constructor(text,paddingX,paddingY,theme2,defaultTextStyle,options){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.theme=theme2,this.defaultTextStyle=defaultTextStyle,this.options=options?{...options}:{}}setText(text){this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedText=void 0,this.
631
- cachedWidth=void 0,this.cachedLines=void 0,invalidateRenderedMarkdown()}renderSettings(width){let style=this.defaultTextStyle;return{generation:renderedMarkdownGeneration(),width,paddingX:this.paddingX,theme:this.theme,color:style?.color,bgColor:style?.bgColor,bold:style?.bold,italic:style?.italic,strikethrough:style?.strikethrough,underline:style?.underline,preserveOrderedListMarkers:this.options.preserveOrderedListMarkers,preserveBackslashEscapes:this.options.preserveBackslashEscapes,renderLatex:this.
632
- options.renderLatex,capabilities:getCapabilities()}}renderBlock(token,nextTokenType,settings,contentWidth){let known=markdownCaching?renderedBlocks.get(token):void 0;if(known&&known.nextTokenType===nextTokenType&&sameSettings(known.settings,settings))return known.lines;let width=settings.width,leftMargin=" ".repeat(this.paddingX),rightMargin=" ".repeat(this.paddingX),bgFn=this.defaultTextStyle?.bgColor,lines=[],add=line=>{if(isImageLine(line)){lines.push(line);return}let lineWithMargins=leftMargin+
633
- line+rightMargin;if(bgFn)lines.push(applyBackgroundToLine(lineWithMargins,width,bgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);lines.push(lineWithMargins+" ".repeat(paddingNeeded))}};for(let line of this.renderToken(token,contentWidth,nextTokenType))if(isImageLine(line))add(line);else for(let wrappedLine of wrapTextWithAnsi(line,contentWidth))add(wrappedLine);return flattenLines(lines),markdownCaching&&renderedBlocks.set(token,{settings,nextTokenType,
634
- lines}),lines}renderTokens(tokens,settings,contentWidth){let known=renderedTokens.get(tokens);if(known&&sameSettings(known.settings,settings))return known.lines;let lines=[],ends=[],reused=0,from=lexedFrom.get(tokens),fromTokens=from?.tokens.deref(),fromRendered=fromTokens?renderedTokens.get(fromTokens):void 0;from&&fromTokens&&fromRendered&&sameSettings(fromRendered.settings,settings)&&(reused=from.shared,reused>0&&tokens[reused]?.type!==fromTokens[reused]?.type&&reused--,reused>0&&(lines=fromRendered.
635
- lines.slice(0,fromRendered.ends[reused-1]),ends=fromRendered.ends.slice(0,reused)));for(let i=reused;i<tokens.length;i++){for(let line of this.renderBlock(tokens[i],tokens[i+1]?.type,settings,contentWidth))lines.push(line);ends.push(lines.length)}return renderedTokens.set(tokens,{settings,lines,ends}),lines}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;let contentWidth=Math.max(1,width-this.paddingX*2),text=this.options.transform?.(
636
- this.text,contentWidth)??this.text;if(!text||!/\S/.test(text)){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=replaceTabs(text),cached=this.cachedTokens?.deref(),tokens=cached?.source===normalizedText?cached.tokens:void 0;tokens||(tokens=lexMarkdown(normalizedText,this.options.complete),this.cachedTokens=new WeakRef({source:normalizedText,tokens}));let bgFn=this.defaultTextStyle?.bgColor,settings=this.renderSettings(width),
637
- contentLines;if(markdownCaching)contentLines=this.renderTokens(tokens,settings,contentWidth);else{contentLines=[];for(let i=0;i<tokens.length;i++)for(let line of this.renderBlock(tokens[i],tokens[i+1]?.type,settings,contentWidth))contentLines.push(line)}let emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=bgFn?applyBackgroundToLine(emptyLine,width,bgFn):emptyLine;emptyLines.push(line)}flattenLines(emptyLines);let result=emptyLines.concat(contentLines,emptyLines);
638
- return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}applyDefaultStyle(text){if(!this.defaultTextStyle)return text;let styled=text;return this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&
639
- (styled=this.theme.underline(styled)),styled}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let sentinel="\0",styled=sentinel;this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.
640
- underline&&(styled=this.theme.underline(styled));let sentinelIndex=styled.indexOf(sentinel);return this.defaultStylePrefix=sentinelIndex>=0?styled.slice(0,sentinelIndex):"",this.defaultStylePrefix}getStylePrefix(styleFn){let styled=styleFn("\0"),sentinelIndex=styled.indexOf("\0");return sentinelIndex>=0?styled.slice(0,sentinelIndex):""}getDefaultInlineStyleContext(){return{applyText:text=>this.applyDefaultStyle(text),stylePrefix:this.getDefaultStylePrefix()}}renderToken(token,width,nextTokenType,styleContext){
641
- let lines=[];switch(token.type){case"heading":{let headingLevel=token.depth,headingPrefix=`${"#".repeat(headingLevel)} `,headingStyleFn;headingLevel===1?headingStyleFn=text=>this.theme.heading(this.theme.bold(this.theme.underline(text))):headingStyleFn=text=>this.theme.heading(this.theme.bold(text));let headingStyleContext={applyText:headingStyleFn,stylePrefix:this.getStylePrefix(headingStyleFn)},headingText=this.renderInlineTokens(token.tokens||[],headingStyleContext),styledHeading=headingLevel>=
642
- 3?headingStyleFn(headingPrefix)+headingText:headingText;lines.push(styledHeading),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"paragraph":{let paragraphText=this.renderInlineTokens(token.tokens||[],styleContext);lines.push(paragraphText),nextTokenType&&nextTokenType!=="list"&&nextTokenType!=="space"&&lines.push("");break}case"text":lines.push(this.renderInlineTokens([token],styleContext));break;case"latexBlock":{let latexToken=token,rendered=!latexToken.pending&&this.options.
643
- renderLatex!==!1?renderLatex(latexToken.text,{display:!0})??latexToken.raw.trim():latexToken.raw.trim();for(let line of rendered.split(`
683
+ token.tokens??[]);return}if(token?.type!=="code")return;let marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1],lastLine=token.raw.slice(token.raw.lastIndexOf(`
684
+ `)+1);!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)||(token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,""))}var markdownParser=new U;markdownParser.setOptions({tokenizer:new StrictStrikethroughTokenizer});markdownParser.use({tokenizer:{emStrong:markedCjkFriendly().tokenizer?.emStrong},extensions:[...LATEX_MARKDOWN_EXTENSIONS]});var lexedInlines=new Map,nextLexedInlines=new Map;function inlineFlags(state){return(state.inLink?1:0)|(state.
685
+ inRawBlock?2:0)|(state.linkEmitted?4:0)}var InlineMemoLexer=class extends T{inlineDepth=0;lex(src){try{return super.lex(src)}finally{lexedInlines=nextLexedInlines,nextLexedInlines=new Map}}inlineTokens(src,tokens=[]){if(this.inlineDepth>0||tokens.length>0||src.includes("[")&&Object.keys(this.tokens.links??{}).length>0){this.inlineDepth++;try{return super.inlineTokens(src,tokens)}finally{this.inlineDepth--}}let state=this.state,flags=inlineFlags(state),next=nextLexedInlines.get(flags);next===void 0&&
686
+ (next=new Map,nextLexedInlines.set(flags,next));let lexed=next.get(src)??lexedInlines.get(flags)?.get(src);if(lexed===void 0){this.inlineDepth++;try{super.inlineTokens(src,tokens)}finally{this.inlineDepth--}lexed={tokens:tokens.slice(),inLink:state.inLink,inRawBlock:state.inRawBlock,linkEmitted:state.linkEmitted}}else{for(let token of lexed.tokens)tokens.push(token);state.inLink=lexed.inLink,state.inRawBlock=lexed.inRawBlock,state.linkEmitted=lexed.linkEmitted}return next.set(src,lexed),tokens}},
687
+ memos=!0;function lexTokens(source2){return memos&&markdownCaching?new InlineMemoLexer(markdownParser.defaults).lex(source2):markdownParser.lexer(source2)}var lastLexed,lastEnd,lexedMarkdown=[],LEXED_MARKDOWN_KEPT=8,lexedFrom=new WeakMap;function hasLinkDefinitions(tokens){let links=tokens.links;return links!==void 0&&Object.keys(links).length>0}function ownString(text){return JSON.parse(JSON.stringify(text))}function sameTokens(a3,b){if(a3===b)return!0;if(typeof a3!="object"||typeof b!="object"||
688
+ a3===null||b===null)return!1;if(Array.isArray(a3)){if(!Array.isArray(b)||a3.length!==b.length)return!1;for(let i=0;i<a3.length;i++)if(!sameTokens(a3[i],b[i]))return!1;return!0}if(Array.isArray(b))return!1;let aFields=a3,bFields=b,keys=Object.keys(aFields);if(keys.length!==Object.keys(bFields).length)return!1;for(let key of keys)if(!Object.hasOwn(bFields,key)||!sameTokens(aFields[key],bFields[key]))return!1;return!0}var fastPaths=!0,SELF_STARTING_BLOCKS=new Set(["code","heading","hr","list","bloc\
689
+ kquote","table","html"]);function lastBlockSettlesOneBefore(tokens,before,last){if(!fastPaths||before<0||!SELF_STARTING_BLOCKS.has(tokens[before].type))return!1;let raw=tokens[last].raw,text=raw.search(/\S/);return text>=0&&raw.includes(`
690
+ `,text)}function lexAddedMarkdown(previous,source2,added){let last=previous.tokens.length,lastBlock=-1;for(let blocks=0;blocks<2;blocks++){for(last--;last>=0&&previous.tokens[last].type==="space";)last--;blocks===1&&lastBlock>=0&&lastBlockSettlesOneBefore(previous.tokens,last,lastBlock)&&(last=lastBlock),blocks===0&&(lastBlock=last)}if(last<=0)return;let offset=previous.source.length;for(let i=last;i<previous.tokens.length;i++)offset-=previous.tokens[i].raw.length;let kept=previous.end,end=ownString(
691
+ added!==void 0&&kept!==void 0&&offset>=kept.start?kept.text.slice(offset-kept.start)+added:source2.slice(offset));lastEnd={start:offset,text:end};let lexedEnd=lexTokens(end);if(hasLinkDefinitions(lexedEnd))return;let tokens=previous.tokens.slice(0,last),length=offset,shared=last;for(let i=0;i<lexedEnd.length;i++){let token=lexedEnd[i],before=previous.tokens[last+i];fastPaths&&shared===last+i&&i<lexedEnd.length-1&&before!==void 0&&before.raw===token.raw&&sameTokens(before,token)&&(token=before,shared++),
692
+ tokens.push(token),length+=token.raw.length}if(length===source2.length)return lexedFrom.set(tokens,{tokens:new WeakRef(previous.tokens),shared}),tokens}function lexMarkdown(source2,complete=!0,extended){if(lastLexed=void 0,lastEnd=void 0,!markdownCaching){let tokens2=markdownParser.lexer(source2);return trimPartialClosingFences(tokens2),tokens2}let known=extended!==void 0&&lexedMarkdown.includes(extended.from)?extended.from:void 0,previous=-1;for(let i=lexedMarkdown.length-1;i>=0;i--){let entry=lexedMarkdown[i];
693
+ if(entry.source.length===source2.length&&entry!==known&&entry.source===source2){if(lexedMarkdown.splice(i,1),complete&&entry.pieced)break;return lexedMarkdown.push(entry),lastLexed=entry,entry.tokens}!complete&&entry.resumable&&source2.length>entry.source.length&&(previous<0||entry.source.length>lexedMarkdown[previous].source.length)&&(entry===known||source2.startsWith(entry.source))&&(previous=i)}let tokens=previous>=0?lexAddedMarkdown(lexedMarkdown[previous],source2,lexedMarkdown[previous]===known?
694
+ extended?.added:void 0):void 0,pieced=tokens!==void 0,resumable=pieced;if(!tokens){tokens=lexTokens(source2),complete&&(lexedInlines=new Map);let length=0;for(let token of tokens)length+=token.raw.length;resumable=!hasLinkDefinitions(tokens)&&length===source2.length}return trimPartialClosingFences(tokens),previous>=0&&lexedMarkdown.splice(previous,1),lastLexed={source:source2,tokens,resumable,pieced,...pieced&&lastEnd!==void 0?{end:lastEnd}:{}},lexedMarkdown.push(lastLexed),lexedMarkdown.length>
695
+ LEXED_MARKDOWN_KEPT&&lexedMarkdown.shift(),tokens}var textsWithoutTabs=[],TEXTS_WITHOUT_TABS_KEPT=4;function replaceTabs(text){let none=()=>{};if(!text.includes(" "))return{text,remember:none};if(!markdownCaching)return{text:text.replace(/\t/g," "),remember:none};let replaced,extended;for(let i=textsWithoutTabs.length-1;i>=0&&replaced===void 0;i--){let entry=textsWithoutTabs[i];if(text.length>=entry.text.length&&text.startsWith(entry.text)){if(text.length===entry.text.length)replaced=entry.replaced;else{
696
+ let added=ownString(text.slice(entry.text.length)).replace(/\t/g," ");replaced=entry.replaced+added,entry.lexed!==void 0&&(extended={from:entry.lexed,added})}textsWithoutTabs.splice(i,1)}}replaced??=text.replace(/\t/g," ");let kept={text,replaced};return textsWithoutTabs.push(kept),textsWithoutTabs.length>TEXTS_WITHOUT_TABS_KEPT&&textsWithoutTabs.shift(),{text:replaced,...extended===void 0?{}:{extended},remember:lexed=>{kept.lexed=lexed}}}function sameSettings(a3,b){return a3===b||a3.generation===
697
+ b.generation&&a3.width===b.width&&a3.paddingX===b.paddingX&&a3.theme===b.theme&&a3.color===b.color&&a3.bgColor===b.bgColor&&a3.bold===b.bold&&a3.italic===b.italic&&a3.strikethrough===b.strikethrough&&a3.underline===b.underline&&a3.preserveOrderedListMarkers===b.preserveOrderedListMarkers&&a3.preserveBackslashEscapes===b.preserveBackslashEscapes&&a3.renderLatex===b.renderLatex&&a3.capabilities===b.capabilities}var renderedBlocks=new WeakMap,renderedTokens=new WeakMap,markdownCaching=!0;var Markdown=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;cachedTokens;wraps=new Map;nextWraps=new Map;live={array:new LiveLineArray,ends:[],substituted:!1};constructor(text,paddingX,paddingY,theme2,defaultTextStyle,options){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.theme=theme2,this.defaultTextStyle=defaultTextStyle,this.options=options?{...options}:{}}setText(text){this.text=text,this.cachedText=void 0,
698
+ this.cachedWidth=void 0,this.cachedLines=void 0,reportRenderChange(this)}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,invalidateRenderedMarkdown(),reportRenderChange(this)}renderSettings(width){let style=this.defaultTextStyle;return{generation:renderedMarkdownGeneration(),width,paddingX:this.paddingX,theme:this.theme,color:style?.color,bgColor:style?.bgColor,bold:style?.bold,italic:style?.italic,strikethrough:style?.strikethrough,underline:style?.underline,
699
+ preserveOrderedListMarkers:this.options.preserveOrderedListMarkers,preserveBackslashEscapes:this.options.preserveBackslashEscapes,renderLatex:this.options.renderLatex,capabilities:getCapabilities()}}wrapLine(line,width){if(!markdownCaching||!memos)return wrapTextWithAnsi(line,width);let next=this.nextWraps.get(width);next===void 0&&(next=new Map,this.nextWraps.set(width,next));let wrapped=next.get(line)??this.wraps.get(width)?.get(line)??wrapTextWithAnsi(line,width);return next.set(line,wrapped),
700
+ wrapped}renderBlock(token,nextTokenType,settings,contentWidth){let known=markdownCaching?renderedBlocks.get(token):void 0;if(known&&known.nextTokenType===nextTokenType&&sameSettings(known.settings,settings))return known.lines;let width=settings.width,leftMargin=" ".repeat(this.paddingX),rightMargin=" ".repeat(this.paddingX),bgFn=this.defaultTextStyle?.bgColor,lines=[],add=line=>{if(isImageLine(line)){lines.push(line);return}let lineWithMargins=leftMargin+line+rightMargin;if(bgFn)lines.push(applyBackgroundToLine(
701
+ lineWithMargins,width,bgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);lines.push(lineWithMargins+" ".repeat(paddingNeeded))}};for(let line of this.renderToken(token,contentWidth,nextTokenType))if(isImageLine(line))add(line);else for(let wrappedLine of this.wrapLine(line,contentWidth))add(wrappedLine);return flattenLines(lines),markdownCaching&&renderedBlocks.set(token,{settings,nextTokenType,lines}),lines}renderTokens(tokens,settings,contentWidth){
702
+ let known=renderedTokens.get(tokens);if(known&&sameSettings(known.settings,settings))return known.lines;let lines=[],ends=[],reused=0,from=lexedFrom.get(tokens),fromTokens=from?.tokens.deref(),fromRendered=fromTokens?renderedTokens.get(fromTokens):void 0;from&&fromTokens&&fromRendered&&sameSettings(fromRendered.settings,settings)&&(reused=from.shared,reused>0&&tokens[reused]?.type!==fromTokens[reused]?.type&&reused--,reused>0&&(lines=fromRendered.lines.slice(0,fromRendered.ends[reused-1]),ends=fromRendered.
703
+ ends.slice(0,reused)));for(let i=reused;i<tokens.length;i++){for(let line of this.renderBlock(tokens[i],tokens[i+1]?.type,settings,contentWidth))lines.push(line);ends.push(lines.length)}return renderedTokens.set(tokens,{settings,lines,ends}),lines}tokensFor(width){let contentWidth=Math.max(1,width-this.paddingX*2),text=this.options.transform?.(this.text,contentWidth)??this.text;if(!text||!/\S/.test(text))return;let normalized=replaceTabs(text),normalizedText=normalized.text,cached=this.cachedTokens?.
704
+ deref(),tokens=cached?.source.length===normalizedText.length&&cached.source===normalizedText?cached.tokens:void 0;return tokens||(tokens=lexMarkdown(normalizedText,this.options.complete,normalized.extended),normalized.remember(lastLexed?.tokens===tokens?lastLexed:void 0),this.cachedTokens=new WeakRef({source:normalizedText,tokens})),{tokens,contentWidth}}paddingLines(width){let bgFn=this.defaultTextStyle?.bgColor,emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=bgFn?
705
+ applyBackgroundToLine(emptyLine,width,bgFn):emptyLine;emptyLines.push(line)}return flattenLines(emptyLines),emptyLines}keepWraps(){this.nextWraps.size>0&&(this.wraps=this.nextWraps,this.nextWraps=new Map)}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;let rendered=this.cachedText===this.text&&this.cachedWidth===width,prepared=this.tokensFor(width);if(!prepared){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,
706
+ this.cachedLines=result2,result2}let{tokens,contentWidth}=prepared,settings=this.renderSettings(width),contentLines;if(markdownCaching)contentLines=this.renderTokens(tokens,settings,contentWidth);else{contentLines=[];for(let i=0;i<tokens.length;i++)for(let line of this.renderBlock(tokens[i],tokens[i+1]?.type,settings,contentWidth))contentLines.push(line)}let emptyLines=this.paddingLines(width),result=emptyLines.concat(contentLines,emptyLines);return this.keepWraps(),this.cachedText=this.text,this.
707
+ cachedWidth=width,this.cachedLines=result,result.length>0||rendered?result:(reportRenderChange(this),[""])}renderLive(width){let live=this.live,lines=live.array,rendered=this.cachedText===this.text&&this.cachedWidth===width;if(rendered&&live.text===this.text&&live.width===width)return live.substituted&&(lines.edit(0),live.substituted=!1),lines;let prepared=this.tokensFor(width);if(live.text=this.text,live.width=width,this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=void 0,!prepared)
708
+ return lines.lines.length>0&&lines.edit(0),live.tokens=void 0,live.settings=void 0,live.substituted=!1,lines;let{tokens,contentWidth}=prepared,settings=this.renderSettings(width),before=live.tokens,sameContent=markdownCaching&&before!==void 0&&!live.substituted&&live.settings!==void 0&&sameSettings(live.settings,settings);if(!(sameContent&&before===tokens)){let reused=0,from=sameContent?lexedFrom.get(tokens):void 0;from&&before!==void 0&&from.tokens.deref()===before&&(reused=from.shared,reused>0&&
709
+ tokens[reused]?.type!==before[reused]?.type&&reused--);let padding=this.paddingLines(width),ends=live.ends;if(reused>0)lines.edit(padding.length+ends[reused-1]),ends.length=reused;else{lines.edit(0),ends.length=0;for(let line of padding)lines.lines.push(line)}let contentLength=reused>0?ends[reused-1]:0;for(let i=reused;i<tokens.length;i++){let blockLines=this.renderBlock(tokens[i],tokens[i+1]?.type,settings,contentWidth);for(let line of blockLines)lines.lines.push(line);contentLength+=blockLines.
710
+ length,ends.push(contentLength)}for(let line of padding)lines.lines.push(line);this.keepWraps()}return live.tokens=tokens,live.settings=settings,live.substituted=!1,lines.lines.length===0&&!rendered&&(lines.edit(0),lines.lines.push(""),live.substituted=!0,reportRenderChange(this)),lines}applyDefaultStyle(text){if(!this.defaultTextStyle)return text;let styled=text;return this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),
711
+ this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled)),styled}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let sentinel="\0",styled=sentinel;this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.
712
+ bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled));let sentinelIndex=styled.indexOf(sentinel);return this.defaultStylePrefix=sentinelIndex>=0?styled.slice(0,sentinelIndex):"",this.defaultStylePrefix}getStylePrefix(styleFn){let styled=styleFn("\0"),sentinelIndex=styled.indexOf("\0");return sentinelIndex>=0?styled.slice(0,
713
+ sentinelIndex):""}getDefaultInlineStyleContext(){return{applyText:text=>this.applyDefaultStyle(text),stylePrefix:this.getDefaultStylePrefix()}}renderToken(token,width,nextTokenType,styleContext){let lines=[];switch(token.type){case"heading":{let headingLevel=token.depth,headingPrefix=`${"#".repeat(headingLevel)} `,headingStyleFn;headingLevel===1?headingStyleFn=text=>this.theme.heading(this.theme.bold(this.theme.underline(text))):headingStyleFn=text=>this.theme.heading(this.theme.bold(text));let headingStyleContext={
714
+ applyText:headingStyleFn,stylePrefix:this.getStylePrefix(headingStyleFn)},headingText=this.renderInlineTokens(token.tokens||[],headingStyleContext),styledHeading=headingLevel>=3?headingStyleFn(headingPrefix)+headingText:headingText;lines.push(styledHeading),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"paragraph":{let paragraphText=this.renderInlineTokens(token.tokens||[],styleContext);lines.push(paragraphText),nextTokenType&&nextTokenType!=="list"&&nextTokenType!=="space"&&lines.
715
+ push("");break}case"text":lines.push(this.renderInlineTokens([token],styleContext));break;case"latexBlock":{let latexToken=token,rendered=!latexToken.pending&&this.options.renderLatex!==!1?renderLatex(latexToken.text,{display:!0})??latexToken.raw.trim():latexToken.raw.trim();for(let line of rendered.split(`
644
716
  `))lines.push(this.applyDefaultStyle(line));nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"code":{let indent=this.theme.codeBlockIndent??" ";if(lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang||""}`)),this.theme.highlightCode){let highlightedLines=this.theme.highlightCode(token.text,token.lang);for(let hlLine of highlightedLines)lines.push(`${indent}${hlLine}`)}else{let codeLines=token.text.split(`
645
717
  `);for(let codeLine of codeLines)lines.push(`${indent}${this.theme.codeBlock(codeLine)}`)}lines.push(this.theme.codeBlockBorder("```")),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"list":{let listLines=this.renderList(token,0,width,styleContext);lines.push(...listLines);break}case"table":{let tableLines=this.renderTable(token,width,nextTokenType,styleContext);lines.push(...tableLines);break}case"blockquote":{let quoteStyle=text=>this.theme.quote(this.theme.italic(text)),quoteStylePrefix=this.
646
718
  getStylePrefix(quoteStyle),applyQuoteStyle=line=>{if(!quoteStylePrefix)return quoteStyle(line);let lineWithReappliedStyle=line.replace(/\x1b\[0m/g,`\x1B[0m${quoteStylePrefix}`);return quoteStyle(lineWithReappliedStyle)},quoteContentWidth=Math.max(1,width-2),quoteInlineStyleContext={applyText:text=>text,stylePrefix:quoteStylePrefix},quoteTokens=token.tokens||[],renderedQuoteLines=[];for(let i=0;i<quoteTokens.length;i++){let quoteToken=quoteTokens[i],nextQuoteToken=quoteTokens[i+1];renderedQuoteLines.
647
- push(...this.renderToken(quoteToken,quoteContentWidth,nextQuoteToken?.type,quoteInlineStyleContext))}for(;renderedQuoteLines.length>0&&renderedQuoteLines[renderedQuoteLines.length-1]==="";)renderedQuoteLines.pop();for(let quoteLine of renderedQuoteLines){let styledLine=applyQuoteStyle(quoteLine),wrappedLines=wrapTextWithAnsi(styledLine,quoteContentWidth);for(let wrappedLine of wrappedLines)lines.push(this.theme.quoteBorder("\u2502 ")+wrappedLine)}nextTokenType&&nextTokenType!=="space"&&lines.push(
648
- "");break}case"hr":lines.push(this.theme.hr("\u2500".repeat(Math.min(width,80)))),nextTokenType&&nextTokenType!=="space"&&lines.push("");break;case"html":"raw"in token&&typeof token.raw=="string"&&lines.push(this.applyDefaultStyle(token.raw.trim()));break;case"space":lines.push("");break;default:"text"in token&&typeof token.text=="string"&&lines.push(token.text)}return lines}renderInlineTokens(tokens,styleContext){let result="",resolvedStyleContext=styleContext??this.getDefaultInlineStyleContext(),
649
- {applyText,stylePrefix}=resolvedStyleContext,applyTextWithNewlines=text=>text.split(`
719
+ push(...this.renderToken(quoteToken,quoteContentWidth,nextQuoteToken?.type,quoteInlineStyleContext))}for(;renderedQuoteLines.length>0&&renderedQuoteLines[renderedQuoteLines.length-1]==="";)renderedQuoteLines.pop();for(let quoteLine of renderedQuoteLines){let styledLine=applyQuoteStyle(quoteLine),wrappedLines=this.wrapLine(styledLine,quoteContentWidth);for(let wrappedLine of wrappedLines)lines.push(this.theme.quoteBorder("\u2502 ")+wrappedLine)}nextTokenType&&nextTokenType!=="space"&&lines.push("");
720
+ break}case"hr":lines.push(this.theme.hr("\u2500".repeat(Math.min(width,80)))),nextTokenType&&nextTokenType!=="space"&&lines.push("");break;case"html":"raw"in token&&typeof token.raw=="string"&&lines.push(this.applyDefaultStyle(token.raw.trim()));break;case"space":lines.push("");break;default:"text"in token&&typeof token.text=="string"&&lines.push(token.text)}return lines}renderInlineTokens(tokens,styleContext){let result="",resolvedStyleContext=styleContext??this.getDefaultInlineStyleContext(),{
721
+ applyText,stylePrefix}=resolvedStyleContext,applyTextWithNewlines=text=>text.split(`
650
722
  `).map(segment=>applyText(segment)).join(`
651
723
  `);for(let token of tokens)switch(token.type){case"latex":{let latexToken=token,rendered=!latexToken.pending&&this.options.renderLatex!==!1?renderLatex(latexToken.text)??latexToken.raw:latexToken.raw;result+=applyTextWithNewlines(rendered);break}case"escape":result+=applyTextWithNewlines(this.options.preserveBackslashEscapes?token.raw:token.text);break;case"text":token.tokens&&token.tokens.length>0?result+=this.renderInlineTokens(token.tokens,resolvedStyleContext):result+=applyTextWithNewlines(token.
652
724
  text);break;case"paragraph":result+=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);break;case"strong":{let boldContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.bold(boldContent)+stylePrefix;break}case"em":{let italicContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.italic(italicContent)+stylePrefix;break}case"codespan":result+=this.theme.code(token.text)+stylePrefix;break;case"link":{let linkText=this.
@@ -654,7 +726,7 @@ renderInlineTokens(token.tokens||[],resolvedStyleContext),styledLink=this.theme.
654
726
  `;break;case"del":{let delContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.strikethrough(delContent)+stylePrefix;break}case"html":"raw"in token&&typeof token.raw=="string"&&(result+=applyTextWithNewlines(token.raw));break;default:"text"in token&&typeof token.text=="string"&&(result+=applyTextWithNewlines(token.text))}for(;stylePrefix&&result.endsWith(stylePrefix);)result=result.slice(0,-stylePrefix.length);return result}getOrderedListMarker(item){let match=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.
655
727
  exec(item.raw);return match?`${match[1]} `:void 0}getUnorderedListMarker(item){let match=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(item.raw);return match?`${match[1]} `:void 0}renderList(token,depth,width,styleContext){let lines=[],indent=" ".repeat(depth),startNumber=typeof token.start=="number"?token.start:1;for(let i=0;i<token.items.length;i++){let item=token.items[i],isLastItem=i===token.items.length-1,bullet=token.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(
656
728
  item)??`${startNumber+i}. `:`${startNumber+i}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(item)??"- ":"- ",taskMarker=item.task?`[${item.checked?"x":" "}] `:"",marker=bullet+taskMarker,firstPrefix=indent+this.theme.listBullet(marker),continuationPrefix=indent+" ".repeat(visibleWidth(marker)),itemWidth=Math.max(1,width-visibleWidth(firstPrefix)),renderedAnyLine=!1;for(let itemToken of item.tokens){if(itemToken.type==="list"){lines.push(...this.renderList(itemToken,depth+
657
- 1,width,styleContext)),renderedAnyLine=!0;continue}let itemLines=this.renderToken(itemToken,itemWidth,void 0,styleContext);for(let line of itemLines)for(let wrappedLine of wrapTextWithAnsi(line,itemWidth)){let linePrefix=renderedAnyLine?continuationPrefix:firstPrefix;lines.push(linePrefix+wrappedLine),renderedAnyLine=!0}}renderedAnyLine||lines.push(firstPrefix),token.loose&&!isLastItem&&lines.push("")}return lines}getLongestWordWidth(text,maxWidth){let words=text.split(/\s+/).filter(word=>word.length>
729
+ 1,width,styleContext)),renderedAnyLine=!0;continue}let itemLines=this.renderToken(itemToken,itemWidth,void 0,styleContext);for(let line of itemLines)for(let wrappedLine of this.wrapLine(line,itemWidth)){let linePrefix=renderedAnyLine?continuationPrefix:firstPrefix;lines.push(linePrefix+wrappedLine),renderedAnyLine=!0}}renderedAnyLine||lines.push(firstPrefix),token.loose&&!isLastItem&&lines.push("")}return lines}getLongestWordWidth(text,maxWidth){let words=text.split(/\s+/).filter(word=>word.length>
658
730
  0),longest=0;for(let word of words)longest=Math.max(longest,visibleWidth(word));return maxWidth===void 0?longest:Math.min(longest,maxWidth)}wrapCellText(text,maxWidth,stylePrefix=""){let lines=wrapTextWithAnsi(text,Math.max(1,maxWidth));return lines.map((line,index)=>{let styleReset=index<lines.length-1?"\x1B[22;23;24;25;27;28;29;39m":"";return`${line}${styleReset}${stylePrefix}`})}renderTable(token,availableWidth,nextTokenType,styleContext){let lines=[],numCols=token.header.length;if(numCols===
659
731
  0)return lines;let borderOverhead=3*numCols+1,availableForCells=availableWidth-borderOverhead;if(availableForCells<numCols){let fallbackLines=token.raw?wrapTextWithAnsi(token.raw,availableWidth):[];return nextTokenType&&nextTokenType!=="space"&&fallbackLines.push(""),fallbackLines}let maxUnbrokenWordWidth=30,naturalWidths=[],minWordWidths=[];for(let i=0;i<numCols;i++){let headerText=this.renderInlineTokens(token.header[i].tokens||[],styleContext);naturalWidths[i]=visibleWidth(headerText),minWordWidths[i]=
660
732
  Math.max(1,this.getLongestWordWidth(headerText,maxUnbrokenWordWidth))}for(let row of token.rows)for(let i=0;i<row.length;i++){let cellText=this.renderInlineTokens(row[i].tokens||[],styleContext);naturalWidths[i]=Math.max(naturalWidths[i]||0,visibleWidth(cellText)),minWordWidths[i]=Math.max(minWordWidths[i]||1,this.getLongestWordWidth(cellText,maxUnbrokenWordWidth))}let minColumnWidths=minWordWidths,minCellsWidth=minColumnWidths.reduce((a3,b)=>a3+b,0);if(minCellsWidth>availableForCells){minColumnWidths=
@@ -664,8 +736,8 @@ minWidthDelta=Math.max(0,naturalWidth-minWidth),grow=0;return totalGrowPotential
664
736
  join("\u2500\u252C\u2500")}\u2500\u2510`);let headerCellLines=token.header.map((cell,i)=>{let text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix)}),headerLineCount=Math.max(...headerCellLines.map(c2=>c2.length));for(let lineIdx=0;lineIdx<headerLineCount;lineIdx++){let rowParts=headerCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"",padded=text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)));
665
737
  return this.theme.bold(padded)});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}let separatorLine=`\u251C\u2500${columnWidths.map(w2=>"\u2500".repeat(w2)).join("\u2500\u253C\u2500")}\u2500\u2524`;lines.push(separatorLine);for(let rowIndex=0;rowIndex<token.rows.length;rowIndex++){let rowCellLines=token.rows[rowIndex].map((cell,i)=>{let text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix)}),rowLineCount=Math.max(
666
738
  ...rowCellLines.map(c2=>c2.length));for(let lineIdx=0;lineIdx<rowLineCount;lineIdx++){let rowParts=rowCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"";return text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)))});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}rowIndex<token.rows.length-1&&lines.push(separatorLine)}let bottomBorderCells=columnWidths.map(w2=>"\u2500".repeat(w2));return lines.push(`\u2514\u2500${bottomBorderCells.join("\u2500\u2534\u2500")}\
667
- \u2500\u2518`),nextTokenType&&nextTokenType!=="space"&&lines.push(""),lines}};markStableRender(Markdown);var MouseRegion=class{child;onMouse;copiedLines;constructor(child,onMouse){this.child=child,this.onMouse=onMouse}render(width){let lines=renderSharedLines(this.child,width);if(isStableRender(this.child))return lines;let copied=this.copiedLines;return copied!==void 0&&copied.length===lines.length&&copied.every((line,i)=>line===lines[i])?copied:(this.copiedLines=lines.slice(),this.copiedLines)}handleMouse(event){return dispatchMouseEvent(this.child,event)??this.onMouse(event)}invalidate(){this.copiedLines=
668
- void 0,this.child.invalidate()}};markStableRender(MouseRegion);var ScrollView=class extends Container{child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(component,options={}){if(super(),options.axis!==void 0&&options.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${options.axis}`);this.
739
+ \u2500\u2518`),nextTokenType&&nextTokenType!=="space"&&lines.push(""),lines}};markStableRender(Markdown);markReportsChanges(Markdown);markLiveRender(Markdown.prototype.render,function(width){return this.renderLive(width)});var MouseRegion=class{child;onMouse;copiedLines;constructor(child,onMouse){this.child=child,this.onMouse=onMouse}render(width){let lines=renderChildLines(this,this.child,width);if(setSubtreeReportsChanges(this,reportsChanges(this.child)),isStableRender(this.child))return lines;let copied=this.copiedLines;return copied!==void 0&&copied.length===lines.length&&copied.every((line,i)=>line===lines[i])?copied:(this.copiedLines=lines.slice(),this.copiedLines)}handleMouse(event){return dispatchMouseEvent(
740
+ this.child,event)??this.onMouse(event)}invalidate(){this.copiedLines=void 0,this.child.invalidate(),reportRenderChange(this)}static renderLive(region,width){setRenderOwner(region.child,region);let lines=renderLiveLines(region.child,width);return setSubtreeReportsChanges(region,reportsChanges(region.child)),lines}};markStableRender(MouseRegion);markReportsChanges(MouseRegion);markLiveRender(MouseRegion.prototype.render,function(width){return MouseRegion.renderLive(this,width)});var ScrollView=class extends Container{child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(component,options={}){if(super(),options.axis!==void 0&&options.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${options.axis}`);this.
669
741
  child=component,this.children.push(component),this.followEnd=(options.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=options.primary??!1,this.overscroll=options.overscroll??"chain",this.currentScrollbar=options.scrollbar??"hidden",this.scrollbarTrackStyle=options.scrollbarTrackStyle??(text=>`\x1B[90m${text}\x1B[39m`),this.scrollbarThumbStyle=options.scrollbarThumbStyle??(text=>`\x1B[37m${text}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(options.scrollbarHideDelayMs??
670
742
  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(scrollbar){scrollbar!==this.currentScrollbar&&(this.
671
743
  currentScrollbar=scrollbar,scrollbar!=="auto"?this.hideTransientScrollbar():this.scrollbarActive&&this.markScrollbarActivity(),this.requestRenderCallback?.())}getContentWidth(width){return this.scrollbar==="always"&&width>1?width-1:width}markScrollbarActivity(){this.scrollbar!=="auto"||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=!0,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=
@@ -687,7 +759,7 @@ itemIndex,{handled:!0,focus:!0};if(event.type==="click")return this.selectedInde
687
759
  matches(data,"tui.select.down")){if(displayItems.length===0)return;this.selectedIndex=this.selectedIndex===displayItems.length-1?0:this.selectedIndex+1}else kb.matches(data,"tui.select.confirm")||data===" "&&(!this.searchEnabled||this.searchInput?.getValue().length===0)?this.activateItem():kb.matches(data,"tui.select.cancel")?this.onCancel():this.searchEnabled&&this.searchInput&&(this.searchInput.handleInput(data),this.applyFilter(this.searchInput.getValue()))}getDisplayItems(){return this.searchEnabled?
688
760
  this.filteredItems:this.items}getVisibleRange(displayItems){let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),displayItems.length-this.maxVisible));return{startIndex,endIndex:Math.min(startIndex+this.maxVisible,displayItems.length)}}activateItem(){let item=this.getDisplayItems()[this.selectedIndex];if(item){if(item.submenu)this.submenuItemIndex=this.selectedIndex,this.submenuComponent=item.submenu(item.currentValue,(selectedValue,options)=>{selectedValue!==void 0&&
689
761
  (item.currentValue=selectedValue,this.onChange(item.id,selectedValue)),options?.navigateTo&&(this.navigateAfterClose=options.navigateTo),this.closeSubmenu()});else if(item.values&&item.values.length>0){let nextIndex=(item.values.indexOf(item.currentValue)+1)%item.values.length,newValue=item.values[nextIndex];item.currentValue=newValue,this.onChange(item.id,newValue)}}}closeSubmenu(){if(this.submenuComponent=null,this.navigateAfterClose!==null){let id=this.navigateAfterClose;this.navigateAfterClose=
690
- null,this.submenuItemIndex=null,this.selectItem(id),this.activateItem()}else this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null)}applyFilter(query){this.filteredItems=fuzzyFilter(this.items,query,item=>item.label),this.selectedIndex=0}addHintLine(lines,width){lines.push(""),lines.push(truncateToWidth(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"),width))}};var Spacer=class{lines;renderedLines=[];renderedCount=0;constructor(lines=1){this.lines=lines}setLines(lines){this.lines=lines}invalidate(){}render(_width){if(this.renderedCount!==this.lines){let result=[];for(let i=0;i<this.lines;i++)result.push("");this.renderedLines=result,this.renderedCount=this.lines}return this.renderedLines}};markStableRender(Spacer);var TruncatedText=class{text;paddingX;paddingY;constructor(text,paddingX=0,paddingY=0){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY}invalidate(){}render(width){let result=[],emptyLine=" ".repeat(width);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);let availableWidth=Math.max(1,width-this.paddingX*2),singleLineText=this.text,newlineIndex=this.text.indexOf(`
762
+ null,this.submenuItemIndex=null,this.selectItem(id),this.activateItem()}else this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null)}applyFilter(query){this.filteredItems=fuzzyFilter(this.items,query,item=>item.label),this.selectedIndex=0}addHintLine(lines,width){lines.push(""),lines.push(truncateToWidth(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"),width))}};var Spacer=class{lines;renderedLines=[];renderedCount=0;constructor(lines=1){this.lines=lines}setLines(lines){this.lines=lines,reportRenderChange(this)}invalidate(){}render(_width){if(this.renderedCount!==this.lines){let result=[];for(let i=0;i<this.lines;i++)result.push("");this.renderedLines=result,this.renderedCount=this.lines}return this.renderedLines}};markStableRender(Spacer);markReportsChanges(Spacer);var TruncatedText=class{text;paddingX;paddingY;constructor(text,paddingX=0,paddingY=0){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY}invalidate(){}render(width){let result=[],emptyLine=" ".repeat(width);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);let availableWidth=Math.max(1,width-this.paddingX*2),singleLineText=this.text,newlineIndex=this.text.indexOf(`
691
763
  `);newlineIndex!==-1&&(singleLineText=this.text.substring(0,newlineIndex));let displayText=truncateToWidth(singleLineText,availableWidth),leftPadding=" ".repeat(this.paddingX),rightPadding=" ".repeat(this.paddingX),lineWithPadding=leftPadding+displayText+rightPadding,lineVisibleWidth=visibleWidth(lineWithPadding),paddingNeeded=Math.max(0,width-lineVisibleWidth),finalLine=lineWithPadding+" ".repeat(paddingNeeded);result.push(finalLine);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);return result}};var VStack=class extends Stack{layoutType="vstack";constructor(children=[],options={}){super(children,options)}render(width){let viewport={width:Math.max(1,width),height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport),rendered=entries.map(entry=>entry.component.render(viewport.width)),sizes=allocateStackSizes(entries,rendered.map(lines2=>lines2.length),void 0,this.gap),lines=[];for(let index=0;index<entries.length;index++){if(index>0)for(let gap=0;gap<this.gap;gap++)lines.
692
764
  push("");let childLines=rendered[index].slice(0,sizes[index]);lines.push(...childLines);for(let padding=childLines.length;padding<sizes[index];padding++)lines.push("")}return lines}measureHeight(width,heightOf){let viewport={width:Math.max(1,width),height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport),sizes=allocateStackSizes(entries,entries.map(entry=>typeof entry.basis=="number"?0:heightOf(entry.component,viewport.width)),void 0,this.gap),height=Math.max(0,entries.
693
765
  length-1)*this.gap;for(let size of sizes)height+=size;return height}};import{createRequire as createRequire2}from"node:module";import*as path from"node:path";import{createRequire}from"node:module";import{dirname as dirname2,join as join2}from"node:path";import{fileURLToPath}from"node:url";var moduleRequire=createRequire(import.meta.url),TUI_PACKAGE_NAME="@earendil-works/pi-tui";function getNativeModuleCandidates(nativePath,options={}){let moduleDir=dirname2(fileURLToPath(options.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=(options.resolvePackage??moduleRequire.resolve)(TUI_PACKAGE_NAME);candidates.push(join2(dirname2(packageEntry),
@@ -707,7 +779,7 @@ for(let sequence of result.sequences)this.emitDataSequence(sequence);if(this.buf
707
779
  length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(sequence),this.emit("data",sequence)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let sequences=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,sequences}clear(){this.
708
780
  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 fs from"node:fs";import*as path2 from"node:path";function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}var TERMINAL_PROGRESS_KEEPALIVE_MS=1e3,TERMINAL_PROGRESS_ACTIVE_SEQUENCE="\x1B]9;4;3\x07",TERMINAL_PROGRESS_CLEAR_SEQUENCE="\x1B]9;4;0\x07",NATIVE_SHIFT_ENTER_SEQUENCE="\x1B[13;2u",DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7,KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS=150,KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u`,DEVICE_ATTRIBUTES_QUERY="\x1B[c";function parseKeyboardProtocolNegotiationSequence(sequence){let kittyFlags=sequence.match(/^\x1b\[\?(\d+)u$/);
709
781
  if(kittyFlags)return{type:"kitty-flags",flags:Number.parseInt(kittyFlags[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(sequence))return{type:"device-attributes"}}function isKeyboardProtocolNegotiationSequencePrefix(sequence){return sequence==="\x1B["||/^\x1b\[\?[\d;]*$/.test(sequence)}function isAppleTerminalSession(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function refreshTerminalDimensions(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.
710
- pid,"SIGWINCH")}catch{}}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&data==="\r"&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100;function resolveEscapeTimeoutMs(env=process.env){let configured=Number(env.PI_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}var ProcessTerminal=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{
782
+ pid,"SIGWINCH")}catch{}}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&data==="\r"&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100;function resolveEscapeTimeoutMs(env=process.env){let configured=Number(env.HUMAIN_TERMINAL_TUI_ESC_TIMEOUT||env.PI_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}var ProcessTerminal=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{
711
783
  let env=process.env.HUMAIN_TERMINAL_TUI_WRITE_LOG||process.env.PI_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs.statSync(env).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path2.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})();get kittyProtocolActive(){
712
784
  return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){this.inputHandler=onInput,this.resizeHandler=onResize,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),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){
713
785
  this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs()}),this.stdinBuffer.on("data",sequence=>{if(isProgramStatusReply(sequence)){this.programStatusQueryPending&&(this.programStatusQueryPending=!1,this.programStatusSupported=!0,this.writeProgramStatus());return}let negotiation=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiation==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}negotiation&&this.handleKeyboardProtocolNegotiationSequence(
@@ -722,10 +794,11 @@ in32"),input=normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnte
722
794
  enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys();let previousHandler=this.inputHandler;this.inputHandler=void 0;let lastDataTime=Date.now(),onData=()=>{lastDataTime=
723
795
  Date.now()};process.stdin.on("data",onData);let endTime=Date.now()+maxMs;try{for(;;){let now=Date.now(),timeLeft=endTime-now;if(timeLeft<=0||now-lastDataTime>=idleMs)break;await new Promise(resolve=>setTimeout(resolve,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.clearProgressInterval()&&process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus(
724
796
  {state:"clear"})),this.programStatusSupported=!1,this.programStatusQueryPending=!1,process.stdout.write("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),
725
- 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)}write(data){if(process.stdout.write(data),this.writeLogPath)try{fs.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||
726
- Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>0?process.stdout.write(`\x1B[${lines}B`):lines<0&&process.stdout.write(`\x1B[${-lines}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(title){process.stdout.write(`\x1B]0;${title}\
727
- \x07`)}setProgramStatus(status){this.programStatus=status.state==="clear"?void 0:status,this.programStatusSupported&&process.stdout.write(formatProgramStatus(status))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus(this.programStatus))}setProgress(active){active?(process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},
728
- TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var segmenter2=getGraphemeSegmenter(),PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function buildSearchCorpus(lines){let chunks=[],spans=[],textLength=0,pendingSeparator=!1,appendSeparator=()=>{pendingSeparator&&(chunks.push(" "),textLength+=1,pendingSeparator=!1)};for(let row=0;row<lines.length;row++){let line=stripTerminalSequences(lines[row]??""),column=0;if(PRINTABLE_ASCII.test(line)){let index=0;for(;index<line.length;){if(line.charCodeAt(index)===32){textLength>0&&(pendingSeparator=!0),column+=1,index+=
797
+ 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(before,after){let sequence=before;this.progressInterval&&(sequence+=TERMINAL_PROGRESS_CLEAR_SEQUENCE),sequence+="\x1B[?2004l",(this.keyboardProtocolPushed||
798
+ this._kittyProtocolActive)&&(sequence+="\x1B[<u"),this._modifyOtherKeysActive&&(sequence+="\x1B[>4;0m"),sequence+=after;try{fs.writeSync(process.stdout.fd,sequence)}catch{}}write(data){if(process.stdout.write(data),this.writeLogPath)try{fs.appendFileSync(this.writeLogPath,data,{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(lines){lines>0?process.stdout.write(`\x1B[${lines}\
799
+ B`):lines<0&&process.stdout.write(`\x1B[${-lines}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(title){process.stdout.write(`\x1B]0;${title}\x07`)}setProgramStatus(status){this.programStatus=status.state==="clear"?void 0:status,this.programStatusSupported&&process.stdout.write(formatProgramStatus(
800
+ status))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus(this.programStatus))}setProgress(active){active?(process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.
801
+ progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var segmenter2=getGraphemeSegmenter(),PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function buildSearchCorpus(lines){let chunks=[],spans=[],textLength=0,pendingSeparator=!1,appendSeparator=()=>{pendingSeparator&&(chunks.push(" "),textLength+=1,pendingSeparator=!1)};for(let row=0;row<lines.length;row++){let line=stripTerminalSequences(lines[row]??""),column=0;if(PRINTABLE_ASCII.test(line)){let index=0;for(;index<line.length;){if(line.charCodeAt(index)===32){textLength>0&&(pendingSeparator=!0),column+=1,index+=
729
802
  1;continue}let end=index+1;for(;end<line.length&&line.charCodeAt(end)!==32;)end+=1;appendSeparator();let text=line.slice(index,end);chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+text.length,linearColumns:!0}),textLength+=text.length,column+=text.length,index=end}}else for(let grapheme of segmenter2.segment(line)){let text=grapheme.segment,width=visibleWidth(text);if(/^\s+$/u.test(text)){textLength>0&&(pendingSeparator=!0),column+=
730
803
  width;continue}appendSeparator(),chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+width,linearColumns:!1}),textLength+=text.length,column+=width}textLength>0&&(pendingSeparator=!0)}return{text:chunks.join(""),spans}}function normalizeQuery(query){return query.replace(/\s+/gu," ").trim()}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function findSearchCorpusMatches(corpus,normalizedQuery){if(!normalizedQuery)
731
804
  return[];let expression=new RegExp(escapeRegExp(normalizedQuery),"giu"),matches=[],spanIndex=0;for(let match of corpus.text.matchAll(expression)){let start=match.index,end=start+match[0].length;for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=start;)spanIndex+=1;let segments=[];for(let index=spanIndex;index<corpus.spans.length;index++){let span=corpus.spans[index];if(span.textStart>=end)break;if(span.textEnd<=start)continue;let startCol=span.linearColumns?span.startCol+Math.max(
@@ -740,26 +813,26 @@ controlsWidth>availableControlsWidth&&(previousButton="\u2191",nextButton="\u219
740
813
  innerWidth>controlsWidth+outerGapsWidth?1:0,leftRuleWidth=Math.max(0,innerWidth-(showButtons?controlsWidth:0)-outerGapsWidth-rightRuleWidth),previousStart=1+leftRuleWidth+outerGapWidth;return this.previousButtonStart=showButtons?previousStart:-1,this.previousButtonEnd=showButtons?previousStart+visibleWidth(previousButton):-1,this.nextButtonStart=showButtons?this.previousButtonEnd+visibleWidth(separator):-1,this.nextButtonEnd=showButtons?this.nextButtonStart+visibleWidth(nextButton):-1,safeWidth===
741
814
  1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(innerWidth)}\u2510`,`\u2502${content}\u2502`,`\u2514${"\u2500".repeat(leftRuleWidth)}${renderedButtons?" ":""}${renderedButtons}${renderedButtons?" ":""}${"\u2500".repeat(rightRuleWidth)}\u2518`]}};var DEFAULT_DURATION_MS=1e3,AltScreenFlashContainer=class{entries=[];nextId=0;requestRender;constructor(requestRender){this.requestRender=requestRender}flash(message,durationMs=DEFAULT_DURATION_MS){let id=this.nextId++,timer=setTimeout(()=>{let index=this.entries.findIndex(entry=>entry.id===id);index!==-1&&(this.entries.splice(index,1),this.requestRender())},Math.max(0,durationMs));timer.unref(),this.entries.push({id,message,timer}),this.requestRender()}dispose(){for(let entry of this.entries)clearTimeout(
742
815
  entry.timer);this.entries.length=0}invalidate(){}render(width){return this.entries.map(entry=>`\x1B[7m${truncateToWidth(` ${entry.message} `,width,"")}\x1B[27m`)}};var OSC133_ZONE_PREFIX=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function intersect(a3,b){let x2=Math.max(a3.x,b.x),y2=Math.max(a3.y,b.y),right=Math.min(a3.x+a3.width,b.x+b.width),bottom=Math.min(a3.y+a3.height,b.y+b.height);return{x:x2,y:y2,width:Math.max(0,right-x2),height:Math.max(0,bottom-y2)}}function renderCached(context,component,width){let safeWidth=Math.max(1,Math.floor(width)),widths=context.renderCache.get(component);widths||(widths=new Map,context.renderCache.set(component,widths));let lines=widths.
743
- get(safeWidth);return lines||(lines=renderSharedLines(component,safeWidth),widths.set(safeWidth,lines)),lines}function measureHeight(context,component,width){return component instanceof VStack&&component.render===VStack.prototype.render?component.measureHeight(Math.max(1,Math.floor(width)),(child,childWidth)=>measureHeight(context,child,childWidth)):renderCached(context,component,width).length}function measureWidth(context,component,width){return renderCached(context,component,width).reduce((max,line)=>Math.
744
- max(max,visibleWidth(line)),0)}function withParent(box,parent){return box.parent=parent,box}function translateBox(box,deltaY){box.rect.y+=deltaY;for(let child of box.children)translateBox(child,deltaY)}function updateClips(box,parentClip){box.clip=intersect(parentClip,box.rect);for(let child of box.children)updateClips(child,box.clip)}function layoutComponent(context,component,x2,y2,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(component);if(!node){let lines=renderCached(
745
- context,component,safeWidth),allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>0){let cursorLine=lines.findIndex(line=>line.includes(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y:y2,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y:y2,width:safeWidth,height:allocatedHeight2}),children:[],lines,lineOffset,layer:0}}if(node.
746
- type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x2,y2-previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.rect.height,viewportHeight=height===void 0?contentHeight:Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);let scrollView=node.state;(node.state.primary||
747
- !context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y:y2,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),box2={component,rect:rect2,clip:childClip,children:[childBox],scrollView,scrollContentLines:renderCached(context,node.component,contentWidth),layer:0};return childBox.parent=box2,updateClips(childBox,childClip),box2}let entries=visibleStackEntries(node.entries,context.viewport),gapTotal=Math.max(0,entries.length-1)*node.gap;if(node.type===
748
- "vstack"){let intrinsicHeights2=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureHeight(context,entry.component,safeWidth)),sizes=allocateStackSizes(entries,intrinsicHeights2,height,node.gap),naturalHeight=sizes.reduce((sum,size)=>sum+size,0)+gapTotal,allocatedHeight2=height===void 0?naturalHeight:Math.max(0,Math.floor(height)),rect2={x:x2,y:y2,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y2;for(let index=0;index<
749
- entries.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=sizes[index]+node.gap;return box2}let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(context,entry.component,Math.max(1,widths[index]))),
750
- allocatedHeight=height===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,y:y2,width:safeWidth,height:allocatedHeight},box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x2;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y2;node.align==="center"?childY+=Math.floor((allocatedHeight-
751
- childHeight)/2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.push({component:entries[index].component,rect:{x:childX,y:childY,width:0,height:childHeight},clip:{x:childX,y:childY,width:0,height:0},children:[],parent:box,layer:0}):box.children.push(withParent(layoutComponent(context,entries[index].component,childX,childY,childWidth,childHeight,box.clip),box)),childX+=childWidth+node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){
752
- if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(line,column),start=graphemeRange?.start??column,end=graphemeRange?.end??column+1,before=sliceByColumn(line,0,start,!0),target=sliceByColumn(line,start,end-start,!0),after=sliceByColumn(line,end,Math.max(0,totalWidth-end),!0),targetPrefix="",targetIndex=0;for(;targetIndex<target.length;){let ansi=extractAnsiCode(target,targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.
753
- max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.max(0,column-start)),cellPaddingAfter=" ".repeat(Math.max(0,end-column-1)),targetStyle=`\x1B[0m\x1B]8;;\x07${preserveTargetBackground?getActiveBackgroundAnsi(targetPrefix):""}`;return`${before}${beforePadding}${targetStyle}${cellPaddingBefore}${replacement}${cellPaddingAfter}${after}`}function getScrollbarGeometry(box,includeHiddenAuto=!1){if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.
754
- rect.height??box.scrollContentLines?.length??0,trackHeight=box.rect.height,canRevealHiddenAuto=includeHiddenAuto&&box.scrollView.scrollbar==="auto"&&contentHeight>trackHeight;if(!box.scrollView.isScrollbarVisible&&!canRevealHiddenAuto)return;let minThumbHeight=Math.min(2,trackHeight),thumbHeight=Math.max(minThumbHeight,Math.min(trackHeight,Math.round(trackHeight*trackHeight/contentHeight))),maxScrollTop=Math.max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===
755
- 0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),column=box.rect.x+box.rect.width-1;if(!(column<box.clip.x||column>=box.clip.x+box.clip.width))return{column,trackTop:box.rect.y,trackHeight,thumbTop:box.rect.y+thumbOffset,thumbHeight,maxScrollTop}}function paintScrollbar(box,screen,totalWidth){let geometry=getScrollbarGeometry(box);if(!(!geometry||!box.scrollView))for(let offset=0;offset<geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.
756
- y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=geometry.thumbTop&&row<geometry.thumbTop+geometry.thumbHeight?box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive?"\u2588":"\u2503"):box.scrollView.scrollbarTrackStyle("\u2502");screen[row]=replaceScrollbarCell(screen[row]??"",geometry.column,totalWidth,replacement,box.scrollView.scrollbar!=="always")}}function paintBox(box,screen,totalWidth){if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.
757
- rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.y+box.clip.height,screen.length);for(let row=firstRow;row<lastRow;row++){let sourceLine=box.lines[offset+row-box.rect.y];if(sourceLine===void 0)continue;let line=sourceLine.replace(OSC133_ZONE_PREFIX,""),imageMetadata=getKittyImageMetadata(line);if(imageMetadata){let clipBottom=Math.min(screen.length,box.clip.y+box.clip.height),visibleRows=Math.min(imageMetadata.rows,clipBottom-row);visibleRows<imageMetadata.rows&&(line=cropKittyImageLine(
758
- line,0,visibleRows))}box.rect.x===0&&box.rect.width>=totalWidth&&(isImageLine(line)||!screen[row])?screen[row]=line:screen[row]=compositeTuiLine(screen[row]??"",line,box.rect.x,box.rect.width,totalWidth)}}for(let child of box.children)paintBox(child,screen,totalWidth);if(box.scrollView&&box.scrollContentLines&&box.scrollView.scrollTop>0&&box.rect.height>0)for(let imageRow=box.scrollView.scrollTop-1;imageRow>=0;imageRow--){let imageLine=box.scrollContentLines[imageRow]??"",metadata=getKittyImageMetadata(
759
- imageLine);if(metadata){let hiddenRows=box.scrollView.scrollTop-imageRow;if(hiddenRows<metadata.rows){let visibleRows=Math.min(box.rect.height,metadata.rows-hiddenRows),cropped=cropKittyImageLine(imageLine,hiddenRows,visibleRows);box.rect.x===0&&box.rect.width>=totalWidth&&(screen[box.rect.y]=cropped)}break}if(imageLine!=="")break}paintScrollbar(box,screen,totalWidth)}function renderLayoutFrame(root,width,height,requestRender){let safeWidth=Math.max(1,Math.floor(width)),safeHeight=Math.max(1,Math.
760
- floor(height)),context={viewport:{width:safeWidth,height:safeHeight},renderCache:new Map,requestRender,primaryScrollView:void 0},rootBox=layoutComponent(context,root,0,0,safeWidth,safeHeight,{x:0,y:0,width:safeWidth,height:safeHeight}),lines=Array.from({length:safeHeight},()=>"");return paintBox(rootBox,lines,safeWidth),{root:rootBox,width:safeWidth,height:safeHeight,lines,...context.primaryScrollView===void 0?{}:{primaryScrollView:context.primaryScrollView}}}function containsPoint(rect,x2,y2){return x2>=
761
- rect.x&&x2<rect.x+rect.width&&y2>=rect.y&&y2<rect.y+rect.height}function getLayoutBoxesAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){result.push({box,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a3,b)=>b.box.layer-a3.box.layer||b.depth-a3.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(
762
- child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){box.scrollView&&containsPoint(box.rect,x2,y2)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a3,b)=>b.depth-a3.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env=process.env;return process.platform==="darwin"&&env.SSH_CONNECTION===void 0&&env.SSH_CLIENT===void 0&&env.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.isFinite(
816
+ get(safeWidth);return lines||(lines=renderLiveLines(component,safeWidth)?.lines??renderSharedLines(component,safeWidth),widths.set(safeWidth,lines)),lines}function measureHeight(context,component,width){return component instanceof VStack&&component.render===VStack.prototype.render?component.measureHeight(Math.max(1,Math.floor(width)),(child,childWidth)=>measureHeight(context,child,childWidth)):renderCached(context,component,width).length}function measureWidth(context,component,width){return renderCached(
817
+ context,component,width).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)}function withParent(box,parent){return box.parent=parent,box}function translateBox(box,deltaY){box.rect.y+=deltaY;for(let child of box.children)translateBox(child,deltaY)}function updateClips(box,parentClip){box.clip=intersect(parentClip,box.rect);for(let child of box.children)updateClips(child,box.clip)}function layoutComponent(context,component,x2,y2,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(
818
+ component);if(!node){let lines=renderCached(context,component,safeWidth),allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>0){let cursorLine=lines.findIndex(line=>line.includes(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y:y2,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y:y2,width:safeWidth,height:allocatedHeight2}),
819
+ children:[],lines,lineOffset,layer:0}}if(node.type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x2,y2-previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.rect.height,viewportHeight=height===void 0?contentHeight:Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);
820
+ let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y:y2,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),box2={component,rect:rect2,clip:childClip,children:[childBox],scrollView,scrollContentLines:renderCached(context,node.component,contentWidth),layer:0};return childBox.parent=box2,updateClips(childBox,childClip),box2}let entries=visibleStackEntries(node.entries,context.viewport),gapTotal=Math.
821
+ max(0,entries.length-1)*node.gap;if(node.type==="vstack"){let intrinsicHeights2=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureHeight(context,entry.component,safeWidth)),sizes=allocateStackSizes(entries,intrinsicHeights2,height,node.gap),naturalHeight=sizes.reduce((sum,size)=>sum+size,0)+gapTotal,allocatedHeight2=height===void 0?naturalHeight:Math.max(0,Math.floor(height)),rect2={x:x2,y:y2,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,
822
+ rect2),children:[],layer:0},childY=y2;for(let index=0;index<entries.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=sizes[index]+node.gap;return box2}let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(
823
+ context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,y:y2,width:safeWidth,height:allocatedHeight},box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x2;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y2;
824
+ node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.push({component:entries[index].component,rect:{x:childX,y:childY,width:0,height:childHeight},clip:{x:childX,y:childY,width:0,height:0},children:[],parent:box,layer:0}):box.children.push(withParent(layoutComponent(context,entries[index].component,childX,childY,childWidth,childHeight,box.clip),box)),childX+=childWidth+
825
+ node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(line,column),start=graphemeRange?.start??column,end=graphemeRange?.end??column+1,before=sliceByColumn(line,0,start,!0),target=sliceByColumn(line,start,end-start,!0),after=sliceByColumn(line,end,Math.max(0,totalWidth-end),!0),targetPrefix="",targetIndex=0;for(;targetIndex<target.length;){let ansi=extractAnsiCode(target,
826
+ targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.max(0,column-start)),cellPaddingAfter=" ".repeat(Math.max(0,end-column-1)),targetStyle=`\x1B[0m\x1B]8;;\x07${preserveTargetBackground?getActiveBackgroundAnsi(targetPrefix):""}`;return`${before}${beforePadding}${targetStyle}${cellPaddingBefore}${replacement}${cellPaddingAfter}${after}`}function getScrollbarGeometry(box,includeHiddenAuto=!1){
827
+ if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.rect.height??box.scrollContentLines?.length??0,trackHeight=box.rect.height,canRevealHiddenAuto=includeHiddenAuto&&box.scrollView.scrollbar==="auto"&&contentHeight>trackHeight;if(!box.scrollView.isScrollbarVisible&&!canRevealHiddenAuto)return;let minThumbHeight=Math.min(2,trackHeight),thumbHeight=Math.max(minThumbHeight,Math.min(trackHeight,Math.round(trackHeight*trackHeight/contentHeight))),maxScrollTop=Math.
828
+ max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),column=box.rect.x+box.rect.width-1;if(!(column<box.clip.x||column>=box.clip.x+box.clip.width))return{column,trackTop:box.rect.y,trackHeight,thumbTop:box.rect.y+thumbOffset,thumbHeight,maxScrollTop}}function paintScrollbar(box,screen,totalWidth){let geometry=getScrollbarGeometry(box);if(!(!geometry||!box.scrollView))for(let offset=0;offset<
829
+ geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=geometry.thumbTop&&row<geometry.thumbTop+geometry.thumbHeight?box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive?"\u2588":"\u2503"):box.scrollView.scrollbarTrackStyle("\u2502");screen[row]=replaceScrollbarCell(screen[row]??"",geometry.column,totalWidth,replacement,box.scrollView.scrollbar!=="always")}}function paintBox(box,screen,totalWidth){
830
+ if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.y+box.clip.height,screen.length);for(let row=firstRow;row<lastRow;row++){let sourceLine=box.lines[offset+row-box.rect.y];if(sourceLine===void 0)continue;let line=sourceLine.replace(OSC133_ZONE_PREFIX,""),imageMetadata=getKittyImageMetadata(line);if(imageMetadata){let clipBottom=Math.min(screen.length,box.clip.y+box.clip.height),visibleRows=Math.min(imageMetadata.
831
+ rows,clipBottom-row);visibleRows<imageMetadata.rows&&(line=cropKittyImageLine(line,0,visibleRows))}box.rect.x===0&&box.rect.width>=totalWidth&&(isImageLine(line)||!screen[row])?screen[row]=line:screen[row]=compositeTuiLine(screen[row]??"",line,box.rect.x,box.rect.width,totalWidth)}}for(let child of box.children)paintBox(child,screen,totalWidth);if(box.scrollView&&box.scrollContentLines&&box.scrollView.scrollTop>0&&box.rect.height>0)for(let imageRow=box.scrollView.scrollTop-1;imageRow>=0;imageRow--){
832
+ let imageLine=box.scrollContentLines[imageRow]??"",metadata=getKittyImageMetadata(imageLine);if(metadata){let hiddenRows=box.scrollView.scrollTop-imageRow;if(hiddenRows<metadata.rows){let visibleRows=Math.min(box.rect.height,metadata.rows-hiddenRows),cropped=cropKittyImageLine(imageLine,hiddenRows,visibleRows);box.rect.x===0&&box.rect.width>=totalWidth&&(screen[box.rect.y]=cropped)}break}if(imageLine!=="")break}paintScrollbar(box,screen,totalWidth)}function renderLayoutFrame(root,width,height,requestRender){
833
+ let safeWidth=Math.max(1,Math.floor(width)),safeHeight=Math.max(1,Math.floor(height)),context={viewport:{width:safeWidth,height:safeHeight},renderCache:new Map,requestRender,primaryScrollView:void 0},rootBox=layoutComponent(context,root,0,0,safeWidth,safeHeight,{x:0,y:0,width:safeWidth,height:safeHeight}),lines=Array.from({length:safeHeight},()=>"");return paintBox(rootBox,lines,safeWidth),{root:rootBox,width:safeWidth,height:safeHeight,lines,...context.primaryScrollView===void 0?{}:{primaryScrollView:context.
834
+ primaryScrollView}}}function containsPoint(rect,x2,y2){return x2>=rect.x&&x2<rect.x+rect.width&&y2>=rect.y&&y2<rect.y+rect.height}function getLayoutBoxesAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){result.push({box,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a3,b)=>b.box.layer-a3.box.layer||b.depth-a3.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===
835
+ scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){box.scrollView&&containsPoint(box.rect,x2,y2)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a3,b)=>b.depth-a3.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env=process.env;return process.platform==="darwin"&&env.SSH_CONNECTION===void 0&&env.SSH_CLIENT===void 0&&env.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.isFinite(
763
836
  this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let gap=now-this.lastTime,sameGesture=direction===this.lastDirection&&gap<=200;if(this.lastTime=now,this.lastDirection=direction,!sameGesture)return this.averageGap=void 0,this.carry=0,1;if(gap<5)return 1;this.averageGap=this.averageGap===void 0?gap:(this.averageGap+gap)/2;let lines=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,whole=Math.floor(lines);return this.carry=lines-whole,whole}reset(){this.lastTime=Number.
764
837
  NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var ENTER_ALT_SCREEN="\x1B[?1049h",EXIT_ALT_SCREEN="\x1B[?1049l",DISABLE_AUTOWRAP="\x1B[?7l",ENABLE_AUTOWRAP="\x1B[?7h",ENABLE_BUTTON_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",ENABLE_ALL_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",DISABLE_MOUSE="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",FOCUS_IN="\x1B[I",FOCUS_OUT="\x1B[O",BEGIN_SYNCHRONIZED_OUTPUT="\x1B[?2026h",END_SYNCHRONIZED_OUTPUT="\x1B[?2026l",MIN_ROWS_SAVED_BY_SCROLLING=3,OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,
765
838
  OSC133_PROMPT_START=/^\x1b\]133;A(?:\x07|\x1b\\)/,PAGE_SCROLL_OVERLAP=4,ALT_WHEEL_SCROLL_MULTIPLIER=5,MAX_CACHED_OFFSCREEN_KITTY_IMAGES=16,MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES=32*1024*1024,MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES=64*1024*1024,DOUBLE_CLICK_INTERVAL_MS=500,COPY_ERROR_FLASH_DURATION_MS=5e3,TERMINAL_WORD_SELECTION_JOINERS=new Set(["/","-"]),wordSegmenter4=getWordSegmenter(),TuiAltScreen=class extends TuiBase{mode="fullscreen";[VIEWPORT_TUI]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;finishedRows=new Map;finishedRowsWidth=0;imageRows=new Set;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="\
@@ -774,60 +847,61 @@ void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,thi
774
847
  if(this.altScreenActive=!1,options.preserveScreen)this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`);else{let width=Math.max(1,this.terminal.columns),documentLines=this.resolveFakeCursors(this.render(width)).map(line=>line.replace(OSC133_ZONE_PREFIX2,""));this.lastDocument=this.applyLineResets(documentLines.map(line=>line.replaceAll(CURSOR_MARKER,""))).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));
775
848
  let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
776
849
  `),buffer+=`\r\x1B[2K${this.lastDocument[row]??""}`;buffer+=`\x1B[0m${ENABLE_AUTOWRAP}\r
777
- \x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}deleteKittyImages(){return this.imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={
778
- transmissionGeneration:placement.transmissionGeneration,transmissionBytes:placement.transmissionBytes,estimatedDecodedBytes:placement.estimatedDecodedBytes};return cachedImage&&this.uploadedKittyImages.delete(placement.imageId),this.uploadedKittyImages.set(placement.imageId,nextCachedImage),cachedImage?.transmissionGeneration===placement.transmissionGeneration?placement.replacementLine:line}),cachedOffscreenImageCount=0,cachedOffscreenTransmissionBytes=0,cachedOffscreenDecodedBytes=0;for(let[imageId,
779
- cachedImage]of this.uploadedKittyImages)visibleImageIds.has(imageId)||(cachedOffscreenImageCount+=1,cachedOffscreenTransmissionBytes+=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes+=cachedImage.estimatedDecodedBytes);let evictedImageDeletion="";for(let[imageId,cachedImage]of this.uploadedKittyImages){if(cachedOffscreenImageCount<=MAX_CACHED_OFFSCREEN_KITTY_IMAGES&&cachedOffscreenTransmissionBytes<=MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES&&cachedOffscreenDecodedBytes<=MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES)
780
- break;visibleImageIds.has(imageId)||(evictedImageDeletion+=deleteKittyImage(imageId),this.uploadedKittyImages.delete(imageId),cachedOffscreenImageCount-=1,cachedOffscreenTransmissionBytes-=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes-=cachedImage.estimatedDecodedBytes)}return{lines,evictedImageDeletion}}resetRenderState(){this.previousScreen=[],this.finishedRows=new Map,this.imageRows=new Set,this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(lines){
781
- this.getPrimaryScrollView().scrollBy(lines),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(direction){if(!this.currentLayout)return;let scrollView=this.getPrimaryScrollView(),lines=getScrollViewBox(this.currentLayout,scrollView)?.scrollContentLines;if(lines){for(let row=scrollView.scrollTop+direction;row>=0&&row<lines.length;row+=direction)if(OSC133_PROMPT_START.
782
- test(lines[row]??"")){scrollView.scrollTo(row),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let component=new AltScreenSearchComponent(query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={component,index:new AltScreenSearchIndex,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=search,search.overlay=this.showOverlay(component,{anchor:"top-right",width:"\
783
- 40%",minWidth:32,margin:1})}closeSearch(){let search=this.activeSearch;search&&(this.activeSearch=void 0,search.overlay?.hide(),this.requestRender())}updateSearchQuery(query){let search=this.activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){
784
- let search=this.activeSearch;search?.query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x2,y2){let search=this.activeSearch,bounds=search?.overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y2<bounds.row||y2>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y2-bounds.row,x2-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.
785
- getSearchNavigationDirectionAt(event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==0||(event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.
786
- matches=[],search.selectedIndex=-1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",result=search.index.search(lines,search.query),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;
787
- if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.row??0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=
788
- 0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;
789
- let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==
790
- before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.
791
- 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,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),
792
- this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let lines=this.wheelScroll.next(wheelEvent.direction,performance.now()),wheelDelta=wheelEvent.direction*((wheelEvent.button&8)!==0?lines*ALT_WHEEL_SCROLL_MULTIPLIER:lines),event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(
793
- event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):(this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.toggleSearch(),{consume:!0};if(this.activeSearch?.
794
- overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(keybindings.matches(data,"tui.altScreen.pageUp"))return isRelease||this.scrollBy(-Math.max(1,this.
795
- getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageDown"))return isRelease||this.
796
- scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.nextPrompt"))return isRelease||this.scrollToPrompt(
797
- 1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){switch(button&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(type,button,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.
798
- max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||getLayoutNode(box.component)&&box.component.
799
- handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result){let focusTarget=this.resolveMouseFocusTarget(result.focusTarget??result.target.component),focusChanged=result.focus===!0&&this.getFocusedComponent()!==focusTarget;return result.focus&&this.setFocus(focusTarget),
800
- result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x2&&previous.
801
- y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y:y2},count}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(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"release":isMotion?this.decodeMouseButton(raw.button)===
802
- "none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(event,targetResult)),raw.release){if(!this.mousePressMoved&&
803
- this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),clickResult=this.dispatchMouseToTarget(clickEvent,target);clickResult&&(render=this.applyMouseDispatchResult(clickEvent,clickResult)||render)}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.
804
- hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=result.target,this.mousePressPoint={x:raw.x,y:raw.y},
805
- this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(raw)}parseWheelEvent(data){let sgr=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(data);if(sgr){let button=Number.parseInt(sgr[1],10);if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:Number.parseInt(sgr[2],10)-1,y:Number.parseInt(sgr[3],10)-1,button}}if(data.length===6&&data.startsWith("\x1B[M")){let button=data.
806
- charCodeAt(3)-32;if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:data.charCodeAt(4)-33,y:data.charCodeAt(5)-33,button}}}routeWheel(event,delta){let remaining=delta,seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll==="contain")break;let primary=this.getPrimaryScrollView();
807
- remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){let match=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);if(match)return{button:Number.parseInt(match[1],10),x:Number.parseInt(match[2],10)-1,y:Number.parseInt(match[3],10)-1,release:match[4]==="m"}}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||
808
- event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;return!rect||event.release||(event.button&32)!==0||(event.button&3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x2,y2)){let box=getScrollViewBox(
809
- this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){
810
- this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?
811
- getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=
812
- void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(target.scrollView);let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,target.geometry,event.y,grabOffset),this.scrollbarDrag=
813
- {scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x2,y2){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)return;let pointerRow=Math.max(visibleTop,Math.
814
- min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.max(0,Math.min(this.terminal.columns-1,event.
815
- x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.scrollContentLines;if(lines)return lines[point.row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of wordSegmenter4.segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.has(segment.segment);
816
- segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.col>=segment.start&&point.col<segment.end);if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)
817
- selectionStart=segments[index-1].start;for(let index=clickedSegmentIndex;index<segments.length-1&&canJoin(segments[index],segments[index+1]);index++)selectionEnd=segments[index+1].end;return{start:{...point,col:selectionStart},end:{...point,col:selectionEnd,boundary:!0}}}getLineSelection(point){return{start:{...point,col:0},end:{...point,col:visibleWidth(this.getSelectionSourceLine(point)),boundary:!0}}}updateSelectionFocus(point){if(this.selectionGranularity==="character"||!this.selectionInitialRange){
818
- this.selectionFocus=point;return}let range=this.selectionGranularity==="word"?this.getWordSelection(point):this.getLineSelection(point);if(!range)return;let initial=this.selectionInitialRange;range.start.row<initial.start.row||range.start.row===initial.start.row&&range.start.col<initial.start.col?(this.selectionAnchor=initial.end,this.selectionFocus=range.start):(this.selectionAnchor=initial.start,this.selectionFocus=range.end)}getClickCount(point,word){let now=Date.now(),previous=this.lastClick,
819
- count=word&&previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.row===point.row&&previous.scrollView===point.scrollView&&previous.wordStart===word.start.col&&previous.wordEnd===word.end.col?previous.count%3+1:1;return this.lastClick=word?{timestamp:now,count,row:point.row,scrollView:point.scrollView,wordStart:word.start.col,wordEnd:word.end.col}:void 0,count}updateSelectionAutoScroll(event){let scrollView=this.selectionAnchor?.scrollView;if(!scrollView||!this.currentLayout){this.
820
- stopSelectionAutoScroll();return}let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0){this.stopSelectionAutoScroll();return}let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(this.selectionDragPointer={x:event.x,y:event.y},this.selectionAutoScrollDirection=event.y<=visibleTop?-1:event.y>=visibleBottom?1:0,this.selectionAutoScrollDirection===0){
821
- this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref())}autoScrollSelection(){let scrollView=this.selectionAnchor?.scrollView,pointer=this.selectionDragPointer,direction=this.selectionAutoScrollDirection;if(!scrollView||!pointer||direction===0){this.stopSelectionAutoScroll();return}if(scrollView.scrollBy(direction)===direction){this.stopSelectionAutoScroll();return}let point=this.
822
- getScrollSelectionPoint(scrollView,pointer.x,pointer.y);point&&this.updateSelectionFocus(point),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(event){let button=event.button&3;if(button!==0&&!(event.release&&button===3))return;let anchorScrollView=this.selectionAnchor?.scrollView,point=this.
823
- getSelectionPoint(event,anchorScrollView);if(event.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(point);let isClick=!this.selectionDragged&&this.selectionAnchor.scrollView===point.scrollView&&this.selectionAnchor.row===point.row&&this.selectionAnchor.col===point.col,clickedUrl=isClick?this.pressedUrl:void 0;if(this.pressedUrl=void 0,clickedUrl&&this.openUrl){this.selectionAnchor=void 0,
824
- this.selectionFocus=void 0;try{this.openUrl(clickedUrl)}catch{}this.requestRender();return}if(isClick){let clickEvent=this.createMouseEvent("click",event.button,event.x,event.y,{clickCount:this.lastClick?.count??1}),overlay=this.dispatchMouseToOverlay(clickEvent),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(clickEvent));if(result){let render=this.applyMouseDispatchResult(clickEvent,result);this.clearTextSelection(),render&&this.requestRender();return}}this.copyOnSelect&&
825
- this.copySelectionToClipboard(),this.requestRender();return}if((event.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(point),this.updateSelectionAutoScroll(event),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let scrollView=!this.hasOverlay()&&this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y)[0]:void 0,anchor=this.
826
- getSelectionPoint(event,scrollView),word=this.getWordSelection(anchor),clickCount=this.getClickCount(anchor,word),range=clickCount===2?word:clickCount===3?this.getLineSelection(anchor):void 0;this.selectionGranularity=range?clickCount===2?"word":"line":"character",this.selectionInitialRange=range,this.selectionAnchor=range?.start??anchor,this.selectionFocus=range?.end??anchor,this.selectionDragged=!1,this.pressedUrl=range?void 0:getOsc8LinkAtColumn(this.previousScreen[Math.max(0,Math.min(this.terminal.
827
- rows-1,event.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,event.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let anchorBeforeFocus=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.
828
- selectionFocus.col))return anchorBeforeFocus?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(line,row,selection,minColumn=0,maxColumn=visibleWidth(line)){let lineWidth=visibleWidth(line),start=Math.max(0,minColumn),end=Math.min(lineWidth,maxColumn);return row===selection.start.row&&(start=getGraphemeCellRange(line,selection.start.col)?.start??Math.min(selection.start.col,lineWidth)),row===selection.end.row&&(end=selection.
829
- end.boundary?Math.min(selection.end.col,lineWidth):getGraphemeCellRange(line,selection.end.col)?.end??Math.min(selection.end.col+1,lineWidth)),{start:Math.max(minColumn,start),end:Math.min(maxColumn,end)}}getActiveSelectionText(){let selection=this.getSelectionBounds();if(!selection)return;let sourceLines=this.previousScreen;if(selection.start.scrollView){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,selection.start.scrollView);if(!box?.scrollContentLines)return;sourceLines=
830
- box.scrollContentLines}let lines=[];for(let row=selection.start.row;row<=selection.end.row;row++){let line=sourceLines[row]??"",columns=this.getSelectionColumns(line,row,selection);lines.push(stripTerminalSequences(sliceByColumn(line,columns.start,Math.max(0,columns.end-columns.start),!0)).trimEnd())}let text=lines.join(`
850
+ \x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}getExitRestorePrefix(){let prefix=super.getExitRestorePrefix();return this.altScreenActive?`${END_SYNCHRONIZED_OUTPUT}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${prefix}`:prefix}getExitRestoreSuffix(){return`${super.getExitRestoreSuffix()}${this.altScreenActive?`${EXIT_ALT_SCREEN}\x1B[?25h`:""}`}deleteKittyImages(){return this.
851
+ imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={transmissionGeneration:placement.transmissionGeneration,transmissionBytes:placement.transmissionBytes,estimatedDecodedBytes:placement.estimatedDecodedBytes};return cachedImage&&this.
852
+ uploadedKittyImages.delete(placement.imageId),this.uploadedKittyImages.set(placement.imageId,nextCachedImage),cachedImage?.transmissionGeneration===placement.transmissionGeneration?placement.replacementLine:line}),cachedOffscreenImageCount=0,cachedOffscreenTransmissionBytes=0,cachedOffscreenDecodedBytes=0;for(let[imageId,cachedImage]of this.uploadedKittyImages)visibleImageIds.has(imageId)||(cachedOffscreenImageCount+=1,cachedOffscreenTransmissionBytes+=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes+=
853
+ cachedImage.estimatedDecodedBytes);let evictedImageDeletion="";for(let[imageId,cachedImage]of this.uploadedKittyImages){if(cachedOffscreenImageCount<=MAX_CACHED_OFFSCREEN_KITTY_IMAGES&&cachedOffscreenTransmissionBytes<=MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES&&cachedOffscreenDecodedBytes<=MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES)break;visibleImageIds.has(imageId)||(evictedImageDeletion+=deleteKittyImage(imageId),this.uploadedKittyImages.delete(imageId),cachedOffscreenImageCount-=1,cachedOffscreenTransmissionBytes-=
854
+ cachedImage.transmissionBytes,cachedOffscreenDecodedBytes-=cachedImage.estimatedDecodedBytes)}return{lines,evictedImageDeletion}}resetRenderState(){this.previousScreen=[],this.finishedRows=new Map,this.imageRows=new Set,this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(lines){this.getPrimaryScrollView().scrollBy(lines),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().
855
+ scrollToEnd(),this.requestRender()}scrollToPrompt(direction){if(!this.currentLayout)return;let scrollView=this.getPrimaryScrollView(),lines=getScrollViewBox(this.currentLayout,scrollView)?.scrollContentLines;if(lines){for(let row=scrollView.scrollTop+direction;row>=0&&row<lines.length;row+=direction)if(OSC133_PROMPT_START.test(lines[row]??"")){scrollView.scrollTo(row),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let component=new AltScreenSearchComponent(
856
+ query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={component,index:new AltScreenSearchIndex,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=search,search.overlay=this.showOverlay(component,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){let search=this.activeSearch;search&&(this.activeSearch=void 0,search.overlay?.hide(),this.requestRender())}updateSearchQuery(query){let search=this.
857
+ activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){let search=this.activeSearch;search?.query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x2,y2){let search=this.activeSearch,bounds=search?.
858
+ overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y2<bounds.row||y2>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y2-bounds.row,x2-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.getSearchNavigationDirectionAt(event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==
859
+ 0||(event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.matches=[],search.selectedIndex=-1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",
860
+ result=search.index.search(lines,search.query),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.row??
861
+ 0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=
862
+ exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||
863
+ scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.
864
+ isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),
865
+ this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let lines=this.wheelScroll.next(wheelEvent.
866
+ direction,performance.now()),wheelDelta=wheelEvent.direction*((wheelEvent.button&8)!==0?lines*ALT_WHEEL_SCROLL_MULTIPLIER:lines),event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):(this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.
867
+ parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScr\
868
+ een.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(keybindings.matches(data,"tui.altScreen.pageUp"))return isRelease||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(Math.max(1,
869
+ this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageDown"))return isRelease||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(
870
+ -1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.nextPrompt"))return isRelease||this.scrollToPrompt(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||
871
+ this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){switch(button&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(type,button,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.
872
+ wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||getLayoutNode(box.component)&&box.component.handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-
873
+ box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result){let focusTarget=this.resolveMouseFocusTarget(result.focusTarget??result.target.component),focusChanged=result.focus===!0&&this.getFocusedComponent()!==focusTarget;return result.focus&&this.setFocus(focusTarget),result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){
874
+ return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x2&&previous.y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y:y2},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,
875
+ this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"release":isMotion?this.decodeMouseButton(raw.button)==="none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&
876
+ (raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(event,targetResult)),raw.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),
877
+ clickResult=this.dispatchMouseToTarget(clickEvent,target);clickResult&&(render=this.applyMouseDispatchResult(clickEvent,clickResult)||render)}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(
878
+ raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=result.target,this.mousePressPoint={x:raw.x,y:raw.y},this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(raw)}parseWheelEvent(data){let sgr=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(
879
+ data);if(sgr){let button=Number.parseInt(sgr[1],10);if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:Number.parseInt(sgr[2],10)-1,y:Number.parseInt(sgr[3],10)-1,button}}if(data.length===6&&data.startsWith("\x1B[M")){let button=data.charCodeAt(3)-32;if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:data.charCodeAt(4)-33,y:data.charCodeAt(5)-33,button}}}routeWheel(event,delta){
880
+ let remaining=delta,seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll==="contain")break;let primary=this.getPrimaryScrollView();remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){let match=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);if(match)
881
+ return{button:Number.parseInt(match[1],10),x:Number.parseInt(match[2],10)-1,y:Number.parseInt(match[3],10)-1,release:match[4]==="m"}}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;return!rect||event.release||(event.button&32)!==0||(event.button&
882
+ 3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x2,y2)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,
883
+ geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.
884
+ min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&this.scrollScrollbarToPointer(this.scrollbarDrag.
885
+ scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)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(target.scrollView);
886
+ let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,target.geometry,event.y,grabOffset),this.scrollbarDrag={scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x2,y2){if(!this.currentLayout)return;let box=getScrollViewBox(
887
+ this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)return;let pointerRow=Math.max(visibleTop,Math.min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(
888
+ 0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.max(0,Math.min(this.terminal.columns-1,event.x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.scrollContentLines;if(lines)return lines[point.
889
+ row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of wordSegmenter4.segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.has(segment.segment);segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.col>=segment.start&&point.col<segment.end);
890
+ if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)selectionStart=segments[index-1].start;for(let index=clickedSegmentIndex;index<segments.length-1&&canJoin(segments[index],segments[index+1]);index++)selectionEnd=segments[index+1].end;return{
891
+ start:{...point,col:selectionStart},end:{...point,col:selectionEnd,boundary:!0}}}getLineSelection(point){return{start:{...point,col:0},end:{...point,col:visibleWidth(this.getSelectionSourceLine(point)),boundary:!0}}}updateSelectionFocus(point){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=point;return}let range=this.selectionGranularity==="word"?this.getWordSelection(point):this.getLineSelection(point);if(!range)return;let initial=this.selectionInitialRange;
892
+ range.start.row<initial.start.row||range.start.row===initial.start.row&&range.start.col<initial.start.col?(this.selectionAnchor=initial.end,this.selectionFocus=range.start):(this.selectionAnchor=initial.start,this.selectionFocus=range.end)}getClickCount(point,word){let now=Date.now(),previous=this.lastClick,count=word&&previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.row===point.row&&previous.scrollView===point.scrollView&&previous.wordStart===word.start.col&&previous.wordEnd===
893
+ word.end.col?previous.count%3+1:1;return this.lastClick=word?{timestamp:now,count,row:point.row,scrollView:point.scrollView,wordStart:word.start.col,wordEnd:word.end.col}:void 0,count}updateSelectionAutoScroll(event){let scrollView=this.selectionAnchor?.scrollView;if(!scrollView||!this.currentLayout){this.stopSelectionAutoScroll();return}let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0){this.stopSelectionAutoScroll();return}let visibleTop=Math.
894
+ max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(this.selectionDragPointer={x:event.x,y:event.y},this.selectionAutoScrollDirection=event.y<=visibleTop?-1:event.y>=visibleBottom?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref())}autoScrollSelection(){
895
+ let scrollView=this.selectionAnchor?.scrollView,pointer=this.selectionDragPointer,direction=this.selectionAutoScrollDirection;if(!scrollView||!pointer||direction===0){this.stopSelectionAutoScroll();return}if(scrollView.scrollBy(direction)===direction){this.stopSelectionAutoScroll();return}let point=this.getScrollSelectionPoint(scrollView,pointer.x,pointer.y);point&&this.updateSelectionFocus(point),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),
896
+ this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(event){let button=event.button&3;if(button!==0&&!(event.release&&button===3))return;let anchorScrollView=this.selectionAnchor?.scrollView,point=this.getSelectionPoint(event,anchorScrollView);if(event.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(point);let isClick=!this.
897
+ selectionDragged&&this.selectionAnchor.scrollView===point.scrollView&&this.selectionAnchor.row===point.row&&this.selectionAnchor.col===point.col,clickedUrl=isClick?this.pressedUrl:void 0;if(this.pressedUrl=void 0,clickedUrl&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(clickedUrl)}catch{}this.requestRender();return}if(isClick){let clickEvent=this.createMouseEvent("click",event.button,event.x,event.y,{clickCount:this.lastClick?.count??1}),overlay=this.dispatchMouseToOverlay(
898
+ clickEvent),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(clickEvent));if(result){let render=this.applyMouseDispatchResult(clickEvent,result);this.clearTextSelection(),render&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((event.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(point),this.
899
+ updateSelectionAutoScroll(event),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let scrollView=!this.hasOverlay()&&this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y)[0]:void 0,anchor=this.getSelectionPoint(event,scrollView),word=this.getWordSelection(anchor),clickCount=this.getClickCount(anchor,word),range=clickCount===2?word:clickCount===3?this.getLineSelection(anchor):void 0;this.selectionGranularity=range?clickCount===2?"word":"lin\
900
+ e":"character",this.selectionInitialRange=range,this.selectionAnchor=range?.start??anchor,this.selectionFocus=range?.end??anchor,this.selectionDragged=!1,this.pressedUrl=range?void 0:getOsc8LinkAtColumn(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,event.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,event.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let anchorBeforeFocus=this.
901
+ 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 anchorBeforeFocus?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(line,row,selection,minColumn=0,maxColumn=visibleWidth(line)){let lineWidth=visibleWidth(line),
902
+ start=Math.max(0,minColumn),end=Math.min(lineWidth,maxColumn);return row===selection.start.row&&(start=getGraphemeCellRange(line,selection.start.col)?.start??Math.min(selection.start.col,lineWidth)),row===selection.end.row&&(end=selection.end.boundary?Math.min(selection.end.col,lineWidth):getGraphemeCellRange(line,selection.end.col)?.end??Math.min(selection.end.col+1,lineWidth)),{start:Math.max(minColumn,start),end:Math.min(maxColumn,end)}}getActiveSelectionText(){let selection=this.getSelectionBounds();
903
+ if(!selection)return;let sourceLines=this.previousScreen;if(selection.start.scrollView){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,selection.start.scrollView);if(!box?.scrollContentLines)return;sourceLines=box.scrollContentLines}let lines=[];for(let row=selection.start.row;row<=selection.end.row;row++){let line=sourceLines[row]??"",columns=this.getSelectionColumns(line,row,selection);lines.push(stripTerminalSequences(sliceByColumn(line,columns.start,Math.max(0,columns.
904
+ end-columns.start),!0)).trimEnd())}let text=lines.join(`
831
905
  `);return text.length===0?void 0:text}async copySelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}async copyTextToClipboard(text){if(this.copySelection){let result=await this.copySelection(text),ok=result===!0;return this.flash(ok?"Copied!":typeof result=="string"?result:"Copy failed",ok?void 0:COPY_ERROR_FLASH_DURATION_MS),ok}return this.terminal.write(`\x1B]52;c;${Buffer.from(text).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(text,current){
832
906
  let style=current?this.searchCurrentMatchStyle:this.searchMatchStyle,result="",plainStart=0,index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){index+=1;continue}index>plainStart&&(result+=style(text.slice(plainStart,index))),result+=ansi.code,index+=ansi.length,plainStart=index}return plainStart<text.length&&(result+=style(text.slice(plainStart))),result}applySearchHighlights(screen,layout){let search=this.activeSearch;if(!search||search.selectedIndex<0||search.matches.
833
907
  length===0)return screen;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView);if(!box)return screen;let rangesByRow=new Map,scrollbarColumn=getScrollbarGeometry(box)?.column,minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length,box.rect.y+box.rect.height,box.clip.y+box.clip.height),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width,scrollbarColumn??
@@ -856,27 +930,31 @@ cursorPos.col)+1}H`,buffer+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"
856
930
  end--,end===offset){this.flush();continue}this.buffer+=value.slice(offset,end),offset=end,this.buffer.length===MAX_RENDER_WRITE_CHARS&&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 parseKittyImageHeader(line){let sequenceStart=line.indexOf(KITTY_SEQUENCE_PREFIX);if(sequenceStart===-1)return;let paramsStart=sequenceStart+KITTY_SEQUENCE_PREFIX.length,paramsEnd=line.
857
931
  indexOf(";",paramsStart);if(paramsEnd===-1)return;let ids=[],rows=1;for(let param of line.slice(paramsStart,paramsEnd).split(",")){let[key,value]=param.split("=",2);if(value===void 0)continue;let numberValue=Number(value);!Number.isInteger(numberValue)||numberValue<=0||numberValue>4294967295||(key==="i"?ids.push(numberValue):key==="r"&&(rows=numberValue))}return{ids,rows}}function extractKittyImageIds(line){return parseKittyImageHeader(line)?.ids??[]}function extractKittyImageRows(line){return parseKittyImageHeader(
858
932
  line)?.rows??1}function isTermuxSession(){return!!process.env.TERMUX_VERSION}var TuiMainScreen=class extends TuiBase{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.
859
- maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.previousLines=state.previousLines.map(line=>isImageLine(line)?"":line),this.previousKittyImageIds=new Set,this.previousWidth=state.previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.cursorRow,this.hardwareCursorRow=state.hardwareCursorRow,this.maxLinesRendered=state.maxLinesRendered,this.previousViewportTop=state.previousViewportTop}resetRenderState(){this.previousLines=[],this.
860
- previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}beforeTerminalStop(options){if(options.preserveScreen||this.previousLines.length===0)return;this.terminal.write(" ");let lineDiff=this.previousLines.length-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
861
- `)}rawLines=[];finishedLines=[];finishLines(raw){let previousRaw=this.rawLines,previousFinished=this.finishedLines,lines=new Array(raw.length),single=[""],imageLines=0;for(let i=0;i<raw.length;i++){let line=raw[i],finished;i<previousRaw.length&&line===previousRaw[i]?finished=previousFinished[i]:(single[0]=line,finished=this.applyLineResets(single)[0]),finished===line&&imageLines++,lines[i]=finished}return this.rawLines=raw,this.finishedLines=lines,{lines,imageLines}}collectKittyImageIds(lines){let ids=new Set;
862
- for(let line of lines)for(let id of extractKittyImageIds(line))ids.add(id);return ids}deleteKittyImages(ids){let buffer="";for(let id of ids)buffer+=deleteKittyImage(id);return buffer}getKittyImageReservedRows(lines,index,maxIndex=lines.length-1){let rows=extractKittyImageRows(lines[index]??"");if(rows<=1)return 1;let maxRows=Math.min(rows,maxIndex-index+1,lines.length-index),reservedRows=1;for(;reservedRows<maxRows;){let line=lines[index+reservedRows]??"";if(isImageLine(line)||visibleWidth(line)>
863
- 0)break;reservedRows++}return reservedRows}expandChangedRangeForKittyImages(firstChanged,lastChanged,newLines){let expandedFirstChanged=firstChanged,expandedLastChanged=lastChanged,expandForLines=lines=>{for(let i=0;i<lines.length;i++){if(extractKittyImageIds(lines[i]).length===0)continue;let blockEnd=i+this.getKittyImageReservedRows(lines,i)-1;(i>=firstChanged||i<=lastChanged&&blockEnd>=firstChanged)&&(expandedFirstChanged=Math.min(expandedFirstChanged,i),expandedLastChanged=Math.max(expandedLastChanged,
933
+ maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.frameLive=void 0,this.previousLines=state.previousLines.map(line=>isImageLine(line)?"":line),this.previousKittyImageIds=new Set,this.previousWidth=state.previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.cursorRow,this.hardwareCursorRow=state.hardwareCursorRow,this.maxLinesRendered=state.maxLinesRendered,this.previousViewportTop=state.previousViewportTop}resetRenderState(){this.
934
+ frameLive=void 0,this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}beforeTerminalStop(options){if(options.preserveScreen||this.previousLines.length===0)return;this.terminal.write(" ");let lineDiff=this.previousLines.length-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
935
+ `)}unresolvedLines=[];resolvedLines=[];resolvedWithHardwareCursor=!1;resolveFrameFakeCursors(lines,unchanged){let showHardwareCursor=this.getShowHardwareCursor(),previous=showHardwareCursor===this.resolvedWithHardwareCursor?this.unresolvedLines:[],previousResolved=this.resolvedLines,from=previous.length===0?0:Math.min(unchanged,previous.length,lines.length),resolved=from>0?previousResolved.slice(0,from):[];resolved.length=lines.length;let single=[""];for(let i=from;i<lines.length;i++){let line=lines[i];
936
+ i<previous.length&&line===previous[i]?resolved[i]=previousResolved[i]:(single[0]=line,resolved[i]=this.resolveFakeCursors(single)[0])}return this.unresolvedLines=lines,this.resolvedLines=resolved,this.resolvedWithHardwareCursor=showHardwareCursor,resolved.slice()}rawLines=[];finishedLines=[];finishedImageRows=[];frameLive;finishLines(raw,unchanged){let previousRaw=this.rawLines,previousFinished=this.finishedLines,from=Math.min(unchanged,previousRaw.length,raw.length),lines=from>0?previousFinished.
937
+ slice(0,from):[];lines.length=raw.length;let imageRows=this.finishedImageRows.filter(row=>row<from),single=[""];for(let i=from;i<raw.length;i++){let line=raw[i],finished;i<previousRaw.length&&line===previousRaw[i]?finished=previousFinished[i]:(single[0]=line,finished=this.applyLineResets(single)[0]),finished===line&&imageRows.push(i),lines[i]=finished}return this.rawLines=raw,this.finishedLines=lines,this.finishedImageRows=imageRows,{lines,imageLines:imageRows.length}}collectKittyImageIds(lines){
938
+ let ids=new Set;for(let line of lines)for(let id of extractKittyImageIds(line))ids.add(id);return ids}deleteKittyImages(ids){let buffer="";for(let id of ids)buffer+=deleteKittyImage(id);return buffer}getKittyImageReservedRows(lines,index,maxIndex=lines.length-1){let rows=extractKittyImageRows(lines[index]??"");if(rows<=1)return 1;let maxRows=Math.min(rows,maxIndex-index+1,lines.length-index),reservedRows=1;for(;reservedRows<maxRows;){let line=lines[index+reservedRows]??"";if(isImageLine(line)||visibleWidth(
939
+ line)>0)break;reservedRows++}return reservedRows}expandChangedRangeForKittyImages(firstChanged,lastChanged,newLines){let expandedFirstChanged=firstChanged,expandedLastChanged=lastChanged,expandForLines=lines=>{for(let i=0;i<lines.length;i++){if(extractKittyImageIds(lines[i]).length===0)continue;let blockEnd=i+this.getKittyImageReservedRows(lines,i)-1;(i>=firstChanged||i<=lastChanged&&blockEnd>=firstChanged)&&(expandedFirstChanged=Math.min(expandedFirstChanged,i),expandedLastChanged=Math.max(expandedLastChanged,
864
940
  blockEnd))}};return expandForLines(this.previousLines),expandForLines(newLines),{firstChanged:expandedFirstChanged,lastChanged:expandedLastChanged}}deleteChangedKittyImages(firstChanged,lastChanged){if(firstChanged<0||lastChanged<firstChanged||this.previousKittyImageIds.size===0)return"";let ids=new Set,maxLine=Math.min(lastChanged,this.previousLines.length-1);for(let i=firstChanged;i<=maxLine;i++)for(let id of extractKittyImageIds(this.previousLines[i]??""))ids.add(id);return this.deleteKittyImages(
865
941
  ids)}doRender(){if(this.stopped)return;let width=this.terminal.columns,height=this.terminal.rows,widthChanged=this.previousWidth!==0&&this.previousWidth!==width,heightChanged=this.previousHeight!==0&&this.previousHeight!==height,previousBufferLength=this.previousHeight>0?this.previousViewportTop+this.previousHeight:height,prevViewportTop=heightChanged?Math.max(0,previousBufferLength-height):this.previousViewportTop,viewportTop=prevViewportTop,hardwareCursorRow=this.hardwareCursorRow,computeLineDiff=targetRow=>{
866
- let currentScreenRow=hardwareCursorRow-prevViewportTop;return targetRow-viewportTop-currentScreenRow},newLines=this.resolveFakeCursors(this.render(width));this.hasOverlayEntries&&(newLines=this.compositeOverlays(newLines,width,height));let cursorPos=this.extractCursorPosition(newLines,height),finished=this.finishLines(newLines);newLines=finished.lines;let imagesShown=finished.imageLines>0||this.previousKittyImageIds.size>0,collectKittyImageIds=lines=>imagesShown?this.collectKittyImageIds(lines):
867
- new Set,fullRender=clear=>{this.fullRedrawCount+=1;let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));output2.append("\x1B[?2026h"),clear&&(output2.append(this.deleteKittyImages(this.previousKittyImageIds)),output2.append("\x1B[2J\x1B[H\x1B[3J"));for(let i=0;i<newLines.length;i++){i>0&&output2.append(`\r
942
+ let currentScreenRow=hardwareCursorRow-prevViewportTop;return targetRow-viewportTop-currentScreenRow},live=renderLiveLines(this,width),before=this.frameLive,root=live===void 0?renderSharedLines(this,width):before?.live===live&&before.width===width&&before.revision===live.revision?before.lines:live.lines.slice(),unchanged=0;live!==void 0&&before?.live===live&&before.width===width&&this.previousWidth===width&&this.previousHeight===height&&this.getShowHardwareCursor()===this.resolvedWithHardwareCursor&&
943
+ !this.hasOverlayEntries&&(unchanged=Math.min(live.changedSince(before.revision),before.lines.length,root.length-height,this.previousLines.length-height)),unchanged=Math.max(0,unchanged),this.frameLive=live===void 0?void 0:{live,revision:live.revision,width,lines:root};let newLines=this.resolveFrameFakeCursors(root,unchanged);this.hasOverlayEntries&&(newLines=this.compositeOverlays(newLines,width,height));let cursorPos=this.extractCursorPosition(newLines,height),finished=this.finishLines(newLines,
944
+ unchanged);newLines=finished.lines;let imagesShown=finished.imageLines>0||this.previousKittyImageIds.size>0,collectKittyImageIds=lines=>imagesShown?this.collectKittyImageIds(lines):new Set,fullRender=clear=>{this.fullRedrawCount+=1;let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));output2.append("\x1B[?2026h"),clear&&(output2.append(this.deleteKittyImages(this.previousKittyImageIds)),output2.append("\x1B[2J\x1B[H\x1B[3J"));for(let i=0;i<newLines.length;i++){i>0&&output2.append(
945
+ `\r
868
946
  `);let line=newLines[i],imageReservedRows=isImageLine(line)?this.getKittyImageReservedRows(newLines,i):1;if(imageReservedRows>1&&imageReservedRows<=height){for(let row=1;row<imageReservedRows;row++)output2.append(`\r
869
947
  `);output2.append(`\x1B[${imageReservedRows-1}A`),output2.append(line),output2.append(`\x1B[${imageReservedRows-1}B`),i+=imageReservedRows-1;continue}output2.append(line)}output2.append("\x1B[?2026l"),output2.flush(),this.cursorRow=Math.max(0,newLines.length-1),this.hardwareCursorRow=this.cursorRow,clear?this.maxLinesRendered=newLines.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length);let bufferLength=Math.max(height,newLines.length);this.previousViewportTop=Math.max(0,
870
948
  bufferLength-height),this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height},redrawLogDirectory=process.env.PI_TUI_DEBUG_REDRAW==="1"?this.logDirectory:void 0,logRedraw=reason=>{if(redrawLogDirectory===void 0)return;let logPath=path3.join(redrawLogDirectory,"pi-tui-debug.log"),msg=`[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.
871
949
  length}, new=${newLines.length}, height=${height})
872
950
  `;fs2.mkdirSync(path3.dirname(logPath),{recursive:!0}),fs2.appendFileSync(logPath,msg)};if(this.previousLines.length===0&&!widthChanged&&!heightChanged){logRedraw("first render"),fullRender(!1);return}if(widthChanged){logRedraw(`terminal width changed (${this.previousWidth} -> ${width})`),fullRender(!0);return}if(heightChanged&&!isTermuxSession()){logRedraw(`terminal height changed (${this.previousHeight} -> ${height})`),fullRender(!0);return}if(this.getClearOnShrink()&&newLines.length<this.maxLinesRendered&&
873
- !this.hasOverlayEntries){logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),fullRender(!0);return}let firstChanged=-1,lastChanged=-1,maxLines=Math.max(newLines.length,this.previousLines.length);for(let i=0;i<maxLines;i++){let oldLine=i<this.previousLines.length?this.previousLines[i]:"",newLine=i<newLines.length?newLines[i]:"";oldLine!==newLine&&(firstChanged===-1&&(firstChanged=i),lastChanged=i)}let appendedLines=newLines.length>this.previousLines.length;if(appendedLines&&(firstChanged===
874
- -1&&(firstChanged=this.previousLines.length),lastChanged=newLines.length-1),firstChanged!==-1&&imagesShown){let expandedRange=this.expandChangedRangeForKittyImages(firstChanged,lastChanged,newLines);firstChanged=expandedRange.firstChanged,lastChanged=expandedRange.lastChanged}let appendStart=appendedLines&&firstChanged===this.previousLines.length&&firstChanged>0;if(firstChanged===-1){this.positionHardwareCursor(cursorPos,newLines.length),this.previousViewportTop=prevViewportTop,this.previousHeight=
875
- height;return}if(firstChanged>=newLines.length){if(this.previousLines.length>newLines.length){let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));output2.append("\x1B[?2026h"),output2.append(this.deleteChangedKittyImages(firstChanged,lastChanged));let targetRow=Math.max(0,newLines.length-1);if(targetRow<prevViewportTop){logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`),fullRender(!0);return}let lineDiff2=computeLineDiff(targetRow);lineDiff2>0?output2.
876
- append(`\x1B[${lineDiff2}B`):lineDiff2<0&&output2.append(`\x1B[${-lineDiff2}A`),output2.append("\r");let extraLines=this.previousLines.length-newLines.length;if(extraLines>height){logRedraw(`extraLines > height (${extraLines} > ${height})`),fullRender(!0);return}let clearStartOffset=newLines.length===0?0:1;extraLines>0&&clearStartOffset>0&&output2.append(`\x1B[${clearStartOffset}B`);for(let i=0;i<extraLines;i++)output2.append("\r\x1B[2K"),i<extraLines-1&&output2.append("\x1B[1B");let moveBack=Math.
877
- max(0,extraLines-1+clearStartOffset);moveBack>0&&output2.append(`\x1B[${moveBack}A`),output2.append("\x1B[?2026l"),output2.flush(),this.cursorRow=targetRow,this.hardwareCursorRow=targetRow}this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height,this.previousViewportTop=prevViewportTop;return}if(firstChanged<prevViewportTop){logRedraw(`firstChanged < viewportTop\
878
- (${firstChanged} < ${prevViewportTop})`),fullRender(!0);return}let output=new BoundedTerminalWriter(data=>this.terminal.write(data));output.append("\x1B[?2026h"),output.append(this.deleteChangedKittyImages(firstChanged,lastChanged));let prevViewportBottom=prevViewportTop+height-1,moveTargetRow=appendStart?firstChanged-1:firstChanged;if(moveTargetRow>prevViewportBottom){let currentScreenRow=Math.max(0,Math.min(height-1,hardwareCursorRow-prevViewportTop)),moveToBottom=height-1-currentScreenRow;moveToBottom>
879
- 0&&output.append(`\x1B[${moveToBottom}B`);let scroll=moveTargetRow-prevViewportBottom;output.append(`\r
951
+ !this.hasOverlayEntries){logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),fullRender(!0);return}let firstChanged=-1,lastChanged=-1,maxLines=Math.max(newLines.length,this.previousLines.length);for(let i=Math.min(unchanged,this.previousLines.length);i<maxLines;i++){let oldLine=i<this.previousLines.length?this.previousLines[i]:"",newLine=i<newLines.length?newLines[i]:"";oldLine!==newLine&&(firstChanged===-1&&(firstChanged=i),lastChanged=i)}let appendedLines=newLines.length>this.
952
+ previousLines.length;if(appendedLines&&(firstChanged===-1&&(firstChanged=this.previousLines.length),lastChanged=newLines.length-1),firstChanged!==-1&&imagesShown){let expandedRange=this.expandChangedRangeForKittyImages(firstChanged,lastChanged,newLines);firstChanged=expandedRange.firstChanged,lastChanged=expandedRange.lastChanged}let appendStart=appendedLines&&firstChanged===this.previousLines.length&&firstChanged>0;if(firstChanged===-1){this.positionHardwareCursor(cursorPos,newLines.length),this.
953
+ previousViewportTop=prevViewportTop,this.previousHeight=height;return}if(firstChanged>=newLines.length){if(this.previousLines.length>newLines.length){let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));output2.append("\x1B[?2026h"),output2.append(this.deleteChangedKittyImages(firstChanged,lastChanged));let targetRow=Math.max(0,newLines.length-1);if(targetRow<prevViewportTop){logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`),fullRender(!0);return}
954
+ let lineDiff2=computeLineDiff(targetRow);lineDiff2>0?output2.append(`\x1B[${lineDiff2}B`):lineDiff2<0&&output2.append(`\x1B[${-lineDiff2}A`),output2.append("\r");let extraLines=this.previousLines.length-newLines.length;if(extraLines>height){logRedraw(`extraLines > height (${extraLines} > ${height})`),fullRender(!0);return}let clearStartOffset=newLines.length===0?0:1;extraLines>0&&clearStartOffset>0&&output2.append(`\x1B[${clearStartOffset}B`);for(let i=0;i<extraLines;i++)output2.append("\r\x1B[2K"),
955
+ i<extraLines-1&&output2.append("\x1B[1B");let moveBack=Math.max(0,extraLines-1+clearStartOffset);moveBack>0&&output2.append(`\x1B[${moveBack}A`),output2.append("\x1B[?2026l"),output2.flush(),this.cursorRow=targetRow,this.hardwareCursorRow=targetRow}this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height,this.previousViewportTop=prevViewportTop;return}if(firstChanged<
956
+ prevViewportTop){logRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`),fullRender(!0);return}let output=new BoundedTerminalWriter(data=>this.terminal.write(data));output.append("\x1B[?2026h"),output.append(this.deleteChangedKittyImages(firstChanged,lastChanged));let prevViewportBottom=prevViewportTop+height-1,moveTargetRow=appendStart?firstChanged-1:firstChanged;if(moveTargetRow>prevViewportBottom){let currentScreenRow=Math.max(0,Math.min(height-1,hardwareCursorRow-prevViewportTop)),
957
+ moveToBottom=height-1-currentScreenRow;moveToBottom>0&&output.append(`\x1B[${moveToBottom}B`);let scroll=moveTargetRow-prevViewportBottom;output.append(`\r
880
958
  `.repeat(scroll)),prevViewportTop+=scroll,viewportTop+=scroll,hardwareCursorRow=moveTargetRow}let lineDiff=computeLineDiff(moveTargetRow);lineDiff>0?output.append(`\x1B[${lineDiff}B`):lineDiff<0&&output.append(`\x1B[${-lineDiff}A`),output.append(appendStart?`\r
881
959
  `:"\r");let renderEnd=Math.min(lastChanged,newLines.length-1);for(let i=firstChanged;i<=renderEnd;i++){i>firstChanged&&output.append(`\r
882
960
  `);let line=newLines[i],isImage=isImageLine(line),imageReservedRows=isImage?this.getKittyImageReservedRows(newLines,i,renderEnd):1;if(imageReservedRows>1){let imageStartScreenRow=i-viewportTop;if(imageStartScreenRow<0||imageStartScreenRow+imageReservedRows>height){logRedraw(`kitty image pre-clear would scroll (${imageStartScreenRow} + ${imageReservedRows} > ${height})`),fullRender(!0);return}output.append("\x1B[2K");for(let row=1;row<imageReservedRows;row++)output.append(`\r
@@ -1167,6 +1245,6 @@ void 0;if(!validLang)return code.split(`
1167
1245
  `)}catch{return code.split(`
1168
1246
  `).map(line=>theme.fg("mdCodeBlock",line))}}}}function getSelectListTheme(){return{selectedPrefix:text=>theme.fg("accent",text),selectedText:text=>theme.fg("accent",text),description:text=>theme.fg("muted",text),scrollInfo:text=>theme.fg("muted",text),noMatch:text=>theme.fg("muted",text)}}function getEditorTheme(){return{borderColor:text=>theme.fg("borderMuted",text),selectList:getSelectListTheme()}}function getSettingsListTheme(){return{label:(text,selected)=>selected?theme.fg("accent",text):text,
1169
1247
  value:(text,selected)=>selected?theme.fg("accent",text):theme.fg("muted",text),description:text=>theme.fg("dim",text),cursor:theme.fg("accent","\u2192 "),hint:text=>theme.fg("dim",text)}}function formatKeyPart(part,options){let displayPart=process.platform==="darwin"&&part.toLowerCase()==="alt"?"option":part;return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k=>k.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(
1170
- getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}export{U,fuzzyMatch,fuzzyFilter,visibleWidth,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,indexedColor,rgbColor,parseColor,colorToRgb,mixColors,foregroundAnsi,backgroundAnsi,styleText,Key,matchesKey,onCapabilitiesChange,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,markStableRender,renderSharedLines,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,
1171
- Text,Loader,CancellableLoader,SelectList,Editor,setImageTranscoder,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguagesOnDemand,SYSTEM_THEME_NAME,THEME_TOKENS,DEFAULT_THEME_NAME,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,
1172
- loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,getThemeInstance,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,keyDisplayText,keyHint,rawKeyHint};
1248
+ getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}export{U,fuzzyMatch,fuzzyFilter,visibleWidth,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,indexedColor,rgbColor,parseColor,colorToRgb,mixColors,foregroundAnsi,backgroundAnsi,styleText,Key,matchesKey,onCapabilitiesChange,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,markStableRender,LiveLineArray,markLiveRender,markReportsChanges,reportsChanges,setSubtreeReportsChanges,renderChildLines,reportRenderChange,
1249
+ Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,Text,Loader,CancellableLoader,SelectList,Editor,setImageTranscoder,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguagesOnDemand,SYSTEM_THEME_NAME,THEME_TOKENS,DEFAULT_THEME_NAME,setThemeJsonValidator,setTerminalColors,
1250
+ setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,getThemeInstance,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,keyDisplayText,keyHint,rawKeyHint};