@code-yeongyu/senpi 2026.9.27-4 → 2026.9.28-2

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 (294) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/bundle/chunks/{app-server-command-3GVJZFFH.js → app-server-command-H6LFICZ2.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-4SUOOZZ4.js → azure-openai-responses-FCZNBRWE.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-PSCNHY7D.js → chunk-3GMFUEU7.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-HBG6SQU5.js → chunk-62XHQXCZ.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-EJKCBRYK.js → chunk-6BWCPOCV.js} +4 -4
  8. package/dist/bundle/chunks/{chunk-SLL375O7.js → chunk-6VD3EBQE.js} +1 -1
  9. package/dist/bundle/chunks/chunk-7YUGCTEV.js +15 -0
  10. package/dist/bundle/chunks/{chunk-FWBSGMAE.js → chunk-A4UMPXQF.js} +1 -1
  11. package/dist/bundle/chunks/chunk-BBK6SSYT.js +2 -0
  12. package/dist/bundle/chunks/{chunk-C2425O2Q.js → chunk-CNQ4JB45.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-27IFXX3B.js → chunk-DRN4FQCE.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-22MGY5JQ.js → chunk-EHSZ7UCW.js} +1 -1
  15. package/dist/bundle/chunks/chunk-FHJYIU3U.js +5 -0
  16. package/dist/bundle/chunks/chunk-GJUCSTAG.js +19 -0
  17. package/dist/bundle/chunks/chunk-KOPTADA3.js +8 -0
  18. package/dist/bundle/chunks/{chunk-VMKAYXHL.js → chunk-LSW7QSLV.js} +31 -26
  19. package/dist/bundle/chunks/{chunk-2BMD37YV.js → chunk-LUPPSEQW.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-NRGMT74E.js → chunk-QOVUQZO4.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-IKXPBYSO.js → chunk-SICBVLRH.js} +1 -1
  22. package/dist/bundle/chunks/chunk-SN4ZHPMN.js +135 -0
  23. package/dist/bundle/chunks/{chunk-MUTD2NOH.js → chunk-TFA3YAJK.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-4T4GFAGK.js → chunk-VFSXUT7K.js} +1 -1
  25. package/dist/bundle/chunks/{cli-main-66NFBKVH.js → cli-main-GYRTYPMG.js} +1 -1
  26. package/dist/bundle/chunks/{google-generative-ai-ZTGKZTGU.js → google-generative-ai-LFCBHG3Y.js} +1 -1
  27. package/dist/bundle/chunks/{google-vertex-CCZ376YK.js → google-vertex-C474FXU7.js} +1 -1
  28. package/dist/bundle/chunks/{help-fast-path-NZ3I2UEN.js → help-fast-path-3U3YDEZ6.js} +1 -1
  29. package/dist/bundle/chunks/{host-command-RORPAC5X.js → host-command-6CJ7YM6W.js} +1 -1
  30. package/dist/bundle/chunks/{host-lifecycle-UDMJGLOR.js → host-lifecycle-RZIMOFDM.js} +1 -1
  31. package/dist/bundle/chunks/host-lifecycle.js +6 -6
  32. package/dist/bundle/chunks/interactive-host-runtime-A3GEIFTU.js +4 -0
  33. package/dist/bundle/chunks/{interactive-mode-LOAADKLH.js → interactive-mode-LX665HTP.js} +1 -1
  34. package/dist/bundle/chunks/{list-tips-S5CANO5W.js → list-tips-S4U7TKER.js} +1 -1
  35. package/dist/bundle/chunks/multi-session-host-MFTUM6XQ.js +21 -0
  36. package/dist/bundle/chunks/{openai-codex-responses-YSGZZDD5.js → openai-codex-responses-2LDIFL6Z.js} +1 -1
  37. package/dist/bundle/chunks/{openai-completions-KWHRWCBN.js → openai-completions-7KZLPKYP.js} +1 -1
  38. package/dist/bundle/chunks/{openai-images-6U5FCN5S.js → openai-images-I7DR7ERP.js} +1 -1
  39. package/dist/bundle/chunks/{openai-responses-7PWMBGYX.js → openai-responses-LCHS3AF3.js} +1 -1
  40. package/dist/bundle/chunks/{openrouter-images-QIKWQZUD.js → openrouter-images-IPNDRK6C.js} +1 -1
  41. package/dist/bundle/chunks/{package-manager-cli-5EEDA35I.js → package-manager-cli-6IAE5WG3.js} +1 -1
  42. package/dist/bundle/chunks/{rotation-stream-KZG4OVR7.js → rotation-stream-ZVJEGA2G.js} +1 -1
  43. package/dist/bundle/chunks/{rpc-mode-HOEA5NGQ.js → rpc-mode-XN3HNZMH.js} +1 -1
  44. package/dist/bundle/chunks/session-picker-FPKB4DAC.js +2 -0
  45. package/dist/bundle/chunks/session-worker.js +318 -309
  46. package/dist/bundle/cli.js +1 -1
  47. package/dist/bundle/index.js +1 -1
  48. package/dist/bundle/rpc-entry.js +1 -1
  49. package/dist/cli/args.js +1 -1
  50. package/dist/cli/args.js.map +1 -1
  51. package/dist/cli/host-command.d.ts +8 -1
  52. package/dist/cli/host-command.d.ts.map +1 -1
  53. package/dist/cli/host-command.js +66 -14
  54. package/dist/cli/host-command.js.map +1 -1
  55. package/dist/core/agent-session.d.ts +18 -1
  56. package/dist/core/agent-session.d.ts.map +1 -1
  57. package/dist/core/agent-session.js +119 -3
  58. package/dist/core/agent-session.js.map +1 -1
  59. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts +2 -2
  60. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts.map +1 -1
  61. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +13 -5
  62. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js.map +1 -1
  63. package/dist/core/extensions/builtin/tool-search/native-search.d.ts.map +1 -1
  64. package/dist/core/extensions/builtin/tool-search/native-search.js +13 -1
  65. package/dist/core/extensions/builtin/tool-search/native-search.js.map +1 -1
  66. package/dist/core/retry-fallback/candidates.d.ts +26 -0
  67. package/dist/core/retry-fallback/candidates.d.ts.map +1 -0
  68. package/dist/core/retry-fallback/candidates.js +41 -0
  69. package/dist/core/retry-fallback/candidates.js.map +1 -0
  70. package/dist/core/retry-fallback/circuit-probes.d.ts +30 -0
  71. package/dist/core/retry-fallback/circuit-probes.d.ts.map +1 -0
  72. package/dist/core/retry-fallback/circuit-probes.js +60 -0
  73. package/dist/core/retry-fallback/circuit-probes.js.map +1 -0
  74. package/dist/core/retry-fallback/circuit.d.ts +101 -0
  75. package/dist/core/retry-fallback/circuit.d.ts.map +1 -0
  76. package/dist/core/retry-fallback/circuit.js +175 -0
  77. package/dist/core/retry-fallback/circuit.js.map +1 -0
  78. package/dist/core/retry-fallback/controller-types.d.ts +58 -0
  79. package/dist/core/retry-fallback/controller-types.d.ts.map +1 -0
  80. package/dist/core/retry-fallback/controller-types.js +2 -0
  81. package/dist/core/retry-fallback/controller-types.js.map +1 -0
  82. package/dist/core/retry-fallback/controller.d.ts +21 -49
  83. package/dist/core/retry-fallback/controller.d.ts.map +1 -1
  84. package/dist/core/retry-fallback/controller.js +88 -42
  85. package/dist/core/retry-fallback/controller.js.map +1 -1
  86. package/dist/core/sdk.d.ts.map +1 -1
  87. package/dist/core/sdk.js +25 -17
  88. package/dist/core/sdk.js.map +1 -1
  89. package/dist/core/session-failure-report.d.ts +33 -0
  90. package/dist/core/session-failure-report.d.ts.map +1 -0
  91. package/dist/core/session-failure-report.js +62 -0
  92. package/dist/core/session-failure-report.js.map +1 -0
  93. package/dist/core/settings-manager.d.ts +3 -0
  94. package/dist/core/settings-manager.d.ts.map +1 -1
  95. package/dist/core/settings-manager.js +4 -0
  96. package/dist/core/settings-manager.js.map +1 -1
  97. package/dist/core/slash-commands.d.ts.map +1 -1
  98. package/dist/core/slash-commands.js +1 -0
  99. package/dist/core/slash-commands.js.map +1 -1
  100. package/dist/index.d.ts +1 -1
  101. package/dist/index.d.ts.map +1 -1
  102. package/dist/index.js +1 -1
  103. package/dist/index.js.map +1 -1
  104. package/dist/modes/index.d.ts +1 -0
  105. package/dist/modes/index.d.ts.map +1 -1
  106. package/dist/modes/index.js +2 -0
  107. package/dist/modes/index.js.map +1 -1
  108. package/dist/modes/interactive/help-content.d.ts.map +1 -1
  109. package/dist/modes/interactive/help-content.js +3 -0
  110. package/dist/modes/interactive/help-content.js.map +1 -1
  111. package/dist/modes/interactive/interactive-host-attach.d.ts +10 -0
  112. package/dist/modes/interactive/interactive-host-attach.d.ts.map +1 -0
  113. package/dist/modes/interactive/interactive-host-attach.js +14 -0
  114. package/dist/modes/interactive/interactive-host-attach.js.map +1 -0
  115. package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -1
  116. package/dist/modes/interactive/interactive-host-runtime.js +3 -6
  117. package/dist/modes/interactive/interactive-host-runtime.js.map +1 -1
  118. package/dist/modes/interactive/interactive-mode.d.ts +12 -0
  119. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  120. package/dist/modes/interactive/interactive-mode.js +95 -1
  121. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  122. package/dist/modes/interactive/session-failure-info.d.ts +3 -0
  123. package/dist/modes/interactive/session-failure-info.d.ts.map +1 -0
  124. package/dist/modes/interactive/session-failure-info.js +21 -0
  125. package/dist/modes/interactive/session-failure-info.js.map +1 -0
  126. package/dist/modes/interactive/tips/catalog/model-tips.d.ts +7 -7
  127. package/dist/modes/interactive/tips/catalog/model-tips.d.ts.map +1 -1
  128. package/dist/modes/interactive/tips/catalog/model-tips.js +7 -1
  129. package/dist/modes/interactive/tips/catalog/model-tips.js.map +1 -1
  130. package/dist/modes/interactive/tips/catalog/session-tips.d.ts.map +1 -1
  131. package/dist/modes/interactive/tips/catalog/session-tips.js +1 -1
  132. package/dist/modes/interactive/tips/catalog/session-tips.js.map +1 -1
  133. package/dist/modes/rpc/host-attach-hold.d.ts +16 -0
  134. package/dist/modes/rpc/host-attach-hold.d.ts.map +1 -0
  135. package/dist/modes/rpc/host-attach-hold.js +9 -0
  136. package/dist/modes/rpc/host-attach-hold.js.map +1 -0
  137. package/dist/modes/rpc/host-cleanup-paths.d.ts +20 -0
  138. package/dist/modes/rpc/host-cleanup-paths.d.ts.map +1 -0
  139. package/dist/modes/rpc/host-cleanup-paths.js +13 -0
  140. package/dist/modes/rpc/host-cleanup-paths.js.map +1 -0
  141. package/dist/modes/rpc/host-client-occupancy.d.ts +24 -0
  142. package/dist/modes/rpc/host-client-occupancy.d.ts.map +1 -0
  143. package/dist/modes/rpc/host-client-occupancy.js +53 -0
  144. package/dist/modes/rpc/host-client-occupancy.js.map +1 -0
  145. package/dist/modes/rpc/host-daemon-paths.d.ts +61 -8
  146. package/dist/modes/rpc/host-daemon-paths.d.ts.map +1 -1
  147. package/dist/modes/rpc/host-daemon-paths.js +128 -11
  148. package/dist/modes/rpc/host-daemon-paths.js.map +1 -1
  149. package/dist/modes/rpc/host-daemon-registration.d.ts +11 -1
  150. package/dist/modes/rpc/host-daemon-registration.d.ts.map +1 -1
  151. package/dist/modes/rpc/host-daemon-registration.js +28 -15
  152. package/dist/modes/rpc/host-daemon-registration.js.map +1 -1
  153. package/dist/modes/rpc/host-endpoints.d.ts +12 -0
  154. package/dist/modes/rpc/host-endpoints.d.ts.map +1 -0
  155. package/dist/modes/rpc/host-endpoints.js +59 -0
  156. package/dist/modes/rpc/host-endpoints.js.map +1 -0
  157. package/dist/modes/rpc/host-ensure-lock.d.ts +11 -0
  158. package/dist/modes/rpc/host-ensure-lock.d.ts.map +1 -0
  159. package/dist/modes/rpc/host-ensure-lock.js +49 -0
  160. package/dist/modes/rpc/host-ensure-lock.js.map +1 -0
  161. package/dist/modes/rpc/host-ensure.d.ts +7 -0
  162. package/dist/modes/rpc/host-ensure.d.ts.map +1 -1
  163. package/dist/modes/rpc/host-ensure.js +42 -65
  164. package/dist/modes/rpc/host-ensure.js.map +1 -1
  165. package/dist/modes/rpc/host-gc-evidence.d.ts +18 -0
  166. package/dist/modes/rpc/host-gc-evidence.d.ts.map +1 -0
  167. package/dist/modes/rpc/host-gc-evidence.js +128 -0
  168. package/dist/modes/rpc/host-gc-evidence.js.map +1 -0
  169. package/dist/modes/rpc/host-gc.d.ts +28 -0
  170. package/dist/modes/rpc/host-gc.d.ts.map +1 -0
  171. package/dist/modes/rpc/host-gc.js +110 -0
  172. package/dist/modes/rpc/host-gc.js.map +1 -0
  173. package/dist/modes/rpc/host-generations.d.ts +10 -2
  174. package/dist/modes/rpc/host-generations.d.ts.map +1 -1
  175. package/dist/modes/rpc/host-generations.js +12 -7
  176. package/dist/modes/rpc/host-generations.js.map +1 -1
  177. package/dist/modes/rpc/host-handoff.d.ts +6 -0
  178. package/dist/modes/rpc/host-handoff.d.ts.map +1 -1
  179. package/dist/modes/rpc/host-handoff.js +31 -4
  180. package/dist/modes/rpc/host-handoff.js.map +1 -1
  181. package/dist/modes/rpc/host-lifecycle-policy.d.ts +53 -0
  182. package/dist/modes/rpc/host-lifecycle-policy.d.ts.map +1 -0
  183. package/dist/modes/rpc/host-lifecycle-policy.js +64 -0
  184. package/dist/modes/rpc/host-lifecycle-policy.js.map +1 -0
  185. package/dist/modes/rpc/host-lifecycle.d.ts +1 -44
  186. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
  187. package/dist/modes/rpc/host-lifecycle.js +23 -85
  188. package/dist/modes/rpc/host-lifecycle.js.map +1 -1
  189. package/dist/modes/rpc/host-observe-request.d.ts +17 -0
  190. package/dist/modes/rpc/host-observe-request.d.ts.map +1 -0
  191. package/dist/modes/rpc/host-observe-request.js +30 -0
  192. package/dist/modes/rpc/host-observe-request.js.map +1 -0
  193. package/dist/modes/rpc/host-probe.d.ts +12 -0
  194. package/dist/modes/rpc/host-probe.d.ts.map +1 -1
  195. package/dist/modes/rpc/host-probe.js +28 -1
  196. package/dist/modes/rpc/host-probe.js.map +1 -1
  197. package/dist/modes/rpc/host-protocol-info.d.ts +2 -0
  198. package/dist/modes/rpc/host-protocol-info.d.ts.map +1 -1
  199. package/dist/modes/rpc/host-protocol-info.js +1 -0
  200. package/dist/modes/rpc/host-protocol-info.js.map +1 -1
  201. package/dist/modes/rpc/host-readiness.d.ts +22 -0
  202. package/dist/modes/rpc/host-readiness.d.ts.map +1 -0
  203. package/dist/modes/rpc/host-readiness.js +44 -0
  204. package/dist/modes/rpc/host-readiness.js.map +1 -0
  205. package/dist/modes/rpc/host-runner.d.ts +13 -0
  206. package/dist/modes/rpc/host-runner.d.ts.map +1 -1
  207. package/dist/modes/rpc/host-runner.js +23 -4
  208. package/dist/modes/rpc/host-runner.js.map +1 -1
  209. package/dist/modes/rpc/host-status-all.d.ts +31 -0
  210. package/dist/modes/rpc/host-status-all.d.ts.map +1 -0
  211. package/dist/modes/rpc/host-status-all.js +78 -0
  212. package/dist/modes/rpc/host-status-all.js.map +1 -0
  213. package/dist/modes/rpc/host-status-rows.d.ts +35 -0
  214. package/dist/modes/rpc/host-status-rows.d.ts.map +1 -0
  215. package/dist/modes/rpc/host-status-rows.js +42 -0
  216. package/dist/modes/rpc/host-status-rows.js.map +1 -0
  217. package/dist/modes/rpc/host-status.d.ts +32 -1
  218. package/dist/modes/rpc/host-status.d.ts.map +1 -1
  219. package/dist/modes/rpc/host-status.js +33 -27
  220. package/dist/modes/rpc/host-status.js.map +1 -1
  221. package/dist/modes/rpc/host-successor.d.ts +3 -1
  222. package/dist/modes/rpc/host-successor.d.ts.map +1 -1
  223. package/dist/modes/rpc/host-successor.js +105 -42
  224. package/dist/modes/rpc/host-successor.js.map +1 -1
  225. package/dist/modes/rpc/host-watchdog.d.ts +6 -0
  226. package/dist/modes/rpc/host-watchdog.d.ts.map +1 -1
  227. package/dist/modes/rpc/host-watchdog.js +12 -13
  228. package/dist/modes/rpc/host-watchdog.js.map +1 -1
  229. package/dist/modes/rpc/loop-lag-watchdog.d.ts +16 -0
  230. package/dist/modes/rpc/loop-lag-watchdog.d.ts.map +1 -1
  231. package/dist/modes/rpc/loop-lag-watchdog.js +34 -2
  232. package/dist/modes/rpc/loop-lag-watchdog.js.map +1 -1
  233. package/dist/modes/rpc/multi-session-host.d.ts +2 -1
  234. package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
  235. package/dist/modes/rpc/multi-session-host.js +33 -6
  236. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  237. package/dist/modes/rpc/rpc-mode.d.ts +2 -2
  238. package/dist/modes/rpc/rpc-mode.js +2 -2
  239. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  240. package/dist/modes/rpc/rpc-types.d.ts +16 -0
  241. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  242. package/dist/modes/rpc/rpc-types.js.map +1 -1
  243. package/dist/modes/rpc/session-command-router.d.ts +9 -1
  244. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  245. package/dist/modes/rpc/session-command-router.js +4 -1
  246. package/dist/modes/rpc/session-command-router.js.map +1 -1
  247. package/dist/modes/rpc/session-path-key.d.ts +3 -1
  248. package/dist/modes/rpc/session-path-key.d.ts.map +1 -1
  249. package/dist/modes/rpc/session-path-key.js +3 -1
  250. package/dist/modes/rpc/session-path-key.js.map +1 -1
  251. package/docs/rpc.md +186 -19
  252. package/docs/settings.md +25 -1
  253. package/docs/usage.md +5 -2
  254. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +24 -0
  255. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  256. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  257. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  258. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  259. package/node_modules/@earendil-works/pi-ai/dist/utils/error-body.d.ts +6 -0
  260. package/node_modules/@earendil-works/pi-ai/dist/utils/error-body.d.ts.map +1 -1
  261. package/node_modules/@earendil-works/pi-ai/dist/utils/error-body.js +36 -0
  262. package/node_modules/@earendil-works/pi-ai/dist/utils/error-body.js.map +1 -1
  263. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts +1 -0
  264. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts.map +1 -1
  265. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +14 -1
  266. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js.map +1 -1
  267. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  268. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  269. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  270. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.d.ts.map +1 -1
  271. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.js +6 -4
  272. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.js.map +1 -1
  273. package/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts +3 -0
  274. package/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts.map +1 -1
  275. package/node_modules/@earendil-works/pi-tui/dist/components/editor.js +20 -0
  276. package/node_modules/@earendil-works/pi-tui/dist/components/editor.js.map +1 -1
  277. package/node_modules/@earendil-works/pi-tui/dist/editor-component.d.ts +2 -0
  278. package/node_modules/@earendil-works/pi-tui/dist/editor-component.d.ts.map +1 -1
  279. package/node_modules/@earendil-works/pi-tui/dist/editor-component.js.map +1 -1
  280. package/node_modules/@earendil-works/pi-tui/dist/slash-command-autocomplete.d.ts +5 -0
  281. package/node_modules/@earendil-works/pi-tui/dist/slash-command-autocomplete.d.ts.map +1 -1
  282. package/node_modules/@earendil-works/pi-tui/dist/slash-command-autocomplete.js +7 -0
  283. package/node_modules/@earendil-works/pi-tui/dist/slash-command-autocomplete.js.map +1 -1
  284. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  285. package/package.json +7 -7
  286. package/dist/bundle/chunks/chunk-3DEXCYNN.js +0 -135
  287. package/dist/bundle/chunks/chunk-5X4KSPK5.js +0 -12
  288. package/dist/bundle/chunks/chunk-KMD5ZONU.js +0 -5
  289. package/dist/bundle/chunks/chunk-PEHZYGYA.js +0 -8
  290. package/dist/bundle/chunks/chunk-PRC5XIIH.js +0 -2
  291. package/dist/bundle/chunks/chunk-QKY33652.js +0 -18
  292. package/dist/bundle/chunks/interactive-host-runtime-TIFT2SKR.js +0 -4
  293. package/dist/bundle/chunks/multi-session-host-GRHKB7Q2.js +0 -21
  294. package/dist/bundle/chunks/session-picker-FTFCQYHH.js +0 -2
@@ -21,8 +21,8 @@ import{__export}from"./chunk-IKOFCODM.js";function parseTmuxKittyTerminalOverrid
21
21
  `);throw new Error(errorMsg)}}let truncatedLine=sliceByColumn(line,0,width,!0)+TUI.SEGMENT_RESET;newLines[i]=truncatedLine,buffer+=truncatedLine;continue}buffer+=line}let finalCursorRow=renderEnd;if(this.previousLines.length>newLines.length){if(renderEnd<newLines.length-1){let moveDown=newLines.length-1-renderEnd;buffer+=`\x1B[${moveDown}B`,finalCursorRow=newLines.length-1}let extraLines=this.previousLines.length-newLines.length;for(let i=newLines.length;i<this.previousLines.length;i++)buffer+=`\r
22
22
  \x1B[2K${TUI.SEGMENT_RESET}`;buffer+=`\x1B[${extraLines}A`}if(buffer=this.finishFrame(buffer,cursorPos,newLines.length,finalCursorRow),process.env.PI_TUI_DEBUG==="1"){let debugDir="/tmp/tui";fs.mkdirSync(debugDir,{recursive:!0});let debugPath=path.join(debugDir,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),debugData=[`firstChanged: ${firstChanged}`,`viewportTop: ${viewportTop}`,`cursorRow: ${this.cursorRow}`,`height: ${height}`,`lineDiff: ${lineDiff}`,`hardwareCursorRow: ${hardwareCursorRow}`,`renderEnd: ${renderEnd}`,`finalCursorRow: ${finalCursorRow}`,`cursorPos: ${JSON.stringify(cursorPos)}`,`newLines.length: ${newLines.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(newLines,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",JSON.stringify(buffer)].join(`
23
23
  `);fs.writeFileSync(debugPath,debugData,{encoding:"utf8",mode:DIAGNOSTIC_LOG_MODE}),chmodDiagnosticLogBestEffort(debugPath)}writeBounded(this.terminal,buffer),this.cursorRow=Math.max(0,newLines.length-1),this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length),this.previousViewportTop=Math.max(prevViewportTop,finalCursorRow-height+1),this.setPreviousLines(newLines,rawLines),needsKittyImageExpansion&&(this.previousKittyImageIds=this.collectKittyImageIds(newLines)),this.previousWidth=width,this.previousHeight=height}buildHardwareCursorSequence(cursorPos,totalLines){let buffer="";if(!cursorPos||totalLines<=0)this.#lastCursorVisibility!==!1&&(buffer+="\x1B[?25l",this.#lastCursorVisibility=!1);else{let targetRow=Math.max(0,Math.min(cursorPos.row,totalLines-1)),targetCol=Math.max(0,cursorPos.col),rowDelta=targetRow-this.hardwareCursorRow;rowDelta>0?buffer+=`\x1B[${rowDelta}B`:rowDelta<0&&(buffer+=`\x1B[${-rowDelta}A`),buffer+=`\x1B[${targetCol+1}G`,this.hardwareCursorRow=targetRow,this.#lastCursorVisibility!==this.showHardwareCursor&&(buffer+=this.showHardwareCursor?"\x1B[?25h":"\x1B[?25l",this.#lastCursorVisibility=this.showHardwareCursor)}return buffer}finishFrame(buffer,cursorPos,totalLines,hardwareCursorRow){return this.hardwareCursorRow=hardwareCursorRow,buffer+this.buildHardwareCursorSequence(cursorPos,totalLines)+TUI.FRAME_END}positionHardwareCursor(cursorPos,totalLines){let buffer=this.buildHardwareCursorSequence(cursorPos,totalLines);buffer&&this.terminal.write(TUI.FRAME_BEGIN+buffer+TUI.FRAME_END)}queryTerminalBackgroundColor({timeoutMs}){return new Promise(resolve=>{let query={settled:!1,resolve,timer:void 0};query.timer=setTimeout(()=>{query.settled||(query.settled=!0,query.timer=void 0,query.resolve?.(void 0),query.resolve=void 0)},timeoutMs),this.pendingOsc11BackgroundQueries.push(query),this.pendingOsc11BackgroundReplies+=1,this.terminal.write("\x1B]11;?\x07")})}queryTerminalColorScheme({timeoutMs}){return new Promise(resolve=>{let settled=!1,timer,unsubscribe=()=>{},settle=scheme=>{settled||(settled=!0,timer&&(clearTimeout(timer),timer=void 0),unsubscribe(),resolve(scheme))};unsubscribe=this.onTerminalColorSchemeChange(settle),timer=setTimeout(()=>settle(void 0),timeoutMs),this.terminal.write("\x1B[?996n")})}},TUI=class extends TuiBase{constructor(){super(...arguments),this.mode="regular"}};function isAsciiLetter(char){if(!char)return!1;let code=char.charCodeAt(0);return code>=97&&code<=122}function isAsciiDigit(char){if(!char)return!1;let code=char.charCodeAt(0);return code>=48&&code<=57}function isWordBoundaryPrefix(char){switch(char){case" ":case" ":case`
24
- `:case"\r":case"-":case"_":case".":case"/":case":":return!0;default:return!1}}function scoreMatch(queryLower,textLower){if(queryLower.length===0)return{matches:!0,score:0};if(queryLower.length>textLower.length)return{matches:!1,score:0};let queryIndex=0,score=0,lastMatchIndex=-1,consecutiveMatches=0;for(let i=0;i<textLower.length&&queryIndex<queryLower.length;i++)if(textLower[i]===queryLower[queryIndex]){let isWordBoundary=i===0||isWordBoundaryPrefix(textLower[i-1]);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<queryLower.length?{matches:!1,score:0}:(queryLower===textLower&&(score-=100),{matches:!0,score})}function addWholeTokenSwap(variants,queryLower){let splitIndex=0;for(;splitIndex<queryLower.length&&isAsciiLetter(queryLower[splitIndex]);)splitIndex++;if(splitIndex>0&&splitIndex<queryLower.length){let digitEnd=splitIndex;for(;digitEnd<queryLower.length&&isAsciiDigit(queryLower[digitEnd]);)digitEnd++;digitEnd===queryLower.length&&variants.add(queryLower.slice(splitIndex)+queryLower.slice(0,splitIndex))}for(splitIndex=0;splitIndex<queryLower.length&&isAsciiDigit(queryLower[splitIndex]);)splitIndex++;if(splitIndex>0&&splitIndex<queryLower.length){let letterEnd=splitIndex;for(;letterEnd<queryLower.length&&isAsciiLetter(queryLower[letterEnd]);)letterEnd++;letterEnd===queryLower.length&&variants.add(queryLower.slice(splitIndex)+queryLower.slice(0,splitIndex))}}function buildAlphanumericSwapQueries(queryLower){let variants=new Set;addWholeTokenSwap(variants,queryLower);for(let i=0;i<queryLower.length-1;i++){let current=queryLower[i],next=queryLower[i+1];(isAsciiLetter(current)&&isAsciiDigit(next)||isAsciiDigit(current)&&isAsciiLetter(next))&&variants.add(queryLower.slice(0,i)+next+current+queryLower.slice(i+2))}return[...variants]}function fuzzyMatch(query,text){return fuzzyMatchLower(query.toLowerCase(),text.toLowerCase())}function fuzzyMatchLower(queryLower,textLower){let direct=scoreMatch(queryLower,textLower);if(direct.matches)return direct;let bestSwap=null;for(let variant of buildAlphanumericSwapQueries(queryLower)){let match=scoreMatch(variant,textLower);if(!match.matches)continue;let score=match.score+5;(!bestSwap||score<bestSwap.score)&&(bestSwap={matches:!0,score})}return bestSwap??direct}function fuzzyFilter(items,query,getText){if(!query.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((a,b2)=>a.totalScore-b2.totalScore),results.map(r=>r.item)}import{spawn}from"child_process";import{readdirSync,statSync}from"fs";import{homedir as homedir3}from"os";import{basename,dirname as dirname2,join as join2}from"path";var SKILL_COMMAND_PREFIX="skill:",DOLLAR_QUERY_PATTERN=/^\$([a-zA-Z0-9:_-]*)$/,DOLLAR_MENTION_PATTERN=/(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g,COMMON_SHELL_VARIABLES=new Set(["CI","EDITOR","HOME","LANG","LC_ALL","NODE_ENV","OLDPWD","PATH","PWD","SHELL","SHLVL","TERM","TMPDIR","USER","VISUAL"]);function isDollarQueryCompletable(query){return query===""?!0:query.startsWith("-")||query.startsWith("_")||/^\d/.test(query)?!1:!COMMON_SHELL_VARIABLES.has(query)}function commandName(command){return"name"in command?command.name:command.value}function skillName(name){return name.startsWith(SKILL_COMMAND_PREFIX)&&name.slice(SKILL_COMMAND_PREFIX.length)||null}function commandDescription(command){let hint="argumentHint"in command&&command.argumentHint?command.argumentHint:void 0,description=command.description??"";return hint?description?`${hint} \u2014 ${description}`:hint:description||void 0}function findDollarSkillMentions(line,knownSkills){if(knownSkills.size===0)return[];let mentions=[];for(let match of line.matchAll(DOLLAR_MENTION_PATTERN)){let token=match[2]??"",name=token.startsWith(SKILL_COMMAND_PREFIX)?token.slice(SKILL_COMMAND_PREFIX.length):token;if(!knownSkills.has(name))continue;let start=match.index+(match[1]??"").length;mentions.push({start,end:start+token.length+1,name})}return mentions}function knownSkillNames(commands){return new Set(commands.flatMap(command=>{let name=skillName(commandName(command));return name?[name]:[]}))}function getDollarInvocationContext(textBeforeCursor,_cursorLine,commands){let tokenStart=textBeforeCursor.search(/\S+$/),token=tokenStart===-1?"":textBeforeCursor.slice(tokenStart),match=DOLLAR_QUERY_PATTERN.exec(token);if(!match)return null;let rawQuery=match[1]??"";if(!isDollarQueryCompletable(rawQuery))return null;let explicitSkillNamespace=rawQuery.startsWith(SKILL_COMMAND_PREFIX),query=explicitSkillNamespace?rawQuery.slice(SKILL_COMMAND_PREFIX.length):rawQuery;if(knownSkillNames(commands).has(query))return null;let isFirstToken=textBeforeCursor.slice(0,tokenStart).trim()==="";return{prefix:`$${rawQuery}`,query,skillsOnly:explicitSkillNamespace||!isFirstToken}}function getDollarInvocationSuggestions(commands,query,skillsOnly){let items=commands.flatMap(command=>{let name=commandName(command),skill=skillName(name);return skill?[{kind:"skill",value:`$${skill}`,label:`$${skill}`,searchText:skill,description:commandDescription(command)}]:skillsOnly?[]:[{kind:"command",value:`/${name}`,label:`/${name}`,searchText:name,description:commandDescription(command)}]});return fuzzyFilter(items,query,item=>item.searchText).map((item,index)=>({...item,index})).sort((left,right)=>left.kind!==right.kind?left.kind==="command"?-1:1:left.index-right.index).map(({index:_index,kind:_kind,searchText:_searchText,...item})=>item)}var SKILL_COMMAND_PREFIX2="skill:";function compareSlashCommandSuggestion(prefix,left,right){let leftExact=left.value===prefix,rightExact=right.value===prefix;if(leftExact!==rightExact)return leftExact?-1:1;let leftPrefix=left.value.startsWith(prefix),rightPrefix=right.value.startsWith(prefix);return leftPrefix!==rightPrefix?leftPrefix?-1:1:leftPrefix&&rightPrefix&&left.value.length!==right.value.length?right.value.length-left.value.length:left.index-right.index}function getSlashCommandSuggestions(commands,prefix){let normalizedPrefix=prefix.toLowerCase(),explicitSkillNamespace=normalizedPrefix.startsWith(SKILL_COMMAND_PREFIX2),hasSkillCommands=commands.some(cmd=>("name"in cmd?cmd.name:cmd.value).startsWith(SKILL_COMMAND_PREFIX2)),commandItems=commands.flatMap(cmd=>{let name="name"in cmd?cmd.name:cmd.value,isSkill=name.startsWith(SKILL_COMMAND_PREFIX2),skillName2=isSkill?name.slice(SKILL_COMMAND_PREFIX2.length):"";if(isSkill&&!explicitSkillNamespace&&(normalizedPrefix.length===0||!skillName2.toLowerCase().startsWith(normalizedPrefix)))return[];let 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,searchText:isSkill&&!explicitSkillNamespace?skillName2:name}]});return hasSkillCommands&&!explicitSkillNamespace&&normalizedPrefix.length>0&&SKILL_COMMAND_PREFIX2.startsWith(normalizedPrefix)&&commandItems.push({name:SKILL_COMMAND_PREFIX2,label:SKILL_COMMAND_PREFIX2,description:"Browse available skills",searchText:SKILL_COMMAND_PREFIX2}),fuzzyFilter(commandItems,prefix,item=>item.searchText).map((item,index)=>({value:item.name,label:item.label,...item.description&&{description:item.description},index})).sort((left,right)=>compareSlashCommandSuggestion(normalizedPrefix,left,right)).map(({index:_index,...item})=>item)}var PATH_DELIMITERS=new Set([" "," ",'"',"'","="]);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.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){for(let i=text.length-1;i>=0;i-=1)if(PATH_DELIMITERS.has(text[i]??""))return i;return-1}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){return index===0||PATH_DELIMITERS.has(text[index-1]??"")}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}:prefix.startsWith("@")?{rawPrefix:prefix.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:prefix,isAtPrefix:!1,isQuotedPrefix:!1}}function buildCompletionValue(path4,options){let needsQuotes=options.isQuotedPrefix||path4.includes(" "),prefix=options.isAtPrefix?"@":"";return needsQuotes?`${`${prefix}"`}${path4}"`:`${prefix}${path4}`}async function walkDirectoryWithFd(baseDir,fdPath,query,maxResults,signal,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)),await new Promise(resolve=>{if(signal.aborted){resolve([]);return}let child=spawn(fdPath,args,{stdio:["ignore","pipe","pipe"]}),stdout="",resolved=!1,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(`
25
- `).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{constructor(commands=[],basePath,fdPath=null){this.commands=commands,this.basePath=basePath,this.fdPath=fdPath}getMentionRanges(line){return findDollarSkillMentions(line,knownSkillNames(this.commands)).map(({start,end})=>({start,end}))}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 dollarContext=getDollarInvocationContext(textBeforeCursor,cursorLine,this.commands);if(dollarContext){let suggestions2=getDollarInvocationSuggestions(this.commands,dollarContext.query,dollarContext.skillsOnly);return suggestions2.length===0?null:{items:suggestions2,prefix:dollarContext.prefix}}if(!options.force&&textBeforeCursor.startsWith("/")){let spaceIndex=textBeforeCursor.indexOf(" ");if(spaceIndex===-1){let prefix=textBeforeCursor.slice(1),filtered=getSlashCommandSuggestions(this.commands,prefix);return filtered.length===0?null:{items:filtered,prefix:textBeforeCursor}}let tokenStart=textBeforeCursor.search(/\S+$/),currentToken=tokenStart===-1?"":textBeforeCursor.slice(tokenStart);if(currentToken.startsWith("/skill:")&&this.isLeadingKnownSkillCommandRun(textBeforeCursor.slice(0,tokenStart))){let skillCommands=this.commands.filter(command2=>("name"in command2?command2.name:command2.value).startsWith("skill:")),filtered=getSlashCommandSuggestions(skillCommands,currentToken.slice(1));return filtered.length===0?null:{items:filtered,prefix:currentToken}}let commandName2=textBeforeCursor.slice(1,spaceIndex),argumentText=textBeforeCursor.slice(spaceIndex+1),command=this.commands.find(cmd=>("name"in cmd?cmd.name:cmd.value)===commandName2);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,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.startsWith("$")&&(item.value.startsWith("/")||item.value.startsWith("$"))){let newLine2=`${beforePrefix}${item.value} ${adjustedAfterCursor}`,newLines2=[...lines];return newLines2[cursorLine]=newLine2,{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+item.value.length+1}}if(prefix.startsWith("/")&&!prefix.slice(1).includes("/")&&(beforePrefix.trim()===""||prefix.startsWith("/skill:")&&this.isLeadingKnownSkillCommandRun(beforePrefix))){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.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('"'),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+cursorOffset}}isLeadingKnownSkillCommandRun(text){let tokens=text.trim().split(/\s+/);return tokens.length>0&&tokens.every(token=>{if(!token.startsWith("/skill:"))return!1;let commandName2=token.slice(1);return this.commands.some(command=>("name"in command?command.name:command.value)===commandName2)})}extractAtPrefix(text){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix?.startsWith('@"'))return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),tokenStart=lastDelimiterIndex===-1?0:lastDelimiterIndex+1;return text[tokenStart]==="@"?text.slice(tokenStart):null}extractPathPrefix(text,forceExtract=!1){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix)return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),pathPrefix=lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1);return forceExtract||pathPrefix.includes("/")||pathPrefix.startsWith(".")||pathPrefix.startsWith("~/")||pathPrefix===""&&text.endsWith(" ")?pathPrefix:null}expandHomePath(path4){if(path4.startsWith("~/")){let expandedPath=join2(homedir3(),path4.slice(2));return path4.endsWith("/")&&!expandedPath.endsWith("/")?`${expandedPath}/`:expandedPath}else if(path4==="~")return homedir3();return path4}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=join2(this.basePath,displayBase);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=this.expandHomePath(expandedPrefix)),rawPrefix===""||rawPrefix==="./"||rawPrefix==="../"||rawPrefix==="~"||rawPrefix==="~/"||rawPrefix==="/"||isAtPrefix&&rawPrefix==="")rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join2(this.basePath,expandedPrefix),searchPrefix="";else if(rawPrefix.endsWith("/"))rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join2(this.basePath,expandedPrefix),searchPrefix="";else{let dir=dirname2(expandedPrefix),file=basename(expandedPrefix);rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=dir:searchDir=join2(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=join2(searchDir,entry.name);isDirectory=statSync(fullPath).isDirectory()}catch{}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=dirname2(homeRelativeDir);relativePath=`~/${dir==="."?name:join2(dir,name)}`}else if(displayPrefix.startsWith("/")){let dir=dirname2(displayPrefix);dir==="/"?relativePath=`/${name}`:relativePath=`${dir}/${name}`}else relativePath=join2(dirname2(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((a,b2)=>{let aIsDir=a.value.endsWith("/"),bIsDir=b2.value.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a.label.localeCompare(b2.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){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=await this.getBaseDirSuggestions(fdBaseDir,fdQuery,options.signal),recursiveEntries=await walkDirectoryWithFd(fdBaseDir,this.fdPath,fdQuery,100,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((a,b2)=>{let scoreDiff=b2.score-a.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(a.path).split("/").filter(Boolean).length,bDepth=toDisplayPath(b2.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a.path.length-b2.path.length;return lengthDiff!==0?lengthDiff:a.path.localeCompare(b2.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.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.trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};var Text=class{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}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-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=" ".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 this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};var DEFAULT_PRIMARY_COLUMN_WIDTH=32,PRIMARY_COLUMN_GAP=2,MIN_DESCRIPTION_WIDTH=10,normalizeToSingleLine=text=>text.replace(/[\r\n]+/g," ").trim(),clamp=(value,min,max)=>Math.max(min,Math.min(value,max)),SelectList=class{constructor(items,maxVisible,theme,layout={}){this.items=[],this.filteredItems=[],this.selectedIndex=0,this.maxVisible=5,this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme,this.layout=layout}setFilter(filter){this.filteredItems=this.items.filter(item=>item.value.toLowerCase().startsWith(filter.toLowerCase())),this.selectedIndex=0}setSelectedIndex(index){this.selectedIndex=Math.max(0,Math.min(index,this.filteredItems.length-1))}invalidate(){}render(width){let lines=[];if(this.filteredItems.length===0)return lines.push(this.theme.noMatch(" No matching commands")),lines;let primaryColumnWidth=this.getPrimaryColumnWidth(),{startIndex,endIndex}=this.getVisibleRange();for(let i=startIndex;i<endIndex;i++){let item=this.filteredItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,descriptionSingleLine=item.description?normalizeToSingleLine(item.description):void 0;lines.push(this.renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth))}if(startIndex>0||endIndex<this.filteredItems.length){let scrollText=` (${this.selectedIndex+1}/${this.filteredItems.length})`;lines.push(this.theme.scrollInfo(truncateToWidth(scrollText,width-2,"")))}return lines}handleMouse(event){if(this.filteredItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+delta)),this.selectedIndex!==previousIndex&&this.notifySelectionChange(),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let{startIndex,endIndex}=this.getVisibleRange(),itemIndex=startIndex+event.y;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=itemIndex,this.selectedIndex!==itemIndex&&(this.selectedIndex=itemIndex,this.notifySelectionChange()),{handled:!0,focus:!0};if(event.type==="click"){let clickedIndex=this.mousePressedIndex??itemIndex;this.mousePressedIndex=void 0;let changed=this.selectedIndex!==clickedIndex;this.selectedIndex=clickedIndex,changed&&this.notifySelectionChange();let selectedItem=this.filteredItems[this.selectedIndex];return selectedItem&&this.onSelect?.(selectedItem),{handled:!0}}}}handleInput(keyData){let kb=getKeybindings();if(kb.matches(keyData,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.confirm")){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelect&&this.onSelect(selectedItem)}else kb.matches(keyData,"tui.select.cancel")&&this.onCancel&&this.onCancel()}getVisibleRange(){let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex,endIndex:Math.min(startIndex+this.maxVisible,this.filteredItems.length)}}renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth){let prefix=isSelected?"\u2192 ":" ",prefixWidth=visibleWidth(prefix);if(descriptionSingleLine&&width>40){let effectivePrimaryColumnWidth=Math.max(1,Math.min(primaryColumnWidth,width-prefixWidth-4)),maxPrimaryWidth=Math.max(1,effectivePrimaryColumnWidth-PRIMARY_COLUMN_GAP),truncatedValue2=this.truncatePrimary(item,isSelected,maxPrimaryWidth,effectivePrimaryColumnWidth),truncatedValueWidth=visibleWidth(truncatedValue2),spacing=" ".repeat(Math.max(1,effectivePrimaryColumnWidth-truncatedValueWidth)),descriptionStart=prefixWidth+truncatedValueWidth+spacing.length,remainingWidth=width-descriptionStart-2;if(remainingWidth>MIN_DESCRIPTION_WIDTH){let truncatedDesc=truncateToWidth(descriptionSingleLine,remainingWidth,"");return this.composeRow(prefix,truncatedValue2,spacing+truncatedDesc,isSelected)}}let maxWidth=width-prefixWidth-2,truncatedValue=this.truncatePrimary(item,isSelected,maxWidth,maxWidth);return this.composeRow(prefix,truncatedValue,void 0,isSelected)}composeRow(prefix,primary,description,isSelected){return this.theme.renderRow?this.theme.renderRow({prefix:isSelected?this.theme.selectedPrefix(prefix):prefix,primary,description,isSelected}):isSelected?this.theme.selectedText(`${prefix}${primary}${description??""}`):prefix+primary+(description!==void 0?this.theme.description(description):"")}getPrimaryColumnWidth(){let{min,max}=this.getPrimaryColumnBounds(),widestPrimary=this.filteredItems.reduce((widest,item)=>Math.max(widest,visibleWidth(this.getDisplayValue(item))+PRIMARY_COLUMN_GAP),0);return clamp(widestPrimary,min,max)}getPrimaryColumnBounds(){let rawMin=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??DEFAULT_PRIMARY_COLUMN_WIDTH,rawMax=this.layout.maxPrimaryColumnWidth??this.layout.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||item.value}notifySelectionChange(){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelectionChange&&this.onSelectionChange(selectedItem)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};function A(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=A();function U(l3){T=l3}var E={exec:()=>null};function I(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),i=e[n];return i||(i=l3(n),e[n]=i),i}}function d(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(i,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(m.caret,"$1"),t=t.replace(i,o),n},getRegex:()=>new RegExp(t,e)};return n}var we=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),m={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,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l3=>new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:I(l3=>new RegExp(`^ {0,${l3}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)),headingBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}#`)),htmlBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:</?(?:${H})(?: +|$|/?>)|<(?:script|pre|style|textarea|!--))`,"i")),blockquoteBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}>`))},ye=/^(?:[ \t]*(?:\n|$))+/,Pe=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Se=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,v=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,_e=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,K=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,le=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ue=d(le).replace(/bull/g,K).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),$e=d(le).replace(/bull/g,K).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),W=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Le=/^[^\n]+/,X=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ze=d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",X).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ee=d(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,K).getRegex(),H="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",J=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Me=d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",J).replace("tag",H).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),pe=l3=>d(W).replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",l3).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Ae=pe(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ie=pe(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ce=d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ie).getRegex(),V={blockquote:Ce,code:Pe,def:ze,fences:Se,heading:_e,hr:v,html:Me,lheading:ue,list:Ee,newline:ye,paragraph:Ae,table:E,text:Le},ie=d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Be={...V,lheading:$e,table:ie,paragraph:d(W).replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ie).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex()},De={...V,html:d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",J).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:E,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(W).replace("hr",v).replace("heading",` *#{1,6} *[^
24
+ `:case"\r":case"-":case"_":case".":case"/":case":":return!0;default:return!1}}function scoreMatch(queryLower,textLower){if(queryLower.length===0)return{matches:!0,score:0};if(queryLower.length>textLower.length)return{matches:!1,score:0};let queryIndex=0,score=0,lastMatchIndex=-1,consecutiveMatches=0;for(let i=0;i<textLower.length&&queryIndex<queryLower.length;i++)if(textLower[i]===queryLower[queryIndex]){let isWordBoundary=i===0||isWordBoundaryPrefix(textLower[i-1]);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<queryLower.length?{matches:!1,score:0}:(queryLower===textLower&&(score-=100),{matches:!0,score})}function addWholeTokenSwap(variants,queryLower){let splitIndex=0;for(;splitIndex<queryLower.length&&isAsciiLetter(queryLower[splitIndex]);)splitIndex++;if(splitIndex>0&&splitIndex<queryLower.length){let digitEnd=splitIndex;for(;digitEnd<queryLower.length&&isAsciiDigit(queryLower[digitEnd]);)digitEnd++;digitEnd===queryLower.length&&variants.add(queryLower.slice(splitIndex)+queryLower.slice(0,splitIndex))}for(splitIndex=0;splitIndex<queryLower.length&&isAsciiDigit(queryLower[splitIndex]);)splitIndex++;if(splitIndex>0&&splitIndex<queryLower.length){let letterEnd=splitIndex;for(;letterEnd<queryLower.length&&isAsciiLetter(queryLower[letterEnd]);)letterEnd++;letterEnd===queryLower.length&&variants.add(queryLower.slice(splitIndex)+queryLower.slice(0,splitIndex))}}function buildAlphanumericSwapQueries(queryLower){let variants=new Set;addWholeTokenSwap(variants,queryLower);for(let i=0;i<queryLower.length-1;i++){let current=queryLower[i],next=queryLower[i+1];(isAsciiLetter(current)&&isAsciiDigit(next)||isAsciiDigit(current)&&isAsciiLetter(next))&&variants.add(queryLower.slice(0,i)+next+current+queryLower.slice(i+2))}return[...variants]}function fuzzyMatch(query,text){return fuzzyMatchLower(query.toLowerCase(),text.toLowerCase())}function fuzzyMatchLower(queryLower,textLower){let direct=scoreMatch(queryLower,textLower);if(direct.matches)return direct;let bestSwap=null;for(let variant of buildAlphanumericSwapQueries(queryLower)){let match=scoreMatch(variant,textLower);if(!match.matches)continue;let score=match.score+5;(!bestSwap||score<bestSwap.score)&&(bestSwap={matches:!0,score})}return bestSwap??direct}function fuzzyFilter(items,query,getText){if(!query.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((a,b2)=>a.totalScore-b2.totalScore),results.map(r=>r.item)}import{spawn}from"child_process";import{readdirSync,statSync}from"fs";import{homedir as homedir3}from"os";import{basename,dirname as dirname2,join as join2}from"path";var SKILL_COMMAND_PREFIX="skill:",DOLLAR_QUERY_PATTERN=/^\$([a-zA-Z0-9:_-]*)$/,DOLLAR_MENTION_PATTERN=/(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g,COMMON_SHELL_VARIABLES=new Set(["CI","EDITOR","HOME","LANG","LC_ALL","NODE_ENV","OLDPWD","PATH","PWD","SHELL","SHLVL","TERM","TMPDIR","USER","VISUAL"]);function isDollarQueryCompletable(query){return query===""?!0:query.startsWith("-")||query.startsWith("_")||/^\d/.test(query)?!1:!COMMON_SHELL_VARIABLES.has(query)}function commandName(command){return"name"in command?command.name:command.value}function skillName(name){return name.startsWith(SKILL_COMMAND_PREFIX)&&name.slice(SKILL_COMMAND_PREFIX.length)||null}function commandDescription(command){let hint="argumentHint"in command&&command.argumentHint?command.argumentHint:void 0,description=command.description??"";return hint?description?`${hint} \u2014 ${description}`:hint:description||void 0}function findDollarSkillMentions(line,knownSkills){if(knownSkills.size===0)return[];let mentions=[];for(let match of line.matchAll(DOLLAR_MENTION_PATTERN)){let token=match[2]??"",name=token.startsWith(SKILL_COMMAND_PREFIX)?token.slice(SKILL_COMMAND_PREFIX.length):token;if(!knownSkills.has(name))continue;let start=match.index+(match[1]??"").length;mentions.push({start,end:start+token.length+1,name})}return mentions}function knownSkillNames(commands){return new Set(commands.flatMap(command=>{let name=skillName(commandName(command));return name?[name]:[]}))}function getDollarInvocationContext(textBeforeCursor,_cursorLine,commands){let tokenStart=textBeforeCursor.search(/\S+$/),token=tokenStart===-1?"":textBeforeCursor.slice(tokenStart),match=DOLLAR_QUERY_PATTERN.exec(token);if(!match)return null;let rawQuery=match[1]??"";if(!isDollarQueryCompletable(rawQuery))return null;let explicitSkillNamespace=rawQuery.startsWith(SKILL_COMMAND_PREFIX),query=explicitSkillNamespace?rawQuery.slice(SKILL_COMMAND_PREFIX.length):rawQuery;if(knownSkillNames(commands).has(query))return null;let isFirstToken=textBeforeCursor.slice(0,tokenStart).trim()==="";return{prefix:`$${rawQuery}`,query,skillsOnly:explicitSkillNamespace||!isFirstToken}}function getDollarInvocationSuggestions(commands,query,skillsOnly){let items=commands.flatMap(command=>{let name=commandName(command),skill=skillName(name);return skill?[{kind:"skill",value:`$${skill}`,label:`$${skill}`,searchText:skill,description:commandDescription(command)}]:skillsOnly?[]:[{kind:"command",value:`/${name}`,label:`/${name}`,searchText:name,description:commandDescription(command)}]});return fuzzyFilter(items,query,item=>item.searchText).map((item,index)=>({...item,index})).sort((left,right)=>left.kind!==right.kind?left.kind==="command"?-1:1:left.index-right.index).map(({index:_index,kind:_kind,searchText:_searchText,...item})=>item)}var SKILL_COMMAND_PREFIX2="skill:";function isSlashNamespaceItem(value){return value.endsWith(":")}function compareSlashCommandSuggestion(prefix,left,right){let leftExact=left.value===prefix,rightExact=right.value===prefix;if(leftExact!==rightExact)return leftExact?-1:1;let leftPrefix=left.value.startsWith(prefix),rightPrefix=right.value.startsWith(prefix);return leftPrefix!==rightPrefix?leftPrefix?-1:1:leftPrefix&&rightPrefix&&left.value.length!==right.value.length?right.value.length-left.value.length:left.index-right.index}function getSlashCommandSuggestions(commands,prefix){let normalizedPrefix=prefix.toLowerCase(),explicitSkillNamespace=normalizedPrefix.startsWith(SKILL_COMMAND_PREFIX2),hasSkillCommands=commands.some(cmd=>("name"in cmd?cmd.name:cmd.value).startsWith(SKILL_COMMAND_PREFIX2)),commandItems=commands.flatMap(cmd=>{let name="name"in cmd?cmd.name:cmd.value,isSkill=name.startsWith(SKILL_COMMAND_PREFIX2),skillName2=isSkill?name.slice(SKILL_COMMAND_PREFIX2.length):"";if(isSkill&&!explicitSkillNamespace&&(normalizedPrefix.length===0||!skillName2.toLowerCase().startsWith(normalizedPrefix)))return[];let 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,searchText:isSkill&&!explicitSkillNamespace?skillName2:name}]});return hasSkillCommands&&!explicitSkillNamespace&&normalizedPrefix.length>0&&SKILL_COMMAND_PREFIX2.startsWith(normalizedPrefix)&&commandItems.push({name:SKILL_COMMAND_PREFIX2,label:SKILL_COMMAND_PREFIX2,description:"Browse available skills",searchText:SKILL_COMMAND_PREFIX2}),fuzzyFilter(commandItems,prefix,item=>item.searchText).map((item,index)=>({value:item.name,label:item.label,...item.description&&{description:item.description},index})).sort((left,right)=>compareSlashCommandSuggestion(normalizedPrefix,left,right)).map(({index:_index,...item})=>item)}var PATH_DELIMITERS=new Set([" "," ",'"',"'","="]);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.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){for(let i=text.length-1;i>=0;i-=1)if(PATH_DELIMITERS.has(text[i]??""))return i;return-1}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){return index===0||PATH_DELIMITERS.has(text[index-1]??"")}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}:prefix.startsWith("@")?{rawPrefix:prefix.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:prefix,isAtPrefix:!1,isQuotedPrefix:!1}}function buildCompletionValue(path4,options){let needsQuotes=options.isQuotedPrefix||path4.includes(" "),prefix=options.isAtPrefix?"@":"";return needsQuotes?`${`${prefix}"`}${path4}"`:`${prefix}${path4}`}async function walkDirectoryWithFd(baseDir,fdPath,query,maxResults,signal,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)),await new Promise(resolve=>{if(signal.aborted){resolve([]);return}let child=spawn(fdPath,args,{stdio:["ignore","pipe","pipe"]}),stdout="",resolved=!1,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(`
25
+ `).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{constructor(commands=[],basePath,fdPath=null){this.commands=commands,this.basePath=basePath,this.fdPath=fdPath}getMentionRanges(line){return findDollarSkillMentions(line,knownSkillNames(this.commands)).map(({start,end})=>({start,end}))}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 dollarContext=getDollarInvocationContext(textBeforeCursor,cursorLine,this.commands);if(dollarContext){let suggestions2=getDollarInvocationSuggestions(this.commands,dollarContext.query,dollarContext.skillsOnly);return suggestions2.length===0?null:{items:suggestions2,prefix:dollarContext.prefix}}if(!options.force&&textBeforeCursor.startsWith("/")){let spaceIndex=textBeforeCursor.indexOf(" ");if(spaceIndex===-1){let prefix=textBeforeCursor.slice(1),filtered=getSlashCommandSuggestions(this.commands,prefix);return filtered.length===0?null:{items:filtered,prefix:textBeforeCursor}}let tokenStart=textBeforeCursor.search(/\S+$/),currentToken=tokenStart===-1?"":textBeforeCursor.slice(tokenStart);if(currentToken.startsWith("/skill:")&&this.isLeadingKnownSkillCommandRun(textBeforeCursor.slice(0,tokenStart))){let skillCommands=this.commands.filter(command2=>("name"in command2?command2.name:command2.value).startsWith("skill:")),filtered=getSlashCommandSuggestions(skillCommands,currentToken.slice(1));return filtered.length===0?null:{items:filtered,prefix:currentToken}}let commandName2=textBeforeCursor.slice(1,spaceIndex),argumentText=textBeforeCursor.slice(spaceIndex+1),command=this.commands.find(cmd=>("name"in cmd?cmd.name:cmd.value)===commandName2);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,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.startsWith("$")&&(item.value.startsWith("/")||item.value.startsWith("$"))){let newLine2=`${beforePrefix}${item.value} ${adjustedAfterCursor}`,newLines2=[...lines];return newLines2[cursorLine]=newLine2,{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+item.value.length+1}}if(prefix.startsWith("/")&&!prefix.slice(1).includes("/")&&(beforePrefix.trim()===""||prefix.startsWith("/skill:")&&this.isLeadingKnownSkillCommandRun(beforePrefix))){let separator=isSlashNamespaceItem(item.value)?"":" ",newLine2=`${beforePrefix}/${item.value}${separator}${adjustedAfterCursor}`,newLines2=[...lines];return newLines2[cursorLine]=newLine2,{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+1+item.value.length+separator.length}}if(prefix.startsWith("@")){let isDirectory2=item.label.endsWith("/"),suffix=isDirectory2?"":" ",newLine2=`${beforePrefix+item.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=[...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&&hasTrailingQuote?item.value.length-1:item.value.length;return{lines:newLines,cursorLine,cursorCol:beforePrefix.length+cursorOffset}}isLeadingKnownSkillCommandRun(text){let tokens=text.trim().split(/\s+/);return tokens.length>0&&tokens.every(token=>{if(!token.startsWith("/skill:"))return!1;let commandName2=token.slice(1);return this.commands.some(command=>("name"in command?command.name:command.value)===commandName2)})}extractAtPrefix(text){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix?.startsWith('@"'))return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),tokenStart=lastDelimiterIndex===-1?0:lastDelimiterIndex+1;return text[tokenStart]==="@"?text.slice(tokenStart):null}extractPathPrefix(text,forceExtract=!1){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix)return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),pathPrefix=lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1);return forceExtract||pathPrefix.includes("/")||pathPrefix.startsWith(".")||pathPrefix.startsWith("~/")||pathPrefix===""&&text.endsWith(" ")?pathPrefix:null}expandHomePath(path4){if(path4.startsWith("~/")){let expandedPath=join2(homedir3(),path4.slice(2));return path4.endsWith("/")&&!expandedPath.endsWith("/")?`${expandedPath}/`:expandedPath}else if(path4==="~")return homedir3();return path4}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=join2(this.basePath,displayBase);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=this.expandHomePath(expandedPrefix)),rawPrefix===""||rawPrefix==="./"||rawPrefix==="../"||rawPrefix==="~"||rawPrefix==="~/"||rawPrefix==="/"||isAtPrefix&&rawPrefix==="")rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join2(this.basePath,expandedPrefix),searchPrefix="";else if(rawPrefix.endsWith("/"))rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join2(this.basePath,expandedPrefix),searchPrefix="";else{let dir=dirname2(expandedPrefix),file=basename(expandedPrefix);rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=dir:searchDir=join2(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=join2(searchDir,entry.name);isDirectory=statSync(fullPath).isDirectory()}catch{}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=dirname2(homeRelativeDir);relativePath=`~/${dir==="."?name:join2(dir,name)}`}else if(displayPrefix.startsWith("/")){let dir=dirname2(displayPrefix);dir==="/"?relativePath=`/${name}`:relativePath=`${dir}/${name}`}else relativePath=join2(dirname2(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((a,b2)=>{let aIsDir=a.value.endsWith("/"),bIsDir=b2.value.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a.label.localeCompare(b2.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){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=await this.getBaseDirSuggestions(fdBaseDir,fdQuery,options.signal),recursiveEntries=await walkDirectoryWithFd(fdBaseDir,this.fdPath,fdQuery,100,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((a,b2)=>{let scoreDiff=b2.score-a.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(a.path).split("/").filter(Boolean).length,bDepth=toDisplayPath(b2.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a.path.length-b2.path.length;return lengthDiff!==0?lengthDiff:a.path.localeCompare(b2.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.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.trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};var Text=class{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}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-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=" ".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 this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};var DEFAULT_PRIMARY_COLUMN_WIDTH=32,PRIMARY_COLUMN_GAP=2,MIN_DESCRIPTION_WIDTH=10,normalizeToSingleLine=text=>text.replace(/[\r\n]+/g," ").trim(),clamp=(value,min,max)=>Math.max(min,Math.min(value,max)),SelectList=class{constructor(items,maxVisible,theme,layout={}){this.items=[],this.filteredItems=[],this.selectedIndex=0,this.maxVisible=5,this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme,this.layout=layout}setFilter(filter){this.filteredItems=this.items.filter(item=>item.value.toLowerCase().startsWith(filter.toLowerCase())),this.selectedIndex=0}setSelectedIndex(index){this.selectedIndex=Math.max(0,Math.min(index,this.filteredItems.length-1))}invalidate(){}render(width){let lines=[];if(this.filteredItems.length===0)return lines.push(this.theme.noMatch(" No matching commands")),lines;let primaryColumnWidth=this.getPrimaryColumnWidth(),{startIndex,endIndex}=this.getVisibleRange();for(let i=startIndex;i<endIndex;i++){let item=this.filteredItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,descriptionSingleLine=item.description?normalizeToSingleLine(item.description):void 0;lines.push(this.renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth))}if(startIndex>0||endIndex<this.filteredItems.length){let scrollText=` (${this.selectedIndex+1}/${this.filteredItems.length})`;lines.push(this.theme.scrollInfo(truncateToWidth(scrollText,width-2,"")))}return lines}handleMouse(event){if(this.filteredItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+delta)),this.selectedIndex!==previousIndex&&this.notifySelectionChange(),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let{startIndex,endIndex}=this.getVisibleRange(),itemIndex=startIndex+event.y;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=itemIndex,this.selectedIndex!==itemIndex&&(this.selectedIndex=itemIndex,this.notifySelectionChange()),{handled:!0,focus:!0};if(event.type==="click"){let clickedIndex=this.mousePressedIndex??itemIndex;this.mousePressedIndex=void 0;let changed=this.selectedIndex!==clickedIndex;this.selectedIndex=clickedIndex,changed&&this.notifySelectionChange();let selectedItem=this.filteredItems[this.selectedIndex];return selectedItem&&this.onSelect?.(selectedItem),{handled:!0}}}}handleInput(keyData){let kb=getKeybindings();if(kb.matches(keyData,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.confirm")){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelect&&this.onSelect(selectedItem)}else kb.matches(keyData,"tui.select.cancel")&&this.onCancel&&this.onCancel()}getVisibleRange(){let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex,endIndex:Math.min(startIndex+this.maxVisible,this.filteredItems.length)}}renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth){let prefix=isSelected?"\u2192 ":" ",prefixWidth=visibleWidth(prefix);if(descriptionSingleLine&&width>40){let effectivePrimaryColumnWidth=Math.max(1,Math.min(primaryColumnWidth,width-prefixWidth-4)),maxPrimaryWidth=Math.max(1,effectivePrimaryColumnWidth-PRIMARY_COLUMN_GAP),truncatedValue2=this.truncatePrimary(item,isSelected,maxPrimaryWidth,effectivePrimaryColumnWidth),truncatedValueWidth=visibleWidth(truncatedValue2),spacing=" ".repeat(Math.max(1,effectivePrimaryColumnWidth-truncatedValueWidth)),descriptionStart=prefixWidth+truncatedValueWidth+spacing.length,remainingWidth=width-descriptionStart-2;if(remainingWidth>MIN_DESCRIPTION_WIDTH){let truncatedDesc=truncateToWidth(descriptionSingleLine,remainingWidth,"");return this.composeRow(prefix,truncatedValue2,spacing+truncatedDesc,isSelected)}}let maxWidth=width-prefixWidth-2,truncatedValue=this.truncatePrimary(item,isSelected,maxWidth,maxWidth);return this.composeRow(prefix,truncatedValue,void 0,isSelected)}composeRow(prefix,primary,description,isSelected){return this.theme.renderRow?this.theme.renderRow({prefix:isSelected?this.theme.selectedPrefix(prefix):prefix,primary,description,isSelected}):isSelected?this.theme.selectedText(`${prefix}${primary}${description??""}`):prefix+primary+(description!==void 0?this.theme.description(description):"")}getPrimaryColumnWidth(){let{min,max}=this.getPrimaryColumnBounds(),widestPrimary=this.filteredItems.reduce((widest,item)=>Math.max(widest,visibleWidth(this.getDisplayValue(item))+PRIMARY_COLUMN_GAP),0);return clamp(widestPrimary,min,max)}getPrimaryColumnBounds(){let rawMin=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??DEFAULT_PRIMARY_COLUMN_WIDTH,rawMax=this.layout.maxPrimaryColumnWidth??this.layout.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||item.value}notifySelectionChange(){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelectionChange&&this.onSelectionChange(selectedItem)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};function A(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=A();function U(l3){T=l3}var E={exec:()=>null};function I(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),i=e[n];return i||(i=l3(n),e[n]=i),i}}function d(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(i,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(m.caret,"$1"),t=t.replace(i,o),n},getRegex:()=>new RegExp(t,e)};return n}var we=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),m={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,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l3=>new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:I(l3=>new RegExp(`^ {0,${l3}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)),headingBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}#`)),htmlBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:</?(?:${H})(?: +|$|/?>)|<(?:script|pre|style|textarea|!--))`,"i")),blockquoteBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}>`))},ye=/^(?:[ \t]*(?:\n|$))+/,Pe=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Se=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,v=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,_e=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,K=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,le=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ue=d(le).replace(/bull/g,K).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),$e=d(le).replace(/bull/g,K).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),W=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Le=/^[^\n]+/,X=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ze=d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",X).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ee=d(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,K).getRegex(),H="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",J=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Me=d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",J).replace("tag",H).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),pe=l3=>d(W).replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",l3).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Ae=pe(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ie=pe(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ce=d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ie).getRegex(),V={blockquote:Ce,code:Pe,def:ze,fences:Se,heading:_e,hr:v,html:Me,lheading:ue,list:Ee,newline:ye,paragraph:Ae,table:E,text:Le},ie=d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Be={...V,lheading:$e,table:ie,paragraph:d(W).replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ie).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex()},De={...V,html:d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",J).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:E,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(W).replace("hr",v).replace("heading",` *#{1,6} *[^
26
26
  ]`).replace("lheading",ue).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},qe=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ve=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ce=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,He=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,_=/[\p{P}\p{S}]/u,C=/[\s\p{P}\p{S}]/u,Z=/[^\s\p{P}\p{S}]/u,Ze=d(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,C).getRegex(),Ge=/[\p{Pi}\p{Ps}"']/u,he=/(?!~)[\p{P}\p{S}]/u,Qe=/(?!~)[\s\p{P}\p{S}]/u,Ne=/(?:[^\s\p{P}\p{S}]|~)/u,je=d(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",we?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),de=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Ue=d(de,"u").replace(/punct/g,_).getRegex(),Fe=d(de,"u").replace(/punct/g,he).getRegex(),Ke=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,We=d(Ke,"u").replace(/openQuote/g,Ge).replace(/punct/g,_).getRegex(),ke="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Xe=d(ke,"gu").replace(/notPunctSpace/g,Z).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),Je=d(ke,"gu").replace(/notPunctSpace/g,Ne).replace(/punctSpace/g,Qe).replace(/punct/g,he).getRegex(),Ve="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Ye=d(Ve,"gu").replace(/notPunctSpace/g,Z).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),et=d("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Z).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),tt="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",nt=d(tt,"gu").replace(/notPunctSpace/g,Z).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),rt=d(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,_).getRegex(),st="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",it=d(st,"gu").replace(/notPunctSpace/g,Z).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),ot=d(/\\(punct)/,"gu").replace(/punct/g,_).getRegex(),at=d(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),lt=d(J).replace("(?:-->|$)","-->").getRegex(),ut=d("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",lt).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ge=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,N=d(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",ge).getRegex(),pt=d(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",N).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ct=d(/^!?\[(label)\]\[(ref)\]/).replace("label",N).replace("ref",X).getRegex(),ht=d(/^!?\[(ref)\](?:\[\])?/).replace("ref",X).getRegex(),oe=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,dt=d(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",ge).getRegex(),kt=d("reflink|nolink(?!\\()","g").replace("reflink",d(/^!?\[(label)\]\[(ref)\]/).replace("label",dt).replace("ref",oe).getRegex()).replace("nolink",d(/^!?\[(ref)\](?:\[\])?/).replace("ref",oe).getRegex()).getRegex(),ae=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Y={_backpedal:E,anyPunctuation:ot,autolink:at,blockSkip:je,br:ce,code:ve,del:E,delLDelim:E,delRDelim:E,emStrongLDelim:Ue,emStrongRDelimAst:Xe,emStrongRDelimUnd:et,escape:qe,link:pt,nolink:ht,punctuation:Ze,reflink:ct,reflinkSearch:kt,tag:ut,text:He,url:E},gt={...Y,emStrongLDelim:We,emStrongRDelimAst:Ye,emStrongRDelimUnd:nt,link:d(/^!?\[(label)\]\((.*?)\)/).replace("label",N).getRegex(),reflink:d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",N).getRegex()},F={...Y,emStrongRDelimAst:Je,emStrongLDelim:Fe,delLDelim:rt,delRDelim:it,url:d(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ae).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:d(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",ae).getRegex()},ft={...F,br:d(ce).replace("{2,}","*").getRegex(),text:d(F.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},G={normal:V,gfm:Be,pedantic:De},B={normal:Y,gfm:F,breaks:ft,pedantic:gt},mt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},fe=l3=>mt[l3];function R(l3,e){if(e){if(m.escapeTest.test(l3))return l3.replace(m.escapeReplace,fe)}else if(m.escapeTestNoEncode.test(l3))return l3.replace(m.escapeReplaceNoEncode,fe);return l3}function ee(l3){try{l3=encodeURI(l3).replace(m.percentDecode,"%")}catch{return null}return l3}function te(l3,e){let t=l3.replace(m.findPipe,(r,o,s)=>{let u=!1,a=o;for(;--a>=0&&s[a]==="\\";)u=!u;return u?"|":" |"}),n=t.split(m.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(m.slashPipe,"|");return n}function $(l3,e,t){let n=l3.length;if(n===0)return"";let i=0;for(;i<n;){let r=l3.charAt(n-i-1);if(r===e&&!t)i++;else if(r!==e&&t)i++;else break}return l3.slice(0,n-i)}function ne(l3){let e=l3.split(`
27
27
  `),t=e.length-1;for(;t>=0&&m.blankLine.test(e[t]);)t--;return e.length-t<=2?l3:e.slice(0,t+1).join(`
28
28
  `)}function D(l3){return l3.toLowerCase().toUpperCase().toLowerCase()}function me(l3,e){if(l3.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l3.length;n++)if(l3[n]==="\\")n++;else if(l3[n]===e[0])t++;else if(l3[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function xe(l3,e=0){let t=e,n="";for(let i of l3)if(i===" "){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=i,t++;return n}function be(l3,e,t,n,i){let r=e.href,o=e.title||null,s=l3[1].replace(i.other.outputLinkReplace,"$1"),u=l3[0].charAt(0)==="!";n.state.inLink=!0;let a=n.state.linkEmitted,p=n.state.inRawBlock;n.state.linkEmitted=!1;let c=n.inlineTokens(s),h=n.state.linkEmitted;if(n.state.linkEmitted=a,n.state.inLink=!1,!u){if(h){n.state.inRawBlock=p;return}n.state.linkEmitted=!0}return{type:u?"image":"link",raw:t,href:r,title:o,text:s,tokens:c}}function xt(l3,e,t){let n=l3.match(t.other.indentCodeCompensation);if(n===null)return e;let i=n[1];return e.split(`
@@ -108,7 +108,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
108
108
  `||platform!=="linux"||isMultiplexerSession(env)||env.SSH_CONNECTION?.trim()||env.SSH_CLIENT?.trim()||env.SSH_TTY?.trim())return data;let isWarp=!!(env.WARP_SESSION_ID?.trim()||env.WARP_TERMINAL_SESSION_UUID?.trim()),interopPath=env.WSL_INTEROP?.trim(),isWsl=isWarp&&interopPath!==void 0&&/^\/run\/WSL\/\d+_interop$/.test(interopPath)&&socketExists(interopPath);return isWarp&&isWsl?NATIVE_SHIFT_ENTER_SEQUENCE:data}function keyboardEnhancementEnabled(){let value=process.env.PI_TUI_KEYBOARD_PROTOCOL;return value===void 0?!0:!["0","false","no","off"].includes(value.toLowerCase())}function isDeadTerminalError(error){if(!(error instanceof Error))return!1;if("code"in error&&typeof error.code=="string")return DEAD_TERMINAL_ERROR_CODES.has(error.code);if("errno"in error&&error.errno===EIO_ERRNO)return!0;let messageErrno=ERRNO_IN_MESSAGE_PATTERN.exec(error.message);return messageErrno?DEAD_TERMINAL_ERRNOS.has(Number.parseInt(messageErrno[1],10)):!1}var STDIN_ERROR_HANDLER_GRACE_MS=250,stdinErrorSubscribers=new Set;function isTerminalDetachStdinError(err){if(err.code==="EIO")return!0;let errno=err.errno;return errno===EIO_ERRNO||errno===-EIO_ERRNO}var dispatchStdinError=err=>{if(!isTerminalDetachStdinError(err)){if(!process.stdin.listeners("error").some(listener=>listener!==dispatchStdinError))throw err;return}for(let subscriber of stdinErrorSubscribers)subscriber(err)};function subscribeToStdinErrors(subscriber){stdinErrorSubscribers.size===0&&process.stdin.on("error",dispatchStdinError),stdinErrorSubscribers.add(subscriber)}function unsubscribeFromStdinErrors(subscriber){stdinErrorSubscribers.delete(subscriber),stdinErrorSubscribers.size===0&&process.stdin.removeListener("error",dispatchStdinError)}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{constructor(options){this.wasRaw=!1,this.externalWriteObservers=new Set,this.keyboardNegotiationSettled=!1,this.cursorQueryTimedOut=!1,this.forwardingExternalWrite=!1,this._kittyProtocolActive=!1,this._modifyOtherKeysActive=!1,this.keyboardProtocolPushed=!1,this.keyboardProtocolNegotiationBuffer="",this.discardingPrivateResponse=!1,this.writeLogPath=(()=>{let env=process.env.PI_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs2.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 path3.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})(),this.onExternalStdoutWrite=options?.onExternalStdoutWrite,this.observeExternalStderrWrites=options?.observeExternalStderrWrites??observeProcessStderrWrites,this.tmuxExecFile=options?.tmuxExecFile}get kittyProtocolActive(){return this._kittyProtocolActive}queryCursorPosition(){if(this.cursorQuery)return this.cursorQuery.promise;if(!this.inputHandler||this.cursorQueryTimedOut)return Promise.resolve(void 0);let resolve,promise=new Promise(settle=>{resolve=settle}),timer=setTimeout(()=>{this.cursorQueryTimedOut=!0,this.settleCursorQuery(void 0)},750);return this.cursorQuery={promise,resolve,timer,issued:!1,tmuxPane:process.env.TMUX_PANE,deadline:Date.now()+750},this.issueCursorQuery(),promise}issueCursorQuery(){if(!this.keyboardNegotiationSettled||!this.cursorQuery||this.cursorQuery.issued)return;this.cursorQuery.issued=!0,this.rawWrite("\x1B[?6n");let pending=this.cursorQuery;pending?.tmuxPane!==void 0&&queryTmuxCursorPosition(pending.tmuxPane,pending.deadline,this.tmuxExecFile).then(position=>{this.cursorQuery===pending&&(Date.now()>=pending.deadline&&(this.cursorQueryTimedOut=!0),this.settleCursorQuery(this.cursorQueryTimedOut?void 0:position))})}settleCursorQuery(position){let pending=this.cursorQuery;pending&&(this.cursorQuery=void 0,clearTimeout(pending.timer),pending.resolve(position))}observeExternalWrites(listener){return this.externalWriteObservers.add(listener),this.inputHandler&&(this.installExternalStdoutGuard(),this.installExternalStderrObserver()),()=>{this.externalWriteObservers.delete(listener)}}noteExternalWrite(){for(let listener of this.externalWriteObservers)listener()}installExternalStderrObserver(){this.stopExternalStderrObservation||this.externalWriteObservers.size===0||(this.stopExternalStderrObservation=this.observeExternalStderrWrites(()=>this.noteExternalWrite()))}rawWrite(data){if(this.rawStdoutWrite){this.rawStdoutWrite(data);return}process.stdout.write(data)}installExternalStdoutGuard(){let handler=this.onExternalStdoutWrite;if(!handler&&this.externalWriteObservers.size===0||this.originalStdoutWrite)return;this.originalStdoutWrite=process.stdout.write;let rawWrite=process.stdout.write.bind(process.stdout);this.rawStdoutWrite=rawWrite,process.stdout.write=((chunk,encodingOrCallback,callback)=>{let cb=typeof encodingOrCallback=="function"?encodingOrCallback:callback,encoding=typeof encodingOrCallback=="string"?encodingOrCallback:void 0,text=typeof chunk=="string"?chunk:Buffer.from(chunk).toString(encoding);if(!handler||this.forwardingExternalWrite)return this.noteExternalWrite(),rawWrite(text),cb?.(null),!0;this.forwardingExternalWrite=!0;try{handler(text)}catch{this.noteExternalWrite(),rawWrite(text)}finally{this.forwardingExternalWrite=!1}return cb?.(null),!0})}removeExternalStdoutGuard(){this.originalStdoutWrite&&(process.stdout.write=this.originalStdoutWrite,this.originalStdoutWrite=void 0,this.rawStdoutWrite=void 0)}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){this.installExternalStdoutGuard(),this.installExternalStderrObserver(),this.keyboardNegotiationSettled=!keyboardEnhancementEnabled(),this.cursorQueryTimedOut=!1,this.discardingPrivateResponse=!1,this.inputHandler=onInput,this.resizeHandler=onResize,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),this.stdinErrorHandlerCleanupTimer&&(clearTimeout(this.stdinErrorHandlerCleanupTimer),this.stdinErrorHandlerCleanupTimer=void 0),this.stdinErrorHandler||(this.stdinErrorHandler=()=>{},subscribeToStdinErrors(this.stdinErrorHandler)),this.rawWrite("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs()}),this.stdinBuffer.on("data",sequence=>{if(this.discardingPrivateResponse)if(sequence.startsWith("\x1B"))this.discardingPrivateResponse=!1;else{/[\x40-\x7e]/.test(sequence)&&(this.discardingPrivateResponse=!1);return}let negotiationSequence=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)||this.forwardInputSequence(sequence)}),this.stdinBuffer.on("paste",content=>{this.inputHandler&&this.inputHandler(`\x1B[200~${content}\x1B[201~`)}),this.stdinDataHandler=data=>{this.stdinBuffer.process(data)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),keyboardEnhancementEnabled()&&((process.env.TMUX!==void 0||process.env.TMUX_PANE!==void 0)&&this.enableModifyOtherKeys(),this.keyboardProtocolPushed=!0,this.clearKeyboardProtocolNegotiationBuffer(),this.rawWrite(KITTY_KEYBOARD_PROTOCOL_QUERY))}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(!negotiationSequence)return!1;if(this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence.type==="cursor-position"){if(this.cursorQuery?.issued&&this.cursorQuery.tmuxPane===void 0){let{type:_type,...position}=negotiationSequence;this.settleCursorQuery(position)}return!0}return this.keyboardNegotiationSettled=!0,this.issueCursorQuery(),negotiationSequence.type==="kitty-flags"?(negotiationSequence.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,setKittyProtocolActive(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(sequence){if(this.keyboardProtocolNegotiationBuffer){let bufferedSequence=this.keyboardProtocolNegotiationBuffer+sequence,negotiationSequence2=parseKeyboardProtocolNegotiationSequence(bufferedSequence);if(negotiationSequence2)return this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence2;if(isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence))return this.setKeyboardProtocolNegotiationBuffer(bufferedSequence),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let negotiationSequence=parseKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence)return negotiationSequence;if(isKeyboardProtocolNegotiationSequencePrefix(sequence))return this.setKeyboardProtocolNegotiationBuffer(sequence),"pending"}setKeyboardProtocolNegotiationBuffer(sequence){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=sequence}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(discardTail=!1){if(!this.keyboardProtocolNegotiationBuffer)return;let sequence=this.keyboardProtocolNegotiationBuffer;if(this.clearKeyboardProtocolNegotiationBuffer(),/^\x1b\[\?[\d;]*$/.test(sequence)){this.discardingPrivateResponse=discardTail;return}this.forwardInputSequence(sequence)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput(!0)},KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(sequence){if(!this.inputHandler)return;let shouldDetectNativeShiftEnter=sequence==="\r"&&(isAppleTerminalSession()||process.platform==="win32"),input=normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnter,shouldDetectNativeShiftEnter&&isNativeModifierPressed("shift"));this.inputHandler(input)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(this.rawWrite("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(this.rawWrite("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{getNativePlatformHelper()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\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=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.settleCursorQuery(void 0),this.stopExternalStderrObservation?.(),this.stopExternalStderrObservation=void 0,this.clearProgressInterval()&&this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.rawWrite("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;if(this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode)try{process.stdin.setRawMode(this.wasRaw)}catch(error){if(!isDeadTerminalError(error))throw error}this.removeExternalStdoutGuard(),this.scheduleStdinErrorHandlerCleanup()}scheduleStdinErrorHandlerCleanup(){if(!this.stdinErrorHandler||this.stdinErrorHandlerCleanupTimer)return;let handler=this.stdinErrorHandler;this.stdinErrorHandlerCleanupTimer=setTimeout(()=>{this.stdinErrorHandlerCleanupTimer=void 0,this.stdinErrorHandler===handler&&(this.stdinErrorHandler=void 0,unsubscribeFromStdinErrors(handler))},STDIN_ERROR_HANDLER_GRACE_MS),this.stdinErrorHandlerCleanupTimer.unref()}write(data){if(this.rawWrite(data),this.writeLogPath)try{fs2.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?this.rawWrite(`\x1B[${lines}B`):lines<0&&this.rawWrite(`\x1B[${-lines}A`)}hideCursor(){this.rawWrite("\x1B[?25l")}showCursor(){this.rawWrite("\x1B[?25h")}clearLine(){this.rawWrite("\x1B[K")}clearFromCursor(){this.rawWrite("\x1B[J")}clearScreen(){this.rawWrite("\x1B[2J\x1B[H")}setTitle(title){let sanitizedTitle=title.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");this.rawWrite(`\x1B]0;${sanitizedTitle}\x07`)}setProgress(active){active?(this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var FAKE_CURSOR_END2="\x1B[7m \x1B[0m";function clampMentions(mentions,length){return mentions.map(range=>({start:Math.max(0,range.start),end:Math.min(length,range.end)})).filter(range=>range.start<range.end)}function cutPoints(length,mentions,cursorGlyph){let cuts=new Set([0,length]);for(let range of mentions)cuts.add(range.start),cuts.add(range.end);return cursorGlyph&&(cuts.add(cursorGlyph.start),cuts.add(cursorGlyph.end)),[...cuts].sort((left,right)=>left-right)}function renderEditorLine(input){let{text,cursor}=input,mentions=clampMentions(input.mentions,text.length),cursorInText=cursor!==void 0&&cursor.pos<text.length,cursorGlyph=cursorInText&&cursor.drawFakeCursor?{start:cursor.pos,end:cursor.pos+input.firstGrapheme(text.slice(cursor.pos)).length}:void 0,points=cutPoints(text.length,mentions,cursorGlyph),out="";for(let index=0;index<points.length-1;index++){let from=points[index]??0,to=points[index+1]??from;cursorInText&&from===cursor.pos&&(out+=cursor.marker);let segment=text.slice(from,to);cursorGlyph&&from===cursorGlyph.start?out+=`\x1B[7m${segment}\x1B[0m`:mentions.some(range=>from>=range.start&&to<=range.end)?out+=input.mentionStyle(segment):out+=segment}return cursor!==void 0&&!cursorInText&&(out+=cursor.marker,cursor.drawFakeCursor)?{text:out+FAKE_CURSOR_END2,cursorAppended:!0}:{text:out,cursorAppended:!1}}var graphemeSegmenter2=getGraphemeSegmenter(),wordSegmenter4=getWordSegmenter();function isAtomicMarker(segment){return isPasteMarker(segment)||isImageMarker(segment)}function markerKind(segment){if(isPasteMarker(segment))return"paste";if(isImageMarker(segment))return"image"}function containsMarkerPrefix(text){return text.includes("[paste #")||text.includes("[Image #")}function isPrintableAsciiText(text){for(let i=0;i<text.length;i++){let code=text.charCodeAt(i);if(code<32||code>126)return!1}return!0}function wordWrapAsciiLine(line,maxWidth){if(line.length<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],chunkStart=0;for(;chunkStart<line.length;){let chunkEnd=Math.min(line.length,chunkStart+maxWidth);if(chunkEnd<line.length){let breakAt=-1;for(let i=chunkEnd;i>chunkStart;i--){let code=line.charCodeAt(i-1);if(code===32||code===9){breakAt=i-1;break}}breakAt>chunkStart&&(chunkEnd=breakAt)}let raw=line.slice(chunkStart,chunkEnd),text=raw.trimEnd();for((text||chunks.length===0)&&chunks.push({text,startIndex:chunkStart,endIndex:chunkStart+raw.length}),chunkStart=chunkEnd;chunkStart<line.length;){let code=line.charCodeAt(chunkStart);if(code!==32&&code!==9)break;chunkStart++}}return chunks.length>0?chunks:[{text:"",startIndex:0,endIndex:0}]}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(preSegmented===void 0&&!/\s/.test(line)&&!containsMarkerPrefix(line)&&isPrintableAsciiText(line))return wordWrapAsciiLine(line,maxWidth);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(grapheme),charIndex=seg.index,isWs=!isAtomicMarker(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=-1),gWidth>maxWidth){let subChunks=wordWrapLine(grapheme,maxWidth);for(let j=0;j<subChunks.length-1;j++){let sc=subChunks[j];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&&(isAtomicMarker(next.segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=next.index,wrapOppWidth=currentWidth;else if(!isWs&&next&&!isWhitespaceChar(next.segment)){let isCjk=!isAtomicMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isAtomicMarker(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}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#","$"];function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`(?:^|[\\s])[${triggerCharacters.map(escapeCharacterClass).join("")}][^\\s]*$`)}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!=="@").map(escapeCharacterClass);return new RegExp(`(?:^|[ \\t])(?:@(?:"[^"]*|[^\\s]*)|[${escapedWithoutAt.join("")}][^\\s]*)$`)}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=`\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{constructor(tui,theme,options={}){this.state={lines:[""],cursorLine:0,cursorCol:0},this.focused=!1,this.paddingX=0,this.lastWidth=80,this.renderedVisibleLineCount=1,this.renderedAutocompleteHeight=0,this.scrollOffset=0,this.autocompleteTriggerCharacters=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS],this.autocompleteTriggerPattern=buildTriggerPattern(this.autocompleteTriggerCharacters),this.autocompleteDebouncePattern=buildDebouncePattern(this.autocompleteTriggerCharacters),this.autocompleteState=null,this.autocompletePrefix="",this.autocompleteMaxVisible=5,this.autocompleteRequestTask=Promise.resolve(),this.autocompleteStartToken=0,this.autocompleteRequestId=0,this.pasteMarkers=new PasteMarkerRegistry,this.imageMarkers=new ImageMarkerRegistry,this.pasteBuffer="",this.isInPaste=!1,this.history=[],this.historyIndex=-1,this.historyDraft=null,this.killRing=new KillRing,this.lastAction=null,this.jumpMode=null,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.undoStack=new UndoStack,this.wrappedLineCache=[],this.disableSubmit=!1,this.tui=tui,this.theme=theme,this.borderColor=theme.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0,this.terminalEnvironment=options.terminalEnvironment,this.terminalPlatform=options.terminalPlatform,this.terminalSocketExists=options.terminalSocketExists;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter4:graphemeSegmenter2,this.authorizedMarkers(text))}authorizedMarkers(text){let imageMarkers=this.imageMarkers.authorizedMarkers(text);if(imageMarkers.size===0)return this.pasteMarkers.authorizedMarkers(text);let merged=new Set(this.pasteMarkers.authorizedMarkers(text));for(let marker of imageMarkers)merged.add(marker);return merged}removePasteMarker(id){let removal=this.pasteMarkers.remove(id,this.getText());return removal.removed?(this.state.lines=removal.text.split(`
109
109
  `),!0):!1}removeImageMarker(id){let survivors=this.imageMarkers.ids(this.getText()).filter(entryId=>entryId!==id),removal=this.imageMarkers.remove(id,this.getText());return removal.removed?(this.state.lines=removal.text.split(`
110
110
  `),this.onImageMarkersChanged?.(survivors),!0):!1}removeMarkerSegment(segment){switch(markerKind(segment)){case"paste":{let id=pasteMarkerId(segment);return id!==void 0&&this.removePasteMarker(id)}case"image":{let id=imageMarkerId(segment);return id!==void 0&&this.removeImageMarker(id)}default:return!1}}notifyImageMarkersChanged(){this.onImageMarkersChanged?.(this.imageMarkers.ids(this.getText()))}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.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(){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.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(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(text,cursorPlacement="end"){let lines=text.split(`
111
- `);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.wrappedLineCache.length=0}getWrappedLine(lineIndex,contentWidth){let line=this.state.lines[lineIndex]||"",cached=this.wrappedLineCache[lineIndex];if(cached&&cached.lineRef===line&&cached.contentWidth===contentWidth)return cached;let width=isPrintableAsciiText(line)?line.length:visibleWidth(line);if(containsMarkerPrefix(line))return{width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth,[...this.segment(line,"grapheme")])};let wrapped={lineRef:line,contentWidth,width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth)};return this.wrappedLineCache[lineIndex]=wrapped,wrapped}renderTopBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2191",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderBottomBorder(width,hiddenLineCount){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)),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);this.renderedVisibleLineCount=visibleLines.length;let result=[],leftPadding=" ".repeat(paddingX),rightPadding=leftPadding;result.push(this.renderTopBorder(width,this.scrollOffset));let emitCursorMarker=this.focused,drawFakeCursor=!this.tui.getShowHardwareCursor(),mentionStyle=this.theme.mention,mentionRangesByLine=new Map,mentionRangesFor=layoutLine=>{if(!mentionStyle||!this.autocompleteProvider?.getMentionRanges)return[];let ranges=mentionRangesByLine.get(layoutLine.logicalLine);return ranges===void 0&&(ranges=this.autocompleteProvider.getMentionRanges(this.state.lines[layoutLine.logicalLine]??""),mentionRangesByLine.set(layoutLine.logicalLine,ranges)),ranges.map(range=>({start:range.start-layoutLine.startIndex,end:range.end-layoutLine.startIndex}))};for(let layoutLine of visibleLines){let lineVisibleWidth=visibleWidth(layoutLine.text),cursorInPadding=!1,cursor=layoutLine.hasCursor&&layoutLine.cursorPos!==void 0?{pos:layoutLine.cursorPos,marker:emitCursorMarker?CURSOR_MARKER:"",drawFakeCursor}:void 0,rendered=renderEditorLine({text:layoutLine.text,mentions:mentionRangesFor(layoutLine),mentionStyle:mentionStyle??(text=>text),cursor,firstGrapheme:text=>[...this.segment(text,"grapheme")][0]?.segment??""}),displayText=rendered.text;rendered.cursorAppended&&(lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>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)),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(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-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)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);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(),{handled:!0,focus:!0}}handleInput(data){data=normalizeWarpWslShiftEnterInput(data,this.terminalEnvironment,this.terminalPlatform,this.terminalSocketExists);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("\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&&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,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(kb.matches(data,"tui.select.confirm")){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,selected,this.autocompletePrefix);if(this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.autocompletePrefix.startsWith("/"))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(kb.matches(data,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(kb.matches(data,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();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.deleteCharBackward")||matchesKey(data,"shift+backspace")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")||matchesKey(data,"shift+delete")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(kb.matches(data,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();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.input.newLine")||data.charCodeAt(0)===10&&data.length>1||data==="\x1B\r"||data==="\x1B[13;2~"||data.length>1&&data.includes("\x1B")&&data.includes("\r")||data===`
111
+ `);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.wrappedLineCache.length=0}getWrappedLine(lineIndex,contentWidth){let line=this.state.lines[lineIndex]||"",cached=this.wrappedLineCache[lineIndex];if(cached&&cached.lineRef===line&&cached.contentWidth===contentWidth)return cached;let width=isPrintableAsciiText(line)?line.length:visibleWidth(line);if(containsMarkerPrefix(line))return{width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth,[...this.segment(line,"grapheme")])};let wrapped={lineRef:line,contentWidth,width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth)};return this.wrappedLineCache[lineIndex]=wrapped,wrapped}renderTopBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2191",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderBottomBorder(width,hiddenLineCount){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)),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);this.renderedVisibleLineCount=visibleLines.length;let result=[],leftPadding=" ".repeat(paddingX),rightPadding=leftPadding;result.push(this.renderTopBorder(width,this.scrollOffset));let emitCursorMarker=this.focused,drawFakeCursor=!this.tui.getShowHardwareCursor(),mentionStyle=this.theme.mention,mentionRangesByLine=new Map,mentionRangesFor=layoutLine=>{if(!mentionStyle||!this.autocompleteProvider?.getMentionRanges)return[];let ranges=mentionRangesByLine.get(layoutLine.logicalLine);return ranges===void 0&&(ranges=this.autocompleteProvider.getMentionRanges(this.state.lines[layoutLine.logicalLine]??""),mentionRangesByLine.set(layoutLine.logicalLine,ranges)),ranges.map(range=>({start:range.start-layoutLine.startIndex,end:range.end-layoutLine.startIndex}))};for(let layoutLine of visibleLines){let lineVisibleWidth=visibleWidth(layoutLine.text),cursorInPadding=!1,cursor=layoutLine.hasCursor&&layoutLine.cursorPos!==void 0?{pos:layoutLine.cursorPos,marker:emitCursorMarker?CURSOR_MARKER:"",drawFakeCursor}:void 0,rendered=renderEditorLine({text:layoutLine.text,mentions:mentionRangesFor(layoutLine),mentionStyle:mentionStyle??(text=>text),cursor,firstGrapheme:text=>[...this.segment(text,"grapheme")][0]?.segment??""}),displayText=rendered.text;rendered.cursorAppended&&(lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>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)),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(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-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)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);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(),{handled:!0,focus:!0}}handleInput(data){data=normalizeWarpWslShiftEnterInput(data,this.terminalEnvironment,this.terminalPlatform,this.terminalSocketExists);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("\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&&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){let drillsIntoNamespace=this.isSlashNamespaceSelection(selected.value);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(result.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),drillsIntoNamespace&&this.tryTriggerAutocomplete()}return}if(kb.matches(data,"tui.select.confirm")){let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){let drillsIntoNamespace=this.isSlashNamespaceSelection(selected.value);this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);if(this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),drillsIntoNamespace){this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),this.tryTriggerAutocomplete();return}if(this.autocompletePrefix.startsWith("/"))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(kb.matches(data,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(kb.matches(data,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();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.deleteCharBackward")||matchesKey(data,"shift+backspace")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")||matchesKey(data,"shift+delete")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(kb.matches(data,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();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.input.newLine")||data.charCodeAt(0)===10&&data.length>1||data==="\x1B\r"||data==="\x1B[13;2~"||data.length>1&&data.includes("\x1B")&&data.includes("\r")||data===`
112
112
  `&&data.length===1){if(this.shouldSubmitOnBackslashEnter(data,kb)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(kb.matches(data,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(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(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){let layoutLines=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return this.wrappedLineCache.length=this.state.lines.length,layoutLines.push({text:"",hasCursor:!0,cursorPos:0,logicalLine:0,startIndex:0}),layoutLines;for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",isCurrentLine=i===this.state.cursorLine,wrappedLine=this.getWrappedLine(i,contentWidth);if(wrappedLine.width<=contentWidth)isCurrentLine?layoutLines.push({text:line,hasCursor:!0,cursorPos:this.state.cursorCol,logicalLine:i,startIndex:0}):layoutLines.push({text:line,hasCursor:!1,logicalLine:i,startIndex:0});else{let chunks=wrappedLine.chunks;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=cursorPos-chunk.startIndex,adjustedCursorPos>chunk.text.length&&(adjustedCursorPos=chunk.text.length)))),hasCursorInChunk?layoutLines.push({text:chunk.text,hasCursor:!0,cursorPos:adjustedCursorPos,logicalLine:i,startIndex:chunk.startIndex}):layoutLines.push({text:chunk.text,hasCursor:!1,logicalLine:i,startIndex:chunk.startIndex})}}}return this.wrappedLineCache.length=this.state.lines.length,layoutLines}getText(){return this.state.lines.join(`
113
113
  `)}getExpandedText(){return this.pasteMarkers.expand(this.state.lines.join(`
114
114
  `))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(text){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let normalized=this.normalizeText(text),previousText=this.getText();previousText!==normalized&&this.pushUndoSnapshot(),this.pasteMarkers.prune(normalized,previousText);let previousImageOrder=this.imageMarkers.ids(previousText);this.imageMarkers.prune(normalized,previousText),this.setTextInternal(normalized);let canonicalization=this.imageMarkers.canonicalize(normalized);this.applyCanonicalizedText(canonicalization);let imageOrder=canonicalization.order;(previousImageOrder.length!==imageOrder.length||previousImageOrder.some((id,i)=>id!==imageOrder[i]))&&this.onImageMarkersChanged?.(imageOrder)}getPasteState(){return this.pasteMarkers.snapshot()}setPasteState(state){this.pasteMarkers.install(state,this.getText())}getImageMarkerState(){return this.imageMarkers.snapshot()}setImageMarkerState(state){this.imageMarkers.install(state,this.getText())}insertImageMarker(){this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing();let marker=this.imageMarkers.add();this.insertTextAtCursorInternal(marker);let canonicalization=this.imageMarkers.canonicalize(this.getText());this.applyCanonicalizedText(canonicalization);let insertionId=imageMarkerId(marker),finalId=canonicalization.order.includes(insertionId)?canonicalization.order.indexOf(insertionId)+1:insertionId;return this.onImageMarkersChanged?.(canonicalization.order),finalId}applyCanonicalizedText(canonicalization){if(canonicalization.text===this.getText())return;let oldLine=this.state.lines[this.state.cursorLine]??"",cursorCol=this.state.cursorCol,renumbered=new Map;for(let[index,id]of canonicalization.order.entries())renumbered.set(id,index+1);let delta=0;for(let match of oldLine.matchAll(IMAGE_MARKER_REGEX)){if((match.index??0)+match[0].length>cursorCol)break;let newId=renumbered.get(Number.parseInt(match[1]??"0",10));newId!==void 0&&(delta+=formatImageMarker(newId).length-match[0].length)}this.state.lines=canonicalization.text.split(`
@@ -124,4 +124,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
124
124
  `,{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)}}else{this.pushUndoSnapshot();let wasKill=this.lastAction==="kill",oldCursorCol=this.state.cursorCol;this.moveWordBackwards();let deleteFrom=this.state.cursorCol;this.setCursorCol(oldCursorCol);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.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
125
125
  `,{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);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.segment(afterCursor,"grapheme")][0];if(this.removeMarkerSegment(firstGrapheme?.segment??"")){this.onChange?.(this.getText());return}let 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)}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=[];for(let i=0;i<this.state.lines.length;i++){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.getWrappedLine(i,width).chunks;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];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.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,"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.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.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(findWordBackward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isAtomicMarker}))}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){this.exitHistoryBrowsing();let lines=text.split(`
126
126
  `);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]||"");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(`
127
- `);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.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,pasteState:this.pasteMarkers.snapshot(),imageState:this.imageMarkers.snapshot(),attachmentState:this.snapshotAttachmentState?.()})}undo(){this.exitHistoryBrowsing();let snapshot=this.undoStack.pop();snapshot&&(Object.assign(this.state,snapshot.state),this.pasteMarkers.restore(snapshot.pasteState),this.imageMarkers.restore(snapshot.imageState),snapshot.attachmentState!==void 0&&this.restoreAttachmentState?.(snapshot.attachmentState),this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()),this.notifyImageMarkersChanged())}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+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,{segment:text=>this.segment(text,"word"),isAtomicSegment:isAtomicMarker}))}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){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(),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.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||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){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.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||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,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,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&&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(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var HStack=class extends Stack{constructor(children=[],options={}){super(children,options),this.layoutType="hstack"}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.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||(result[target]=compositeTuiLine(result[target],lines[row],x2,childWidth,safeWidth))}x2+=childWidth+this.gap}return result}};var Image=class{constructor(base64Data,mimeType,theme,options={},dimensions){this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme,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(),defaultMaxHeight=Math.max(1,Math.ceil(maxWidth*cellDimensions2.widthPx/cellDimensions2.heightPx)),maxHeight=this.options.maxHeightCells??defaultMaxHeight,caps=getCapabilities(),lines;if(caps.images){caps.images==="kitty"&&this.imageId===void 0&&(this.imageId=allocateImageId());let result=renderImage(this.base64Data,this.dimensions,{maxWidthCells:maxWidth,maxHeightCells:maxHeight,imageId:this.imageId,moveCursor:!1});if(result)if(result.imageId&&(this.imageId=result.imageId),caps.images==="kitty"&&result.lines)lines=result.lines;else if(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(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}};var MouseRegion=class{constructor(child,onMouse){this.child=child,this.onMouse=onMouse}render(width){return this.child.render(width)}handleMouse(event){return dispatchMouseEvent(this.child,event)??this.onMouse(event)}invalidate(){this.child.invalidate()}};var SettingsList=class{constructor(items,maxVisible,theme,onChange,onCancel,options={}){this.selectedIndex=0,this.submenuComponent=null,this.submenuItemIndex=null,this.navigateAfterClose=null,this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme,this.onChange=onChange,this.onCancel=onCancel,this.searchEnabled=options.enableSearch??!1,this.searchEnabled&&(this.searchInput=new Input)}updateValue(id,newValue){let item=this.items.find(i=>i.id===id);item&&(item.currentValue=newValue)}selectItem(id){let index=(this.searchEnabled?this.filteredItems:this.items).findIndex(i=>i.id===id);index!==-1&&(this.selectedIndex=index)}invalidate(){this.submenuComponent?.invalidate?.()}render(width){return this.submenuComponent?this.submenuComponent.render(width):this.renderMainList(width)}renderMainList(width){let lines=[];if(this.searchEnabled&&this.searchInput&&(lines.push(...this.searchInput.render(width)),lines.push("")),this.items.length===0)return lines.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(lines,width),lines;let displayItems=this.getDisplayItems();if(displayItems.length===0)return lines.push(truncateToWidth(this.theme.hint(" No matching settings"),width)),this.addHintLine(lines,width),lines;let{startIndex,endIndex}=this.getVisibleRange(displayItems),maxLabelWidth=Math.min(36,Math.max(...this.items.map(item=>visibleWidth(item.label))));for(let i=startIndex;i<endIndex;i++){let item=displayItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,prefix=isSelected?this.theme.cursor:" ",prefixWidth=visibleWidth(prefix),labelPadded=item.label+" ".repeat(Math.max(0,maxLabelWidth-visibleWidth(item.label))),labelText=this.theme.label(labelPadded,isSelected),separator=" ",usedWidth=prefixWidth+maxLabelWidth+visibleWidth(separator),valueMaxWidth=width-usedWidth-2,valueText=this.theme.value(truncateToWidth(item.currentValue,valueMaxWidth,""),isSelected);lines.push(truncateToWidth(prefix+labelText+separator+valueText,width))}if(startIndex>0||endIndex<displayItems.length){let scrollText=` (${this.selectedIndex+1}/${displayItems.length})`;lines.push(this.theme.hint(truncateToWidth(scrollText,width-2,"")))}let selectedItem=displayItems[this.selectedIndex];if(selectedItem?.description){lines.push("");let wrappedDesc=wrapTextWithAnsi(selectedItem.description,width-4);for(let line of wrappedDesc)lines.push(this.theme.description(` ${line}`))}return this.addHintLine(lines,width),lines}handleMouse(event){if(this.submenuComponent){let result=this.submenuComponent.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(this.searchEnabled&&this.searchInput){if(event.y===0){let result=this.searchInput.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(event.y===1)return}let displayItems=this.getDisplayItems();if(displayItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(displayItems.length-1,this.selectedIndex+delta)),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let rowOffset=this.searchEnabled?2:0,{startIndex,endIndex}=this.getVisibleRange(displayItems),itemIndex=startIndex+event.y-rowOffset;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=itemIndex,this.selectedIndex=itemIndex,{handled:!0,focus:!0};if(event.type==="click")return this.selectedIndex=this.mousePressedIndex??itemIndex,this.mousePressedIndex=void 0,this.activateItem(),{handled:!0}}}handleInput(data){if(this.submenuComponent){this.submenuComponent.handleInput?.(data);return}let kb=getKeybindings(),displayItems=this.getDisplayItems();if(kb.matches(data,"tui.select.up")){if(displayItems.length===0)return;this.selectedIndex=this.selectedIndex===0?displayItems.length-1:this.selectedIndex-1}else if(kb.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?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&&(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=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 VStack=class extends Stack{constructor(children=[],options={}){super(children,options),this.layoutType="vstack"}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.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}};function calculateImageRows(imageDimensions,targetWidthCells,cellDimensions2={widthPx:9,heightPx:18}){return calculateImageCellSize(imageDimensions,targetWidthCells,void 0,cellDimensions2).rows}export{outerKittyGraphicsMode,sanitizeTerminalLabel,getCapabilities,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,x,Q,Key,isKeyRelease,matchesKey,decodeKittyPrintable,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,getGraphemeSegmenter,visibleWidth,stripTerminalSequences,wrapTextWithAnsi,truncateToWidth,sliceByColumn,Container,isViewportTUI,TUI,Input,fuzzyMatch,fuzzyMatchLower,fuzzyFilter,CombinedAutocompleteProvider,Box,Text,Loader,CancellableLoader,expandPasteMarkers,getNativeClipboard,ProcessTerminal,SelectList,Editor,Image,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,TuiAltScreen,TuiMainScreen,dist_exports};
127
+ `);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.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,pasteState:this.pasteMarkers.snapshot(),imageState:this.imageMarkers.snapshot(),attachmentState:this.snapshotAttachmentState?.()})}undo(){this.exitHistoryBrowsing();let snapshot=this.undoStack.pop();snapshot&&(Object.assign(this.state,snapshot.state),this.pasteMarkers.restore(snapshot.pasteState),this.imageMarkers.restore(snapshot.imageState),snapshot.attachmentState!==void 0&&this.restoreAttachmentState?.(snapshot.attachmentState),this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()),this.notifyImageMarkersChanged())}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+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,{segment:text=>this.segment(text,"word"),isAtomicSegment:isAtomicMarker}))}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){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(),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})}openAutocomplete(){this.tryTriggerAutocomplete()}isSlashNamespaceSelection(value){return this.autocompletePrefix.startsWith("/")&&isSlashNamespaceItem(value)}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(){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(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;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(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){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.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?"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.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=""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var HStack=class extends Stack{constructor(children=[],options={}){super(children,options),this.layoutType="hstack"}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.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||(result[target]=compositeTuiLine(result[target],lines[row],x2,childWidth,safeWidth))}x2+=childWidth+this.gap}return result}};var Image=class{constructor(base64Data,mimeType,theme,options={},dimensions){this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme,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(),defaultMaxHeight=Math.max(1,Math.ceil(maxWidth*cellDimensions2.widthPx/cellDimensions2.heightPx)),maxHeight=this.options.maxHeightCells??defaultMaxHeight,caps=getCapabilities(),lines;if(caps.images){caps.images==="kitty"&&this.imageId===void 0&&(this.imageId=allocateImageId());let result=renderImage(this.base64Data,this.dimensions,{maxWidthCells:maxWidth,maxHeightCells:maxHeight,imageId:this.imageId,moveCursor:!1});if(result)if(result.imageId&&(this.imageId=result.imageId),caps.images==="kitty"&&result.lines)lines=result.lines;else if(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(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}};var MouseRegion=class{constructor(child,onMouse){this.child=child,this.onMouse=onMouse}render(width){return this.child.render(width)}handleMouse(event){return dispatchMouseEvent(this.child,event)??this.onMouse(event)}invalidate(){this.child.invalidate()}};var SettingsList=class{constructor(items,maxVisible,theme,onChange,onCancel,options={}){this.selectedIndex=0,this.submenuComponent=null,this.submenuItemIndex=null,this.navigateAfterClose=null,this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme,this.onChange=onChange,this.onCancel=onCancel,this.searchEnabled=options.enableSearch??!1,this.searchEnabled&&(this.searchInput=new Input)}updateValue(id,newValue){let item=this.items.find(i=>i.id===id);item&&(item.currentValue=newValue)}selectItem(id){let index=(this.searchEnabled?this.filteredItems:this.items).findIndex(i=>i.id===id);index!==-1&&(this.selectedIndex=index)}invalidate(){this.submenuComponent?.invalidate?.()}render(width){return this.submenuComponent?this.submenuComponent.render(width):this.renderMainList(width)}renderMainList(width){let lines=[];if(this.searchEnabled&&this.searchInput&&(lines.push(...this.searchInput.render(width)),lines.push("")),this.items.length===0)return lines.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(lines,width),lines;let displayItems=this.getDisplayItems();if(displayItems.length===0)return lines.push(truncateToWidth(this.theme.hint(" No matching settings"),width)),this.addHintLine(lines,width),lines;let{startIndex,endIndex}=this.getVisibleRange(displayItems),maxLabelWidth=Math.min(36,Math.max(...this.items.map(item=>visibleWidth(item.label))));for(let i=startIndex;i<endIndex;i++){let item=displayItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,prefix=isSelected?this.theme.cursor:" ",prefixWidth=visibleWidth(prefix),labelPadded=item.label+" ".repeat(Math.max(0,maxLabelWidth-visibleWidth(item.label))),labelText=this.theme.label(labelPadded,isSelected),separator=" ",usedWidth=prefixWidth+maxLabelWidth+visibleWidth(separator),valueMaxWidth=width-usedWidth-2,valueText=this.theme.value(truncateToWidth(item.currentValue,valueMaxWidth,""),isSelected);lines.push(truncateToWidth(prefix+labelText+separator+valueText,width))}if(startIndex>0||endIndex<displayItems.length){let scrollText=` (${this.selectedIndex+1}/${displayItems.length})`;lines.push(this.theme.hint(truncateToWidth(scrollText,width-2,"")))}let selectedItem=displayItems[this.selectedIndex];if(selectedItem?.description){lines.push("");let wrappedDesc=wrapTextWithAnsi(selectedItem.description,width-4);for(let line of wrappedDesc)lines.push(this.theme.description(` ${line}`))}return this.addHintLine(lines,width),lines}handleMouse(event){if(this.submenuComponent){let result=this.submenuComponent.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(this.searchEnabled&&this.searchInput){if(event.y===0){let result=this.searchInput.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(event.y===1)return}let displayItems=this.getDisplayItems();if(displayItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(displayItems.length-1,this.selectedIndex+delta)),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let rowOffset=this.searchEnabled?2:0,{startIndex,endIndex}=this.getVisibleRange(displayItems),itemIndex=startIndex+event.y-rowOffset;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=itemIndex,this.selectedIndex=itemIndex,{handled:!0,focus:!0};if(event.type==="click")return this.selectedIndex=this.mousePressedIndex??itemIndex,this.mousePressedIndex=void 0,this.activateItem(),{handled:!0}}}handleInput(data){if(this.submenuComponent){this.submenuComponent.handleInput?.(data);return}let kb=getKeybindings(),displayItems=this.getDisplayItems();if(kb.matches(data,"tui.select.up")){if(displayItems.length===0)return;this.selectedIndex=this.selectedIndex===0?displayItems.length-1:this.selectedIndex-1}else if(kb.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?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&&(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=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 VStack=class extends Stack{constructor(children=[],options={}){super(children,options),this.layoutType="vstack"}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.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}};function calculateImageRows(imageDimensions,targetWidthCells,cellDimensions2={widthPx:9,heightPx:18}){return calculateImageCellSize(imageDimensions,targetWidthCells,void 0,cellDimensions2).rows}export{outerKittyGraphicsMode,sanitizeTerminalLabel,getCapabilities,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,x,Q,Key,isKeyRelease,matchesKey,decodeKittyPrintable,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,getGraphemeSegmenter,visibleWidth,stripTerminalSequences,wrapTextWithAnsi,truncateToWidth,sliceByColumn,Container,isViewportTUI,TUI,Input,fuzzyMatch,fuzzyMatchLower,fuzzyFilter,CombinedAutocompleteProvider,Box,Text,Loader,CancellableLoader,expandPasteMarkers,getNativeClipboard,ProcessTerminal,SelectList,Editor,Image,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,TuiAltScreen,TuiMainScreen,dist_exports};