@draht/coding-agent 2026.11.5-1 → 2026.11.14-1

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 (306) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/dist/bundle/chunks/anthropic-messages-C5ZJVCKX.js +6 -0
  3. package/dist/bundle/chunks/{azure-openai-responses-NCMJPZVJ.js → azure-openai-responses-TNRID5YC.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
  5. package/dist/bundle/chunks/chunk-2CHTECAU.js +2 -0
  6. package/dist/bundle/chunks/{chunk-DWOGGNWY.js → chunk-2IQVBLH6.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-P7O36UDU.js → chunk-4FPBO5KP.js} +5 -1
  8. package/dist/bundle/chunks/{chunk-Q2QKCYPU.js → chunk-5C4MAPF6.js} +1 -1
  9. package/dist/bundle/chunks/chunk-5WEOWREV.js +82 -0
  10. package/dist/bundle/chunks/{chunk-DN7SM3LX.js → chunk-ATYP3OSV.js} +3 -1
  11. package/dist/bundle/chunks/chunk-B6S2UR4T.js +2 -0
  12. package/dist/bundle/chunks/chunk-EBTEI43G.js +20 -0
  13. package/dist/bundle/chunks/{chunk-F5TDVH26.js → chunk-GAABJAG4.js} +12 -15
  14. package/dist/bundle/chunks/{chunk-PMINB7UH.js → chunk-JHKMYVPC.js} +169 -130
  15. package/dist/bundle/chunks/{chunk-EOXOMUKR.js → chunk-LCTFXH4P.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-UFACUBF2.js → chunk-MPJIXESS.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-PZKD35UB.js → chunk-MXA4WY3C.js} +1 -1
  18. package/dist/bundle/chunks/chunk-O2XYFH2E.js +30 -0
  19. package/dist/bundle/chunks/{chunk-CA23BDNK.js → chunk-OUXJRC2W.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-3BJ462DN.js → chunk-RI7HJ6AF.js} +1 -1
  21. package/dist/bundle/chunks/chunk-RVXTPNXQ.js +44 -0
  22. package/dist/bundle/chunks/{chunk-QBUTRTYN.js → chunk-SXHVGWCU.js} +1 -1
  23. package/dist/bundle/chunks/chunk-WNZ64GW3.js +2 -0
  24. package/dist/bundle/chunks/chunk-XWZLYE4L.js +9 -0
  25. package/dist/bundle/chunks/{chunk-HJ3PS7QP.js → chunk-YSE3VKKB.js} +2 -2
  26. package/dist/bundle/chunks/{cli-4SUT6MJ6.js → cli-2QKCAPPD.js} +3 -3
  27. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-BJVMNETD.js → cloudflare-workers-ai-system-one-UCG6T3XP.js} +1 -1
  28. package/dist/bundle/chunks/codemode-worker.js +2 -0
  29. package/dist/bundle/chunks/{execute-ZI7T2SUH.js → execute-KGJOWTPG.js} +2 -2
  30. package/dist/bundle/chunks/github-copilot.js +1 -1
  31. package/dist/bundle/chunks/google-generative-ai-GPBKPOXA.js +2 -0
  32. package/dist/bundle/chunks/google-vertex-USZY53NF.js +2 -0
  33. package/dist/bundle/chunks/{llama-cpp-classify-L4URPZ4F.js → llama-cpp-classify-7DEQ4ZUF.js} +1 -1
  34. package/dist/bundle/chunks/{mistral-conversations-CK2BS74V.js → mistral-conversations-UOGXPDZ3.js} +1 -1
  35. package/dist/bundle/chunks/{openai-codex-responses-XGVNKP4D.js → openai-codex-responses-VUDXQ3EU.js} +1 -1
  36. package/dist/bundle/chunks/{openai-completions-72XZO4Q3.js → openai-completions-UQOOS7NM.js} +3 -3
  37. package/dist/bundle/chunks/{openai-decisions-P5OCXLLD.js → openai-decisions-24WNXO2R.js} +1 -1
  38. package/dist/bundle/chunks/{openai-responses-RGLZ4E3Q.js → openai-responses-5AF6MZ5L.js} +1 -1
  39. package/dist/bundle/chunks/{openrouter-images-LSBWMZDK.js → openrouter-images-OUXVVTYQ.js} +1 -1
  40. package/dist/bundle/chunks/{pi-messages-CL4MEVNS.js → pi-messages-DRMOEO6B.js} +1 -1
  41. package/dist/bundle/chunks/{runtime-FJYRBK3O.js → runtime-FZKS2BWI.js} +1 -1
  42. package/dist/bundle/chunks/{runtime-F4362CZF.js → runtime-L23MZBKL.js} +1 -1
  43. package/dist/bundle/chunks/{settings-manager-T6G6KKY3.js → settings-manager-CWRQW6PZ.js} +1 -1
  44. package/dist/bundle/chunks/{typesafe-system-one-BFYS6AEA.js → typesafe-system-one-K63EBJDD.js} +1 -1
  45. package/dist/bundle/chunks/virtual-modules-JZV35VDE.js +2 -0
  46. package/dist/bundle/cli-runtime.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.d.ts.map +1 -1
  50. package/dist/cli/args.js +5 -3
  51. package/dist/cli/args.js.map +1 -1
  52. package/dist/cli/auth-command.d.ts.map +1 -1
  53. package/dist/cli/auth-command.js +30 -6
  54. package/dist/cli/auth-command.js.map +1 -1
  55. package/dist/cli/auth-login.d.ts +15 -0
  56. package/dist/cli/auth-login.d.ts.map +1 -0
  57. package/dist/cli/auth-login.js +232 -0
  58. package/dist/cli/auth-login.js.map +1 -0
  59. package/dist/cli/auth-logout.d.ts +14 -0
  60. package/dist/cli/auth-logout.d.ts.map +1 -0
  61. package/dist/cli/auth-logout.js +57 -0
  62. package/dist/cli/auth-logout.js.map +1 -0
  63. package/dist/cli/auth-terminal.d.ts +17 -0
  64. package/dist/cli/auth-terminal.d.ts.map +1 -0
  65. package/dist/cli/auth-terminal.js +63 -0
  66. package/dist/cli/auth-terminal.js.map +1 -0
  67. package/dist/core/agent-session-runtime.d.ts +5 -0
  68. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  69. package/dist/core/agent-session-runtime.js +16 -2
  70. package/dist/core/agent-session-runtime.js.map +1 -1
  71. package/dist/core/agent-session.d.ts +20 -9
  72. package/dist/core/agent-session.d.ts.map +1 -1
  73. package/dist/core/agent-session.js +71 -29
  74. package/dist/core/agent-session.js.map +1 -1
  75. package/dist/core/ai-schemas.d.ts +1 -0
  76. package/dist/core/ai-schemas.d.ts.map +1 -1
  77. package/dist/core/builtins/budgets.d.ts.map +1 -1
  78. package/dist/core/builtins/budgets.js +6 -3
  79. package/dist/core/builtins/budgets.js.map +1 -1
  80. package/dist/core/cache-warmer.d.ts +4 -37
  81. package/dist/core/cache-warmer.d.ts.map +1 -1
  82. package/dist/core/cache-warmer.js +11 -91
  83. package/dist/core/cache-warmer.js.map +1 -1
  84. package/dist/core/compaction/utils.d.ts.map +1 -1
  85. package/dist/core/compaction/utils.js +2 -1
  86. package/dist/core/compaction/utils.js.map +1 -1
  87. package/dist/core/exec.d.ts +1 -0
  88. package/dist/core/exec.d.ts.map +1 -1
  89. package/dist/core/exec.js +4 -1
  90. package/dist/core/exec.js.map +1 -1
  91. package/dist/core/export-html/ansi-to-html.d.ts +5 -0
  92. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  93. package/dist/core/export-html/ansi-to-html.js +57 -20
  94. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  95. package/dist/core/export-html/template.js +1 -1
  96. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  97. package/dist/core/export-html/tool-renderer.js +2 -3
  98. package/dist/core/export-html/tool-renderer.js.map +1 -1
  99. package/dist/core/extensions/types.d.ts +3 -2
  100. package/dist/core/extensions/types.d.ts.map +1 -1
  101. package/dist/core/extensions/types.js.map +1 -1
  102. package/dist/core/model-config.d.ts +13 -0
  103. package/dist/core/model-config.d.ts.map +1 -1
  104. package/dist/core/model-resolver.d.ts +0 -1
  105. package/dist/core/model-resolver.d.ts.map +1 -1
  106. package/dist/core/model-resolver.js +17 -24
  107. package/dist/core/model-resolver.js.map +1 -1
  108. package/dist/core/model-runtime.d.ts +5 -0
  109. package/dist/core/model-runtime.d.ts.map +1 -1
  110. package/dist/core/model-runtime.js +7 -0
  111. package/dist/core/model-runtime.js.map +1 -1
  112. package/dist/core/polyphase/render/format.d.ts +2 -0
  113. package/dist/core/polyphase/render/format.d.ts.map +1 -1
  114. package/dist/core/polyphase/render/format.js +6 -0
  115. package/dist/core/polyphase/render/format.js.map +1 -1
  116. package/dist/core/polyphase/render/run-block.d.ts +4 -0
  117. package/dist/core/polyphase/render/run-block.d.ts.map +1 -1
  118. package/dist/core/polyphase/render/run-block.js +71 -12
  119. package/dist/core/polyphase/render/run-block.js.map +1 -1
  120. package/dist/core/polyphase/render/snapshot.d.ts +1 -1
  121. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -1
  122. package/dist/core/polyphase/render/snapshot.js +22 -7
  123. package/dist/core/polyphase/render/snapshot.js.map +1 -1
  124. package/dist/core/polyphase/ui/dock.d.ts.map +1 -1
  125. package/dist/core/polyphase/ui/dock.js +34 -2
  126. package/dist/core/polyphase/ui/dock.js.map +1 -1
  127. package/dist/core/polyphase/ui/inspector.d.ts +18 -6
  128. package/dist/core/polyphase/ui/inspector.d.ts.map +1 -1
  129. package/dist/core/polyphase/ui/inspector.js +125 -44
  130. package/dist/core/polyphase/ui/inspector.js.map +1 -1
  131. package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -1
  132. package/dist/core/polyphase/ui/transcript-layout.js +5 -1
  133. package/dist/core/polyphase/ui/transcript-layout.js.map +1 -1
  134. package/dist/core/preferred-providers.d.ts +17 -0
  135. package/dist/core/preferred-providers.d.ts.map +1 -0
  136. package/dist/core/preferred-providers.js +24 -0
  137. package/dist/core/preferred-providers.js.map +1 -0
  138. package/dist/core/prompt-templates.d.ts.map +1 -1
  139. package/dist/core/prompt-templates.js +18 -2
  140. package/dist/core/prompt-templates.js.map +1 -1
  141. package/dist/core/provider-composer.d.ts.map +1 -1
  142. package/dist/core/provider-composer.js +2 -0
  143. package/dist/core/provider-composer.js.map +1 -1
  144. package/dist/core/provider-matching.d.ts +6 -0
  145. package/dist/core/provider-matching.d.ts.map +1 -0
  146. package/dist/core/provider-matching.js +8 -0
  147. package/dist/core/provider-matching.js.map +1 -0
  148. package/dist/core/radius-mcp.d.ts +13 -0
  149. package/dist/core/radius-mcp.d.ts.map +1 -0
  150. package/dist/core/radius-mcp.js +29 -0
  151. package/dist/core/radius-mcp.js.map +1 -0
  152. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  153. package/dist/core/remote-catalog-provider.js +2 -0
  154. package/dist/core/remote-catalog-provider.js.map +1 -1
  155. package/dist/core/runtime-credentials.d.ts +8 -0
  156. package/dist/core/runtime-credentials.d.ts.map +1 -1
  157. package/dist/core/runtime-credentials.js +15 -1
  158. package/dist/core/runtime-credentials.js.map +1 -1
  159. package/dist/core/session-cwd.d.ts +7 -0
  160. package/dist/core/session-cwd.d.ts.map +1 -1
  161. package/dist/core/session-cwd.js +9 -1
  162. package/dist/core/session-cwd.js.map +1 -1
  163. package/dist/core/session-manager.d.ts.map +1 -1
  164. package/dist/core/session-manager.js +45 -36
  165. package/dist/core/session-manager.js.map +1 -1
  166. package/dist/core/settings-defaults.d.ts +1 -1
  167. package/dist/core/settings-defaults.d.ts.map +1 -1
  168. package/dist/core/settings-defaults.js +1 -1
  169. package/dist/core/settings-defaults.js.map +1 -1
  170. package/dist/core/tools/bash.d.ts.map +1 -1
  171. package/dist/core/tools/bash.js +35 -5
  172. package/dist/core/tools/bash.js.map +1 -1
  173. package/dist/core/tools/edit-diff.d.ts +23 -14
  174. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  175. package/dist/core/tools/edit-diff.js +182 -41
  176. package/dist/core/tools/edit-diff.js.map +1 -1
  177. package/dist/core/tools/edit.d.ts.map +1 -1
  178. package/dist/core/tools/edit.js +8 -7
  179. package/dist/core/tools/edit.js.map +1 -1
  180. package/dist/core/tools/find.d.ts.map +1 -1
  181. package/dist/core/tools/find.js +57 -16
  182. package/dist/core/tools/find.js.map +1 -1
  183. package/dist/core/tools/grep.d.ts +4 -0
  184. package/dist/core/tools/grep.d.ts.map +1 -1
  185. package/dist/core/tools/grep.js +20 -8
  186. package/dist/core/tools/grep.js.map +1 -1
  187. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  188. package/dist/core/tools/output-accumulator.js +4 -1
  189. package/dist/core/tools/output-accumulator.js.map +1 -1
  190. package/dist/core/tools/powershell.d.ts.map +1 -1
  191. package/dist/core/tools/powershell.js +15 -2
  192. package/dist/core/tools/powershell.js.map +1 -1
  193. package/dist/core/tools/read.d.ts +13 -0
  194. package/dist/core/tools/read.d.ts.map +1 -1
  195. package/dist/core/tools/read.js +146 -35
  196. package/dist/core/tools/read.js.map +1 -1
  197. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  198. package/dist/core/tools/renderers/read.js +6 -2
  199. package/dist/core/tools/renderers/read.js.map +1 -1
  200. package/dist/core/tools/truncate.d.ts +4 -0
  201. package/dist/core/tools/truncate.d.ts.map +1 -1
  202. package/dist/core/tools/truncate.js +24 -1
  203. package/dist/core/tools/truncate.js.map +1 -1
  204. package/dist/extensions/codemode/execute.js +4 -4
  205. package/dist/extensions/codemode/execute.js.map +1 -1
  206. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  207. package/dist/extensions/codemode/tool.js +34 -12
  208. package/dist/extensions/codemode/tool.js.map +1 -1
  209. package/dist/extensions/llama/provider.d.ts +1 -1
  210. package/dist/extensions/llama/provider.js +1 -1
  211. package/dist/extensions/llama/provider.js.map +1 -1
  212. package/dist/extensions/llama/ui.d.ts.map +1 -1
  213. package/dist/extensions/llama/ui.js +15 -3
  214. package/dist/extensions/llama/ui.js.map +1 -1
  215. package/dist/extensions/mcp/cli.js +5 -8
  216. package/dist/extensions/mcp/cli.js.map +1 -1
  217. package/dist/extensions/mcp/index.d.ts.map +1 -1
  218. package/dist/extensions/mcp/index.js +2 -1
  219. package/dist/extensions/mcp/index.js.map +1 -1
  220. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  221. package/dist/extensions/mcp/runtime.js +3 -2
  222. package/dist/extensions/mcp/runtime.js.map +1 -1
  223. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  224. package/dist/extensions/tool-search/tool.js +18 -6
  225. package/dist/extensions/tool-search/tool.js.map +1 -1
  226. package/dist/main.d.ts.map +1 -1
  227. package/dist/main.js +67 -15
  228. package/dist/main.js.map +1 -1
  229. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  230. package/dist/modes/interactive/components/login-dialog.js +2 -19
  231. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  232. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  233. package/dist/modes/interactive/components/model-selector.js +14 -6
  234. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  235. package/dist/modes/interactive/components/oauth-selector.d.ts +10 -3
  236. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  237. package/dist/modes/interactive/components/oauth-selector.js +32 -5
  238. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  239. package/dist/modes/interactive/components/provider-brand.d.ts +14 -0
  240. package/dist/modes/interactive/components/provider-brand.d.ts.map +1 -0
  241. package/dist/modes/interactive/components/provider-brand.js +66 -0
  242. package/dist/modes/interactive/components/provider-brand.js.map +1 -0
  243. package/dist/modes/interactive/components/radius-login-selector.d.ts +1 -2
  244. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
  245. package/dist/modes/interactive/components/radius-login-selector.js +6 -37
  246. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
  247. package/dist/modes/interactive/components/session-selector.d.ts +6 -1
  248. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  249. package/dist/modes/interactive/components/session-selector.js +23 -5
  250. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  251. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  252. package/dist/modes/interactive/components/tool-execution.js +3 -1
  253. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  254. package/dist/modes/interactive/interactive-mode.d.ts +11 -1
  255. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  256. package/dist/modes/interactive/interactive-mode.js +133 -78
  257. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  258. package/dist/modes/interactive/session-share.js +2 -0
  259. package/dist/modes/interactive/session-share.js.map +1 -1
  260. package/dist/package-manager-cli.d.ts.map +1 -1
  261. package/dist/package-manager-cli.js +27 -4
  262. package/dist/package-manager-cli.js.map +1 -1
  263. package/dist/prompts/commands/test-audit.md +84 -0
  264. package/dist/utils/image-resize.d.ts.map +1 -1
  265. package/dist/utils/image-resize.js +3 -1
  266. package/dist/utils/image-resize.js.map +1 -1
  267. package/dist/utils/terminal-question.d.ts +8 -0
  268. package/dist/utils/terminal-question.d.ts.map +1 -0
  269. package/dist/utils/terminal-question.js +24 -0
  270. package/dist/utils/terminal-question.js.map +1 -0
  271. package/dist/utils/web-url.d.ts +12 -0
  272. package/dist/utils/web-url.d.ts.map +1 -0
  273. package/dist/utils/web-url.js +20 -0
  274. package/dist/utils/web-url.js.map +1 -0
  275. package/docs/cli.md +14 -1
  276. package/docs/extensions.md +6 -4
  277. package/docs/llama-cpp.md +5 -5
  278. package/docs/models-configuration.md +2 -1
  279. package/docs/nvidia-rtx-llama-cpp.md +5 -5
  280. package/docs/polyphase.md +13 -1
  281. package/docs/prompt-templates.md +1 -1
  282. package/docs/providers.md +4 -2
  283. package/docs/quickstart.md +1 -1
  284. package/docs/rpc-commands.md +1 -1
  285. package/docs/rpc.md +1 -1
  286. package/docs/sessions.md +7 -1
  287. package/docs/settings.md +1 -1
  288. package/docs/tui.md +1 -1
  289. package/examples/extensions/gondolin/index.ts +4 -7
  290. package/examples/extensions/subagent/index.ts +5 -1
  291. package/package.json +10 -10
  292. package/prompts/commands/test-audit.md +84 -0
  293. package/schemas/models.schema.json +5 -1
  294. package/schemas/settings.schema.json +1 -1
  295. package/dist/bundle/chunks/anthropic-messages-UJZ4SGHU.js +0 -6
  296. package/dist/bundle/chunks/chunk-AOCWORXE.js +0 -2
  297. package/dist/bundle/chunks/chunk-BK5LXGIH.js +0 -2
  298. package/dist/bundle/chunks/chunk-DQ4G4IS4.js +0 -20
  299. package/dist/bundle/chunks/chunk-SUVMF4W5.js +0 -2
  300. package/dist/bundle/chunks/chunk-VXO6B72D.js +0 -9
  301. package/dist/bundle/chunks/chunk-WXASQQBZ.js +0 -44
  302. package/dist/bundle/chunks/chunk-YD5VPPI4.js +0 -30
  303. package/dist/bundle/chunks/chunk-YWRWN7ZB.js +0 -82
  304. package/dist/bundle/chunks/google-generative-ai-N5IPPKQY.js +0 -2
  305. package/dist/bundle/chunks/google-vertex-A4BKUE4H.js +0 -2
  306. package/dist/bundle/chunks/virtual-modules-BPZIVXNK.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{source_default,typebox_exports}from"./chunk-ITKDPD4D.js";import{sanitizeBinaryOutput}from"./chunk-P7O36UDU.js";import{require_bash,require_c,require_core,require_cpp,require_csharp,require_dart,require_go,require_groovy,require_java,require_javascript,require_json,require_kotlin,require_lua,require_nix,require_perl,require_php,require_python,require_ruby,require_rust,require_scala,require_swift,require_typescript}from"./chunk-LO6CVU2L.js";import{CODEMODE_SOURCE_GRAMMAR,renderToolOutputType,renderToolSample,toCodemodeIdentifier}from"./chunk-DQ4G4IS4.js";import{SETTINGS_DEFAULTS}from"./chunk-PZKD35UB.js";import{getCustomThemesDir,getDocsPath,getThemesDir,resolvePath,shortenHomePath,stripBom}from"./chunk-6M3D4XVD.js";import{__export,__toESM}from"./chunk-HZ2UHMBT.js";var dist_exports={};__export(dist_exports,{Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,Image:()=>Image,Input:()=>Input,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,Markdown:()=>Markdown,Marked:()=>Marked,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,backgroundAnsi:()=>backgroundAnsi,calculateImageRows:()=>calculateImageRows,colorToHex:()=>colorToHex,colorToOkhsl:()=>colorToOkhsl,colorToOklch:()=>colorToOklch,colorToRgb:()=>colorToRgb,compositeTuiLine:()=>compositeTuiLine,decodeKittyPrintable:()=>decodeKittyPrintable,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,foregroundAnsi:()=>foregroundAnsi,formatProgramStatus:()=>formatProgramStatus,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getImageDimensions:()=>getImageDimensions,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getSelectPageIndex:()=>getSelectPageIndex,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,indexedColor:()=>indexedColor,isFocusable:()=>isFocusable,isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isViewportTUI:()=>isViewportTUI,matchesKey:()=>matchesKey,mixColors:()=>mixColors,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,oklchColor:()=>oklchColor,parseColor:()=>parseColor,parseKey:()=>parseKey,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,renderFakeCursor:()=>renderFakeCursor,renderImage:()=>renderImage,renderLatex:()=>renderLatex,replaceControlCharacters:()=>replaceControlCharacters,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function _getDefaults(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var _defaults=_getDefaults();function changeDefaults(newDefaults){_defaults=newDefaults}var noopTest={exec:()=>null};function edit(regex,opt=""){let source=typeof regex=="string"?regex:regex.source,obj={replace:(name,val)=>{let valSource=typeof val=="string"?val:val.source;return valSource=valSource.replace(other.caret,"$1"),source=source.replace(name,valSource),obj},getRegex:()=>new RegExp(source,opt)};return obj}var other={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ 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,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:bull=>new RegExp(`^( {0,3}${bull})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}#`),htmlBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}<(?:[a-z].*>|!--)`,"i")},newline=/^(?:[ \t]*(?:\n|$))+/,blockCode=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,fences=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,bullet=/(?:[*+-]|\d{1,9}[.)])/,lheadingCore=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,lheading=edit(lheadingCore).replace(/bull/g,bullet).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),lheadingGfm=edit(lheadingCore).replace(/bull/g,bullet).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),_paragraph=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,blockText=/^[^\n]+/,_blockLabel=/(?!\s*\])(?:\\.|[^\[\]\\])+/,def=edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",_blockLabel).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),list=edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,bullet).getRegex(),_tag="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",_comment=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,html=edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",_comment).replace("tag",_tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),paragraph=edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockquote=edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",paragraph).getRegex(),blockNormal={blockquote,code:blockCode,def,fences,heading,hr,html,lheading,list,newline,paragraph,table:noopTest,text:blockText},gfmTable=edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockGfm={...blockNormal,lheading:lheadingGfm,table:gfmTable,paragraph:edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",gfmTable).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex()},blockPedantic={...blockNormal,html:edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",_comment).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:noopTest,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:edit(_paragraph).replace("hr",hr).replace("heading",` *#{1,6} *[^
2
+ import{source_default,typebox_exports}from"./chunk-ITKDPD4D.js";import{sanitizeBinaryOutput}from"./chunk-4FPBO5KP.js";import{require_bash,require_c,require_core,require_cpp,require_csharp,require_dart,require_go,require_groovy,require_java,require_javascript,require_json,require_kotlin,require_lua,require_nix,require_perl,require_php,require_python,require_ruby,require_rust,require_scala,require_swift,require_typescript}from"./chunk-LO6CVU2L.js";import{CODEMODE_SOURCE_GRAMMAR,renderToolOutputType,renderToolSample,resolveSchemaRef,toCodemodeIdentifier}from"./chunk-EBTEI43G.js";import{SETTINGS_DEFAULTS}from"./chunk-MXA4WY3C.js";import{getCustomThemesDir,getDocsPath,getThemesDir,resolvePath,shortenHomePath,stripBom}from"./chunk-6M3D4XVD.js";import{__export,__toESM}from"./chunk-HZ2UHMBT.js";var dist_exports={};__export(dist_exports,{Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,Image:()=>Image,Input:()=>Input,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,Markdown:()=>Markdown,Marked:()=>Marked,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,backgroundAnsi:()=>backgroundAnsi,calculateImageRows:()=>calculateImageRows,colorToHex:()=>colorToHex,colorToOkhsl:()=>colorToOkhsl,colorToOklch:()=>colorToOklch,colorToRgb:()=>colorToRgb,compositeTuiLine:()=>compositeTuiLine,decodeKittyPrintable:()=>decodeKittyPrintable,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,foregroundAnsi:()=>foregroundAnsi,formatProgramStatus:()=>formatProgramStatus,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getImageDimensions:()=>getImageDimensions,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getSelectPageIndex:()=>getSelectPageIndex,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,indexedColor:()=>indexedColor,isFocusable:()=>isFocusable,isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isViewportTUI:()=>isViewportTUI,matchesKey:()=>matchesKey,mixColors:()=>mixColors,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,oklchColor:()=>oklchColor,parseColor:()=>parseColor,parseKey:()=>parseKey,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,renderFakeCursor:()=>renderFakeCursor,renderImage:()=>renderImage,renderLatex:()=>renderLatex,replaceControlCharacters:()=>replaceControlCharacters,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function _getDefaults(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var _defaults=_getDefaults();function changeDefaults(newDefaults){_defaults=newDefaults}var noopTest={exec:()=>null};function edit(regex,opt=""){let source=typeof regex=="string"?regex:regex.source,obj={replace:(name,val)=>{let valSource=typeof val=="string"?val:val.source;return valSource=valSource.replace(other.caret,"$1"),source=source.replace(name,valSource),obj},getRegex:()=>new RegExp(source,opt)};return obj}var other={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ 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,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:bull=>new RegExp(`^( {0,3}${bull})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}#`),htmlBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}<(?:[a-z].*>|!--)`,"i")},newline=/^(?:[ \t]*(?:\n|$))+/,blockCode=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,fences=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,bullet=/(?:[*+-]|\d{1,9}[.)])/,lheadingCore=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,lheading=edit(lheadingCore).replace(/bull/g,bullet).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),lheadingGfm=edit(lheadingCore).replace(/bull/g,bullet).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),_paragraph=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,blockText=/^[^\n]+/,_blockLabel=/(?!\s*\])(?:\\.|[^\[\]\\])+/,def=edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",_blockLabel).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),list=edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,bullet).getRegex(),_tag="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",_comment=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,html=edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",_comment).replace("tag",_tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),paragraph=edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockquote=edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",paragraph).getRegex(),blockNormal={blockquote,code:blockCode,def,fences,heading,hr,html,lheading,list,newline,paragraph,table:noopTest,text:blockText},gfmTable=edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockGfm={...blockNormal,lheading:lheadingGfm,table:gfmTable,paragraph:edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",gfmTable).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex()},blockPedantic={...blockNormal,html:edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",_comment).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:noopTest,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:edit(_paragraph).replace("hr",hr).replace("heading",` *#{1,6} *[^
3
3
  ]`).replace("lheading",lheading).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},escape=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,inlineCode=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br=/^( {2,}|\\)\n(?!\s*$)/,inlineText=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,_punctuation=/[\p{P}\p{S}]/u,_punctuationOrSpace=/[\s\p{P}\p{S}]/u,_notPunctuationOrSpace=/[^\s\p{P}\p{S}]/u,punctuation=edit(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,_punctuationOrSpace).getRegex(),_punctuationGfmStrongEm=/(?!~)[\p{P}\p{S}]/u,_punctuationOrSpaceGfmStrongEm=/(?!~)[\s\p{P}\p{S}]/u,_notPunctuationOrSpaceGfmStrongEm=/(?:[^\s\p{P}\p{S}]|~)/u,blockSkip=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,emStrongLDelimCore=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,emStrongLDelim=edit(emStrongLDelimCore,"u").replace(/punct/g,_punctuation).getRegex(),emStrongLDelimGfm=edit(emStrongLDelimCore,"u").replace(/punct/g,_punctuationGfmStrongEm).getRegex(),emStrongRDelimAstCore="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",emStrongRDelimAst=edit(emStrongRDelimAstCore,"gu").replace(/notPunctSpace/g,_notPunctuationOrSpace).replace(/punctSpace/g,_punctuationOrSpace).replace(/punct/g,_punctuation).getRegex(),emStrongRDelimAstGfm=edit(emStrongRDelimAstCore,"gu").replace(/notPunctSpace/g,_notPunctuationOrSpaceGfmStrongEm).replace(/punctSpace/g,_punctuationOrSpaceGfmStrongEm).replace(/punct/g,_punctuationGfmStrongEm).getRegex(),emStrongRDelimUnd=edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,_notPunctuationOrSpace).replace(/punctSpace/g,_punctuationOrSpace).replace(/punct/g,_punctuation).getRegex(),anyPunctuation=edit(/\\(punct)/,"gu").replace(/punct/g,_punctuation).getRegex(),autolink=edit(/^<(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(),_inlineComment=edit(_comment).replace("(?:-->|$)","-->").getRegex(),tag=edit("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",_inlineComment).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),_inlineLabel=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,link=edit(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",_inlineLabel).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),reflink=edit(/^!?\[(label)\]\[(ref)\]/).replace("label",_inlineLabel).replace("ref",_blockLabel).getRegex(),nolink=edit(/^!?\[(ref)\](?:\[\])?/).replace("ref",_blockLabel).getRegex(),reflinkSearch=edit("reflink|nolink(?!\\()","g").replace("reflink",reflink).replace("nolink",nolink).getRegex(),inlineNormal={_backpedal:noopTest,anyPunctuation,autolink,blockSkip,br,code:inlineCode,del:noopTest,emStrongLDelim,emStrongRDelimAst,emStrongRDelimUnd,escape,link,nolink,punctuation,reflink,reflinkSearch,tag,text:inlineText,url:noopTest},inlinePedantic={...inlineNormal,link:edit(/^!?\[(label)\]\((.*?)\)/).replace("label",_inlineLabel).getRegex(),reflink:edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",_inlineLabel).getRegex()},inlineGfm={...inlineNormal,emStrongRDelimAst:emStrongRDelimAstGfm,emStrongLDelim:emStrongLDelimGfm,url:edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},inlineBreaks={...inlineGfm,br:edit(br).replace("{2,}","*").getRegex(),text:edit(inlineGfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},block={normal:blockNormal,gfm:blockGfm,pedantic:blockPedantic},inline={normal:inlineNormal,gfm:inlineGfm,breaks:inlineBreaks,pedantic:inlinePedantic},escapeReplacements={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},getEscapeReplacement=ch=>escapeReplacements[ch];function escape2(html2,encode){if(encode){if(other.escapeTest.test(html2))return html2.replace(other.escapeReplace,getEscapeReplacement)}else if(other.escapeTestNoEncode.test(html2))return html2.replace(other.escapeReplaceNoEncode,getEscapeReplacement);return html2}function cleanUrl(href){try{href=encodeURI(href).replace(other.percentDecode,"%")}catch{return null}return href}function splitCells(tableRow,count){let row=tableRow.replace(other.findPipe,(match,offset,str2)=>{let escaped=!1,curr=offset;for(;--curr>=0&&str2[curr]==="\\";)escaped=!escaped;return escaped?"|":" |"}),cells=row.split(other.splitPipe),i=0;if(cells[0].trim()||cells.shift(),cells.length>0&&!cells.at(-1)?.trim()&&cells.pop(),count)if(cells.length>count)cells.splice(count);else for(;cells.length<count;)cells.push("");for(;i<cells.length;i++)cells[i]=cells[i].trim().replace(other.slashPipe,"|");return cells}function rtrim(str2,c2,invert){let l=str2.length;if(l===0)return"";let suffLen=0;for(;suffLen<l;){let currChar=str2.charAt(l-suffLen-1);if(currChar===c2&&!invert)suffLen++;else if(currChar!==c2&&invert)suffLen++;else break}return str2.slice(0,l-suffLen)}function findClosingBracket(str2,b){if(str2.indexOf(b[1])===-1)return-1;let level=0;for(let i=0;i<str2.length;i++)if(str2[i]==="\\")i++;else if(str2[i]===b[0])level++;else if(str2[i]===b[1]&&(level--,level<0))return i;return level>0?-2:-1}function outputLink(cap,link2,raw,lexer2,rules){let href=link2.href,title=link2.title||null,text=cap[1].replace(rules.other.outputLinkReplace,"$1");lexer2.state.inLink=!0;let token={type:cap[0].charAt(0)==="!"?"image":"link",raw,href,title,text,tokens:lexer2.inlineTokens(text)};return lexer2.state.inLink=!1,token}function indentCodeCompensation(raw,text,rules){let matchIndentToCode=raw.match(rules.other.indentCodeCompensation);if(matchIndentToCode===null)return text;let indentToCode=matchIndentToCode[1];return text.split(`
4
4
  `).map(node=>{let matchIndentInNode=node.match(rules.other.beginningSpace);if(matchIndentInNode===null)return node;let[indentInNode]=matchIndentInNode;return indentInNode.length>=indentToCode.length?node.slice(indentToCode.length):node}).join(`
5
5
  `)}var _Tokenizer=class{options;rules;lexer;constructor(options2){this.options=options2||_defaults}space(src){let cap=this.rules.block.newline.exec(src);if(cap&&cap[0].length>0)return{type:"space",raw:cap[0]}}code(src){let cap=this.rules.block.code.exec(src);if(cap){let text=cap[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:cap[0],codeBlockStyle:"indented",text:this.options.pedantic?text:rtrim(text,`
@@ -59,7 +59,7 @@ Please report this to https://github.com/markedjs/marked.`,silent){let msg="<p>A
59
59
  `:!1:modifier===MODIFIERS.alt?matchesKittySequence(data,CODEPOINTS.enter,MODIFIERS.alt)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.alt)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.alt)?!0:_kittyProtocolActive?!1:data==="\x1B\r":modifier===0?data==="\r"||!_kittyProtocolActive&&data===`
60
60
  `||data==="\x1BOM"||matchesKittySequence(data,CODEPOINTS.enter,0)||matchesKittySequence(data,CODEPOINTS.kpEnter,0):matchesKittySequence(data,CODEPOINTS.enter,modifier)||matchesKittySequence(data,CODEPOINTS.kpEnter,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.enter,modifier);case"backspace":return modifier===MODIFIERS.alt?data==="\x1B\x7F"||data==="\x1B\b"?!0:matchesKittySequence(data,CODEPOINTS.backspace,MODIFIERS.alt)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,MODIFIERS.alt):modifier===MODIFIERS.ctrl?matchesRawBackspace(data,MODIFIERS.ctrl)?!0:matchesKittySequence(data,CODEPOINTS.backspace,MODIFIERS.ctrl)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,MODIFIERS.ctrl):modifier===0?matchesRawBackspace(data,0)||matchesKittySequence(data,CODEPOINTS.backspace,0)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,0):matchesKittySequence(data,CODEPOINTS.backspace,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,modifier);case"insert":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.insert)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.insert,0):matchesLegacyModifierSequence(data,"insert",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.insert,modifier);case"delete":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.delete)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.delete,0):matchesLegacyModifierSequence(data,"delete",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.delete,modifier);case"clear":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.clear):matchesLegacyModifierSequence(data,"clear",modifier);case"home":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.home)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.home,0):matchesLegacyModifierSequence(data,"home",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.home,modifier);case"end":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.end)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.end,0):matchesLegacyModifierSequence(data,"end",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.end,modifier);case"pageup":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.pageUp)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageUp,0):matchesLegacyModifierSequence(data,"pageUp",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageUp,modifier);case"pagedown":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.pageDown)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageDown,0):matchesLegacyModifierSequence(data,"pageDown",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageDown,modifier);case"up":return modifier===MODIFIERS.alt?data==="\x1Bp"||matchesKittySequence(data,ARROW_CODEPOINTS.up,MODIFIERS.alt):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.up)||matchesKittySequence(data,ARROW_CODEPOINTS.up,0):matchesLegacyModifierSequence(data,"up",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.up,modifier);case"down":return modifier===MODIFIERS.alt?data==="\x1Bn"||matchesKittySequence(data,ARROW_CODEPOINTS.down,MODIFIERS.alt):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.down)||matchesKittySequence(data,ARROW_CODEPOINTS.down,0):matchesLegacyModifierSequence(data,"down",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.down,modifier);case"left":return modifier===MODIFIERS.alt?data==="\x1B[1;3D"||!_kittyProtocolActive&&data==="\x1BB"||data==="\x1Bb"||matchesKittySequence(data,ARROW_CODEPOINTS.left,MODIFIERS.alt):modifier===MODIFIERS.ctrl?data==="\x1B[1;5D"||matchesLegacyModifierSequence(data,"left",MODIFIERS.ctrl)||matchesKittySequence(data,ARROW_CODEPOINTS.left,MODIFIERS.ctrl):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.left)||matchesKittySequence(data,ARROW_CODEPOINTS.left,0):matchesLegacyModifierSequence(data,"left",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.left,modifier);case"right":return modifier===MODIFIERS.alt?data==="\x1B[1;3C"||!_kittyProtocolActive&&data==="\x1BF"||data==="\x1Bf"||matchesKittySequence(data,ARROW_CODEPOINTS.right,MODIFIERS.alt):modifier===MODIFIERS.ctrl?data==="\x1B[1;5C"||matchesLegacyModifierSequence(data,"right",MODIFIERS.ctrl)||matchesKittySequence(data,ARROW_CODEPOINTS.right,MODIFIERS.ctrl):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.right)||matchesKittySequence(data,ARROW_CODEPOINTS.right,0):matchesLegacyModifierSequence(data,"right",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.right,modifier);case"f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":{let functionKey=key;return modifier===0&&matchesLegacySequence(data,LEGACY_KEY_SEQUENCES[functionKey])?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS[functionKey],modifier)}}if(key.length===1&&(key>="a"&&key<="z"||isDigitKey(key)||SYMBOL_KEYS.has(key))){let codepoint=key.charCodeAt(0),rawCtrl=rawCtrlChar(key),isLetter=key>="a"&&key<="z",isDigit=isDigitKey(key);return modifier===MODIFIERS.ctrl+MODIFIERS.alt&&!_kittyProtocolActive&&rawCtrl&&data===`\x1B${rawCtrl}`||modifier===MODIFIERS.alt&&!_kittyProtocolActive&&(isLetter||isDigit||SYMBOL_KEYS.has(key))&&data===`\x1B${key}`?!0:modifier===MODIFIERS.ctrl?rawCtrl&&data===rawCtrl?!0:matchesKittySequence(data,codepoint,MODIFIERS.ctrl)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.ctrl):modifier===MODIFIERS.shift+MODIFIERS.ctrl?matchesKittySequence(data,codepoint,MODIFIERS.shift+MODIFIERS.ctrl)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.shift+MODIFIERS.ctrl):modifier===MODIFIERS.shift?isLetter&&data===key.toUpperCase()?!0:matchesKittySequence(data,codepoint,MODIFIERS.shift)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.shift):modifier!==0?matchesKittySequence(data,codepoint,modifier)||matchesPrintableModifyOtherKeys(data,codepoint,modifier):data===key||matchesKittySequence(data,codepoint,0)||matchesPrintableModifyOtherKeys(data,codepoint,0)}return!1}function formatParsedKey(codepoint,modifier,baseLayoutKey){let normalizedCodepoint=normalizeKittyFunctionalCodepoint(codepoint),identityCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizedCodepoint,modifier),isLatinLetter=identityCodepoint>=97&&identityCodepoint<=122,isDigit=identityCodepoint>=48&&identityCodepoint<=57,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(identityCodepoint)),effectiveCodepoint=isLatinLetter||isDigit||isKnownSymbol?identityCodepoint:baseLayoutKey??identityCodepoint,keyName;if(effectiveCodepoint===CODEPOINTS.escape?keyName="escape":effectiveCodepoint===CODEPOINTS.tab?keyName="tab":effectiveCodepoint===CODEPOINTS.enter||effectiveCodepoint===CODEPOINTS.kpEnter?keyName="enter":effectiveCodepoint===CODEPOINTS.space?keyName="space":effectiveCodepoint===CODEPOINTS.backspace?keyName="backspace":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.delete?keyName="delete":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.insert?keyName="insert":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.home?keyName="home":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.end?keyName="end":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.pageUp?keyName="pageUp":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.pageDown?keyName="pageDown":effectiveCodepoint<=FUNCTIONAL_CODEPOINTS.f1&&effectiveCodepoint>=FUNCTIONAL_CODEPOINTS.f12?keyName=`f${FUNCTIONAL_CODEPOINTS.f1-effectiveCodepoint+1}`:effectiveCodepoint===ARROW_CODEPOINTS.up?keyName="up":effectiveCodepoint===ARROW_CODEPOINTS.down?keyName="down":effectiveCodepoint===ARROW_CODEPOINTS.left?keyName="left":effectiveCodepoint===ARROW_CODEPOINTS.right?keyName="right":(effectiveCodepoint>=48&&effectiveCodepoint<=57||effectiveCodepoint>=97&&effectiveCodepoint<=122||SYMBOL_KEYS.has(String.fromCharCode(effectiveCodepoint)))&&(keyName=String.fromCharCode(effectiveCodepoint)),!!keyName)return formatKeyNameWithModifiers(keyName,modifier)}function parseKey(data){let kitty=parseKittySequence(data);if(kitty){let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(kitty.shiftedKey,kitty.modifier,SYMBOL_KEYS);return formatParsedKey(logicalShiftedSymbol?.codepoint??kitty.codepoint,logicalShiftedSymbol?.modifier??kitty.modifier,kitty.baseLayoutKey)}let modifyOtherKeys=parseModifyOtherKeysSequence(data);if(modifyOtherKeys){let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(modifyOtherKeys.codepoint,modifyOtherKeys.modifier,SHIFTED_SYMBOL_KEYS);return formatParsedKey(logicalShiftedSymbol?.codepoint??modifyOtherKeys.codepoint,logicalShiftedSymbol?.modifier??modifyOtherKeys.modifier)}if(_kittyProtocolActive&&(data==="\x1B\r"||data===`
61
61
  `))return"shift+enter";let legacySequenceKeyId=LEGACY_SEQUENCE_KEY_IDS[data];if(legacySequenceKeyId)return legacySequenceKeyId;if(data==="\x1B")return"escape";if(data==="")return"ctrl+\\";if(data==="")return"ctrl+]";if(data==="")return"ctrl+-";if(data==="\x1B\x1B")return"ctrl+alt+[";if(data==="\x1B")return"ctrl+alt+\\";if(data==="\x1B")return"ctrl+alt+]";if(data==="\x1B")return"ctrl+alt+-";if(data===" ")return"tab";if(data==="\r"||!_kittyProtocolActive&&data===`
62
- `||data==="\x1BOM")return"enter";if(data==="\0")return"ctrl+space";if(data===" ")return"space";if(data==="\x7F")return"backspace";if(data==="\b")return isWindowsTerminalSession()?"ctrl+backspace":"backspace";if(data==="\x1B[Z")return"shift+tab";if(!_kittyProtocolActive&&data==="\x1B\r")return"alt+enter";if(!_kittyProtocolActive&&data==="\x1B ")return"alt+space";if(data==="\x1B\x7F"||data==="\x1B\b")return"alt+backspace";if(!_kittyProtocolActive&&data==="\x1BB")return"alt+left";if(!_kittyProtocolActive&&data==="\x1BF")return"alt+right";if(!_kittyProtocolActive&&data.length===2&&data[0]==="\x1B"){let code=data.charCodeAt(1);if(code>=1&&code<=26)return`ctrl+alt+${String.fromCharCode(code+96)}`;let key=String.fromCharCode(code);if(code>=97&&code<=122||code>=48&&code<=57||SYMBOL_KEYS.has(key))return`alt+${key}`}if(data==="\x1B[A")return"up";if(data==="\x1B[B")return"down";if(data==="\x1B[C")return"right";if(data==="\x1B[D")return"left";if(data==="\x1B[H"||data==="\x1BOH")return"home";if(data==="\x1B[F"||data==="\x1BOF")return"end";if(data==="\x1B[3~")return"delete";if(data==="\x1B[5~")return"pageUp";if(data==="\x1B[6~")return"pageDown";if(data.length===1){let code=data.charCodeAt(0);if(code>=1&&code<=26)return`ctrl+${String.fromCharCode(code+96)}`;if(code>=32&&code<=126)return data}}var KITTY_CSI_U_REGEX=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,KITTY_PRINTABLE_ALLOWED_MODIFIERS=MODIFIERS.shift|LOCK_MASK;function decodeKittyPrintable(data){let match=data.match(KITTY_CSI_U_REGEX);if(!match)return;let codepoint=Number.parseInt(match[1]??"",10);if(!Number.isFinite(codepoint))return;let shiftedKey=match[2]&&match[2].length>0?Number.parseInt(match[2],10):void 0,modValue=match[4]?Number.parseInt(match[4],10):1,modifier=Number.isFinite(modValue)?modValue-1:0;if((modifier&~KITTY_PRINTABLE_ALLOWED_MODIFIERS)!==0||modifier&(MODIFIERS.alt|MODIFIERS.ctrl))return;let effectiveCodepoint=codepoint;if(modifier&MODIFIERS.shift&&typeof shiftedKey=="number"&&(effectiveCodepoint=shiftedKey),effectiveCodepoint=normalizeKittyFunctionalCodepoint(effectiveCodepoint),!(!Number.isFinite(effectiveCodepoint)||effectiveCodepoint<32)&&!(effectiveCodepoint>=KITTY_FUNCTIONAL_PUA_START&&effectiveCodepoint<=KITTY_FUNCTIONAL_PUA_END))try{return String.fromCodePoint(effectiveCodepoint)}catch{return}}function decodeModifyOtherKeysPrintable(data){let parsed=parseModifyOtherKeysSequence(data);if(!(!parsed||(parsed.modifier&~LOCK_MASK&~MODIFIERS.shift)!==0)&&!(!Number.isFinite(parsed.codepoint)||parsed.codepoint<32))try{return String.fromCodePoint(parsed.codepoint)}catch{return}}function decodePrintableKey(data){return decodeKittyPrintable(data)??decodeModifyOtherKeysPrintable(data)}function hexToRgb(hex){let normalized=hex.startsWith("#")?hex.slice(1):hex,r=parseInt(normalized.slice(0,2),16),g=parseInt(normalized.slice(2,4),16),b=parseInt(normalized.slice(4,6),16);return{r,g,b}}function parseOscHexChannel(channel){if(!/^[0-9a-f]+$/i.test(channel))return;let max=16**channel.length-1;if(!(max<=0))return Math.round(parseInt(channel,16)/max*255)}var OSC_COLOR_RESPONSE_PATTERN=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,COLOR_SCHEME_REPORT_PATTERN=/^(?:\x1b\[\?997;(1|2)n)+$/;function parseOscColorResponse(data){let match=data.match(OSC_COLOR_RESPONSE_PATTERN);return match?{target:match[1]==="10"?"foreground":match[1]==="11"?"background":Number.parseInt(match[2],10),rgb:parseOscColorValue(match[3])}:void 0}function parseOscColorValue(rawValue){let value=rawValue.trim();if(value.startsWith("#")){let hex=value.slice(1);if(/^[0-9a-f]{6}$/i.test(hex))return hexToRgb(value);if(/^[0-9a-f]{12}$/i.test(hex)){let r2=parseOscHexChannel(hex.slice(0,4)),g2=parseOscHexChannel(hex.slice(4,8)),b2=parseOscHexChannel(hex.slice(8,12));return r2!==void 0&&g2!==void 0&&b2!==void 0?{r:r2,g:g2,b:b2}:void 0}return}let rgbValue=value.replace(/^rgba?:/i,""),[red,green,blue]=rgbValue.split("/");if(red===void 0||green===void 0||blue===void 0)return;let r=parseOscHexChannel(red),g=parseOscHexChannel(green),b=parseOscHexChannel(blue);return r!==void 0&&g!==void 0&&b!==void 0?{r,g,b}:void 0}function parseTerminalColorSchemeReport(data){let match=data.match(COLOR_SCHEME_REPORT_PATTERN);if(match)return match[1]==="2"?"light":"dark"}import{execSync}from"node:child_process";import{homedir as homedir2}from"node:os";import{isAbsolute}from"node:path";import{pathToFileURL}from"node:url";var cachedCapabilities=null,capabilityOverrides={},cellDimensions={widthPx:9,heightPx:18};function getCellDimensions(){return cellDimensions}function setCellDimensions(dims){cellDimensions=dims}function probeTmuxHyperlinks(){try{return execSync("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",timeout:250,stdio:["ignore","pipe","ignore"]}).split(",").map(feature=>feature.trim()).includes("hyperlinks")}catch{return!1}}function detectCapabilitiesFromEnvironment(tmuxForwardsHyperlink){let termProgram=process.env.TERM_PROGRAM?.toLowerCase()||"",terminalEmulator=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",term=process.env.TERM?.toLowerCase()||"",colorTerm=process.env.COLORTERM?.toLowerCase()||"",hasTrueColorHint=colorTerm==="truecolor"||colorTerm==="24bit"||term.endsWith("-direct"),isWindowsConsole=process.platform==="win32";return process.env.TMUX||term.startsWith("tmux")?{images:null,trueColor:hasTrueColorHint,hyperlinks:tmuxForwardsHyperlink()}:term.startsWith("screen")?{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}:termProgram==="herdr"?{images:"kitty",trueColor:hasTrueColorHint,hyperlinks:!0}:termProgram==="rex"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="orca"&&process.env.ORCA_IMAGE_PROTOCOL==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.KITTY_WINDOW_ID||termProgram==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="ghostty"||term.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||termProgram==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||termProgram==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:termProgram==="alacritty"||term.startsWith("alacritty")||process.env.ALACRITTY_WINDOW_ID||termProgram==="vscode"||termProgram==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:terminalEmulator==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:isWindowsConsole?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}}function parseBooleanCapabilityOverride(value){return value==="1"?!0:value==="0"?!1:void 0}function detectCapabilities(tmuxForwardsHyperlink=probeTmuxHyperlinks){let hyperlinks=parseBooleanCapabilityOverride(process.env.DRAHT_HYPERLINKS),detected=detectCapabilitiesFromEnvironment(hyperlinks===void 0?tmuxForwardsHyperlink:()=>hyperlinks),imageProtocol=process.env.DRAHT_IMAGE_PROTOCOL?.toLowerCase(),images=imageProtocol==="kitty"||imageProtocol==="iterm2"?imageProtocol:imageProtocol==="none"||imageProtocol==="0"?null:void 0,trueColor=parseBooleanCapabilityOverride(process.env.DRAHT_TRUE_COLOR);return{...detected,...images!==void 0?{images}:{},...trueColor!==void 0?{trueColor}:{},...hyperlinks!==void 0?{hyperlinks}:{}}}function getCapabilities(){if(!cachedCapabilities){let hyperlinks=capabilityOverrides.hyperlinks;cachedCapabilities={...detectCapabilities(hyperlinks===void 0?void 0:()=>hyperlinks),...capabilityOverrides}}return cachedCapabilities}function getTerminalColorMode(capabilities=getCapabilities()){return capabilities.trueColor?"truecolor":"256color"}function resetCapabilitiesCache(){cachedCapabilities=null}function setCapabilityOverrides(overrides){capabilityOverrides.images===overrides.images&&capabilityOverrides.trueColor===overrides.trueColor&&capabilityOverrides.hyperlinks===overrides.hyperlinks||(capabilityOverrides={...overrides},cachedCapabilities=null)}function setCapabilities(caps){cachedCapabilities=caps}var KITTY_PREFIX="\x1B_G",ITERM2_PREFIX="\x1B]1337;File=";function isImageLine(line){return line.startsWith(KITTY_PREFIX)||line.startsWith(ITERM2_PREFIX)?!0:line.includes(KITTY_PREFIX)||line.includes(ITERM2_PREFIX)}function allocateImageId(){return Math.floor(Math.random()*4294967294)+1}function encodeKitty(base64Data,options2={}){let params=["a=T","f=100","q=2"];if(options2.moveCursor===!1&&params.push("C=1"),options2.columns&&params.push(`c=${options2.columns}`),options2.rows&&params.push(`r=${options2.rows}`),options2.imageId&&params.push(`i=${options2.imageId}`),base64Data.length<=4096)return`\x1B_G${params.join(",")};${base64Data}\x1B\\`;let chunks=[],offset=0,isFirst=!0;for(;offset<base64Data.length;){let chunk=base64Data.slice(offset,offset+4096),isLast=offset+4096>=base64Data.length;isFirst?(chunks.push(`\x1B_G${params.join(",")},m=1;${chunk}\x1B\\`),isFirst=!1):isLast?chunks.push(`\x1B_Gm=0;${chunk}\x1B\\`):chunks.push(`\x1B_Gm=1;${chunk}\x1B\\`),offset+=4096}return chunks.join("")}function deleteKittyImage(imageId){return`\x1B_Ga=d,d=I,i=${imageId},q=2\x1B\\`}function deleteAllKittyImages(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}function deleteAllKittyPlacements(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function encodeITerm2(base64Data,options2={}){let params=[`inline=${options2.inline!==!1?1:0}`,`size=${Buffer.byteLength(base64Data,"base64")}`];if(options2.width!==void 0&&params.push(`width=${options2.width}`),options2.height!==void 0&&params.push(`height=${options2.height}`),options2.name){let nameBase64=Buffer.from(options2.name).toString("base64");params.push(`name=${nameBase64}`)}return options2.preserveAspectRatio===!1&&params.push("preserveAspectRatio=0"),`\x1B]1337;File=${params.join(";")}:${base64Data}\x07`}var kittyImageMetadata=new Map,kittyTransmissionGeneration=0,maxKittyImageRows=0;function registerKittyImageMetadata(metadata){if(kittyTransmissionGeneration+=1,maxKittyImageRows=Math.max(maxKittyImageRows,metadata.rows),kittyImageMetadata.delete(metadata.imageId),kittyImageMetadata.set(metadata.imageId,{...metadata,transmissionGeneration:kittyTransmissionGeneration}),kittyImageMetadata.size>1e3){let oldestImageId=kittyImageMetadata.keys().next().value;oldestImageId!==void 0&&kittyImageMetadata.delete(oldestImageId)}}function getMaxKittyImageRows(){return maxKittyImageRows}function getRegisteredKittyImageMetadataFromControls(controls){let imageId=/(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];return imageId===void 0?void 0:kittyImageMetadata.get(Number.parseInt(imageId,10))}function getRegisteredKittyImageMetadata(line){let controls=/\x1b_G([^;]*);/.exec(line)?.[1];return controls===void 0?void 0:getRegisteredKittyImageMetadataFromControls(controls)}function getExplicitKittyImageRows(controls){let value=/(?:^|,)r=(\d+)(?:,|$)/.exec(controls)?.[1];if(value===void 0)return;let rows=Number.parseInt(value,10);return rows>0?rows:void 0}function getKittyImageRowsFromControls(controls,fallbackRows){return getExplicitKittyImageRows(controls)??fallbackRows}function getKittyImageMetadata(line){let metadata=getRegisteredKittyImageMetadata(line);if(metadata)return{imageId:metadata.imageId,columns:metadata.columns,rows:metadata.rows,widthPx:metadata.widthPx,heightPx:metadata.heightPx}}var KITTY_PLACEMENT_CONTROL_KEYS=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function getKittyImagePlacementRows(line){let controls=/\x1b_G([^;]*);/.exec(line)?.[1];if(controls===void 0)return;let explicitRows=getExplicitKittyImageRows(controls);return explicitRows!==void 0?explicitRows:getRegisteredKittyImageMetadataFromControls(controls)?.rows}function getKittyImagePlacement(line){let match=/\x1b_G([^;]*);/.exec(line);if(!match)return;let metadata=getRegisteredKittyImageMetadataFromControls(match[1]);if(!metadata)return;let commandStart=match.index,commandControls=match[1],transmissionEnd;for(;;){let terminator=line.indexOf("\x1B\\",commandStart+KITTY_PREFIX.length);if(terminator===-1)return;if(transmissionEnd=terminator+2,!/(?:^|,)m=1(?:,|$)/.test(commandControls))break;if(commandStart=transmissionEnd,!line.startsWith(KITTY_PREFIX,commandStart))return;let controlsEnd=line.indexOf(";",commandStart+KITTY_PREFIX.length);if(controlsEnd===-1)return;commandControls=line.slice(commandStart+KITTY_PREFIX.length,controlsEnd)}let sequence=`\x1B_Ga=p,q=2,${match[1].split(",").filter(control=>KITTY_PLACEMENT_CONTROL_KEYS.has(control.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:metadata.imageId,transmissionGeneration:metadata.transmissionGeneration,transmissionBytes:transmissionEnd-match.index,estimatedDecodedBytes:metadata.widthPx*metadata.heightPx*4,rows:getKittyImageRowsFromControls(match[1],metadata.rows),sequence,replacementLine:`${line.slice(0,match.index)}${sequence}${line.slice(transmissionEnd)}`}}function cropKittyImageLine(line,hiddenRows,visibleRows){let metadata=getKittyImageMetadata(line),match=/\x1b_G([^;]*);/.exec(line);if(!metadata||!match||hiddenRows<0||hiddenRows>=metadata.rows||visibleRows<=0)return line;let croppedRows=Math.min(visibleRows,metadata.rows-hiddenRows);if(hiddenRows===0&&croppedRows===metadata.rows)return line;let sourceY=Math.floor(metadata.heightPx*hiddenRows/metadata.rows),sourceEnd=Math.ceil(metadata.heightPx*(hiddenRows+croppedRows)/metadata.rows),sourceHeight=Math.max(1,Math.min(metadata.heightPx,sourceEnd)-sourceY),controls=match[1].split(",").filter(control=>!/^[yhr]=/.test(control));return controls.push(`y=${sourceY}`,`h=${sourceHeight}`,`r=${croppedRows}`),`${line.slice(0,match.index)}\x1B_G${controls.join(",")};${line.slice(match.index+match[0].length)}`}function chooseLessDistortedCellCount(upperCount,idealCount){if(upperCount<=1)return upperCount;let lowerCount=upperCount-1,upperDistortion=Math.max(upperCount/idealCount,idealCount/upperCount);return Math.max(lowerCount/idealCount,idealCount/lowerCount)<upperDistortion?lowerCount:upperCount}function calculateImageCellSize(imageDimensions,maxWidthCells,maxHeightCells,cellDimensions2={widthPx:9,heightPx:18},optimizeAspectRatio=!1){let maxWidth=Math.max(1,Math.floor(maxWidthCells)),maxHeight=maxHeightCells===void 0?void 0:Math.max(1,Math.floor(maxHeightCells)),imageWidth=Math.max(1,imageDimensions.widthPx),imageHeight=Math.max(1,imageDimensions.heightPx),widthScale=maxWidth*cellDimensions2.widthPx/imageWidth,heightScale=maxHeight===void 0?widthScale:maxHeight*cellDimensions2.heightPx/imageHeight,scale=Math.min(widthScale,heightScale),scaledWidthPx=imageWidth*scale,scaledHeightPx=imageHeight*scale,columns=Math.max(1,Math.min(maxWidth,Math.ceil(scaledWidthPx/cellDimensions2.widthPx))),heightRows=scaledHeightPx/cellDimensions2.heightPx,rows=Math.max(1,Math.ceil(heightRows));if(maxHeight!==void 0&&(rows=Math.min(maxHeight,rows)),!optimizeAspectRatio)return{columns,rows};if(widthScale<=heightScale){let idealRows=columns*cellDimensions2.widthPx*imageHeight/(imageWidth*cellDimensions2.heightPx);rows=chooseLessDistortedCellCount(rows,idealRows)}else{let idealColumns=rows*cellDimensions2.heightPx*imageWidth/(imageHeight*cellDimensions2.widthPx);columns=chooseLessDistortedCellCount(columns,idealColumns)}return{columns,rows}}function calculateImageRows(imageDimensions,targetWidthCells,cellDimensions2={widthPx:9,heightPx:18}){return calculateImageCellSize(imageDimensions,targetWidthCells,void 0,cellDimensions2).rows}function getPngDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<24||buffer[0]!==137||buffer[1]!==80||buffer[2]!==78||buffer[3]!==71)return null;let width=buffer.readUInt32BE(16),height=buffer.readUInt32BE(20);return{widthPx:width,heightPx:height}}catch{return null}}function getJpegDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<2||buffer[0]!==255||buffer[1]!==216)return null;let offset=2;for(;offset<buffer.length-9;){if(buffer[offset]!==255){offset++;continue}let marker=buffer[offset+1];if(marker>=192&&marker<=194){let height=buffer.readUInt16BE(offset+5);return{widthPx:buffer.readUInt16BE(offset+7),heightPx:height}}if(offset+3>=buffer.length)return null;let length=buffer.readUInt16BE(offset+2);if(length<2)return null;offset+=2+length}return null}catch{return null}}function getGifDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<10)return null;let sig=buffer.slice(0,6).toString("ascii");if(sig!=="GIF87a"&&sig!=="GIF89a")return null;let width=buffer.readUInt16LE(6),height=buffer.readUInt16LE(8);return{widthPx:width,heightPx:height}}catch{return null}}function getWebpDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<30)return null;let riff=buffer.slice(0,4).toString("ascii"),webp=buffer.slice(8,12).toString("ascii");if(riff!=="RIFF"||webp!=="WEBP")return null;let chunk=buffer.slice(12,16).toString("ascii");if(chunk==="VP8 "){if(buffer.length<30)return null;let width=buffer.readUInt16LE(26)&16383,height=buffer.readUInt16LE(28)&16383;return{widthPx:width,heightPx:height}}else if(chunk==="VP8L"){if(buffer.length<25)return null;let bits=buffer.readUInt32LE(21),width=(bits&16383)+1,height=(bits>>14&16383)+1;return{widthPx:width,heightPx:height}}else if(chunk==="VP8X"){if(buffer.length<30)return null;let width=(buffer[24]|buffer[25]<<8|buffer[26]<<16)+1,height=(buffer[27]|buffer[28]<<8|buffer[29]<<16)+1;return{widthPx:width,heightPx:height}}return null}catch{return null}}function getImageDimensions(base64Data,mimeType){return mimeType==="image/png"?getPngDimensions(base64Data):mimeType==="image/jpeg"?getJpegDimensions(base64Data):mimeType==="image/gif"?getGifDimensions(base64Data):mimeType==="image/webp"?getWebpDimensions(base64Data):null}function renderImage(base64Data,imageDimensions,options2={}){let caps=getCapabilities();if(!caps.images)return null;let maxWidth=options2.maxWidthCells??80,size=calculateImageCellSize(imageDimensions,maxWidth,options2.maxHeightCells,getCellDimensions(),caps.images==="kitty");return caps.images==="kitty"?(options2.imageId!==void 0&&registerKittyImageMetadata({imageId:options2.imageId,columns:size.columns,rows:size.rows,widthPx:imageDimensions.widthPx,heightPx:imageDimensions.heightPx}),{sequence:encodeKitty(base64Data,{columns:size.columns,rows:size.rows,imageId:options2.imageId,moveCursor:options2.moveCursor}),columns:size.columns,rows:size.rows,imageId:options2.imageId}):caps.images==="iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options2.preserveAspectRatio??!0}),columns:size.columns,rows:size.rows}:null}function hyperlink(text,url){return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`}function shortenImagePath(filename){let home=homedir2();return home&&(filename===home||filename.startsWith(`${home}/`)||filename.startsWith(`${home}\\`))?`~${filename.slice(home.length)}`:filename}function imageFallback(mimeType,dimensions,filename){let parts=[];if(filename){let display=shortenImagePath(filename);getCapabilities().hyperlinks&&isAbsolute(filename)?parts.push(hyperlink(display,pathToFileURL(filename).href)):parts.push(display)}return parts.push(`[${mimeType}]`),dimensions&&parts.push(`${dimensions.widthPx}x${dimensions.heightPx}`),`[Image: ${parts.join(" ")}]`}function dispatchMouseEvent(component,event){let result=component.handleMouse?.(event);if(result){if("target"in result){let forwarded=result;return forwarded.focus&&component.handleInput?{...forwarded,focusTarget:component}:forwarded}if(!(!result.handled&&!result.capture&&!result.focus))return{...result,handled:!0,...result.focus?{focusTarget:component}:{},target:{component,originX:event.screenX-event.x,originY:event.screenY-event.y,width:event.width,height:event.height}}}}function retargetMouseEvent(event,target){return{...event,x:event.screenX-target.originX,y:event.screenY-target.originY,width:target.width,height:target.height}}var TERMINAL_PALETTE_SIZE=16,TERMINAL_COLOR_REPLY_COUNT=2+TERMINAL_PALETTE_SIZE,TERMINAL_COLOR_QUERY=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:TERMINAL_PALETTE_SIZE},(_,index)=>`\x1B]4;${index};?\x07`).join("")}\x1B[c`,DEVICE_ATTRIBUTES_RESPONSE_PATTERN=/^\x1b\[\?[\d;]*c$/;function isFocusable(component){return component!==null&&"focused"in component}var CURSOR_MARKER="\x1B_pi:c\x07",FAKE_CURSOR_START="\x1B_pi:fc\x07",FAKE_CURSOR_END="\x1B_pi:/fc\x07",FOCUSED_FAKE_CURSOR=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function renderFakeCursor(text){return`${FAKE_CURSOR_START}${text}${FAKE_CURSOR_END}`}function parseSizeValue(value,referenceSize){if(value===void 0)return;if(typeof value=="number")return value;let match=value.match(/^(\d+(?:\.\d+)?)%$/);if(match)return Math.floor(referenceSize*parseFloat(match[1])/100)}var Container=class{children=[];mouseLayout;addChild(component){this.children.push(component)}removeChild(component){let index=this.children.indexOf(component);index!==-1&&this.children.splice(index,1)}clear(){this.children=[]}invalidate(){for(let child of this.children)child.invalidate?.()}handleMouse(event){if(event.y<0||event.y>=event.height)return;let mouseChildren=this.mouseLayout?.width===event.width?this.mouseLayout.children:this.children.map(component=>({component,height:component.render(event.width).length})),childY=0;for(let{component:child,height:childHeight}of mouseChildren){if(event.y>=childY&&event.y<childY+childHeight){let result=dispatchMouseEvent(child,{...event,y:event.y-childY,height:childHeight});return result?.focus&&this.handleInput?{...result,focusTarget:this}:result}childY+=childHeight}}render(width){let lines=[],mouseChildren=[];for(let child of this.children){let childLines=child.render(width);mouseChildren.push({component:child,height:childLines.length});for(let line of childLines)lines.push(line)}return this.mouseLayout={width,children:mouseChildren},lines}},SEGMENT_RESET="\x1B[0m\x1B]8;;\x07";function compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth){if(isImageLine(baseLine))return baseLine;let afterStart=startCol+overlayWidth,base=extractSegments(baseLine,startCol,afterStart,totalWidth-afterStart,!0),overlay=sliceWithWidth(overlayLine,0,overlayWidth,!0),beforePad=Math.max(0,startCol-base.beforeWidth),overlayPad=Math.max(0,overlayWidth-overlay.width),actualBeforeWidth=Math.max(startCol,base.beforeWidth),actualOverlayWidth=Math.max(overlayWidth,overlay.width),afterTarget=Math.max(0,totalWidth-actualBeforeWidth-actualOverlayWidth),afterPad=Math.max(0,afterTarget-base.afterWidth),result=base.before+" ".repeat(beforePad)+SEGMENT_RESET+overlay.text+" ".repeat(overlayPad)+SEGMENT_RESET+base.after+" ".repeat(afterPad);return visibleWidth(result)<=totalWidth?result:sliceByColumn(result,0,totalWidth,!0)}var VIEWPORT_TUI=Symbol.for("@draht/tui/viewport");function isViewportTUI(tui){return tui[VIEWPORT_TUI]===!0}var TuiBase=class _TuiBase extends Container{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(terminal,showHardwareCursor,logDirectory){super(),this.terminal=terminal,this.logDirectory=logDirectory,showHardwareCursor!==void 0&&(this.showHardwareCursor=showHardwareCursor)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(_options){}afterTerminalStop(_options){}getExitRestorePrefix(){return`${this.terminalColorSchemeNotificationsEnabled?"\x1B[?2031l":""}\x1B[?25h`}getExitRestoreSuffix(){return""}exitRestoreHandler=()=>{if(!this.stopped)try{this.terminal.restoreOnExit?.(this.getExitRestorePrefix(),this.getExitRestoreSuffix())}catch{}};get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(enabled){this.showHardwareCursor!==enabled&&(this.showHardwareCursor=enabled,enabled||this.hideTerminalCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(enabled){this.clearOnShrink=enabled}getFocusedComponent(){return this.focusedComponent}setFocus(component){this.setFocusInternal({component,overlayFocusRestore:"clear"})}setFocusInternal({component,overlayFocusRestore}){let previousFocus=this.focusedComponent,nextFocus=component,previousFocusedOverlay=previousFocus?this.overlayStack.find(entry=>entry.component===previousFocus&&this.isOverlayVisible(entry)):void 0,nextFocusIsOverlay=nextFocus?this.overlayStack.some(entry=>entry.component===nextFocus):!1,restoreState=this.getVisibleOverlayFocusRestore();nextFocus&&!nextFocusIsOverlay?restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?restoreState.resume.status==="focus-target"||!this.isComponentMounted(restoreState.blockedBy)?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):this.overlayFocusRestore={status:"blocked",overlay:restoreState.overlay,blockedBy:nextFocus,resume:restoreState.resume}:previousFocusedOverlay&&restoreState.status!=="inactive"&&restoreState.overlay===previousFocusedOverlay&&!this.isOverlayFocusAncestor(previousFocusedOverlay,nextFocus)&&(this.overlayFocusRestore={status:"blocked",overlay:previousFocusedOverlay,blockedBy:nextFocus,resume:{status:"restore-overlay"}}):nextFocus===null&&(restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):overlayFocusRestore==="clear"&&this.clearOverlayFocusRestore()),isFocusable(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=nextFocus,isFocusable(nextFocus)&&(nextFocus.focused=!0);let focusedOverlay=nextFocus?this.overlayStack.find(entry=>entry.component===nextFocus&&this.isOverlayVisible(entry)):void 0;focusedOverlay&&(this.overlayFocusRestore={status:"eligible",overlay:focusedOverlay})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"}}clearOverlayFocusRestoreFor(overlay){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===overlay&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(restoreState){return restoreState.resume.status==="restore-overlay"?restoreState.overlay.component:(this.clearOverlayFocusRestore(),restoreState.resume.target)}getVisibleOverlayFocusRestore(){let restoreState=this.overlayFocusRestore;return restoreState.status==="inactive"?restoreState:!this.overlayStack.includes(restoreState.overlay)||!this.isOverlayVisible(restoreState.overlay)?{status:"inactive"}:restoreState}isOverlayFocusAncestor(entry,component){let visited=new Set,current=entry.preFocus;for(;current&&!visited.has(current);){if(visited.add(current),current===component)return!0;current=this.overlayStack.find(overlay=>overlay.component===current)?.preFocus??null}return!1}retargetOverlayPreFocus(removed){for(let overlay of this.overlayStack)overlay!==removed&&overlay.preFocus===removed.component&&(overlay.preFocus=removed.preFocus)}getMountedRoots(){return this.children}isComponentMounted(component){return this.getMountedRoots().some(child=>this.containsComponent(child,component))}containsComponent(root,target){return root===target?!0:root instanceof Container?root.children.some(child=>this.containsComponent(child,target)):!1}showOverlay(component,options2){let entry={component,...options2===void 0?{}:{options:options2},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(entry),!options2?.nonCapturing&&this.isOverlayVisible(entry)&&this.setFocus(component),this.hideTerminalCursor(),this.requestRender(),{hide:()=>{let index=this.overlayStack.indexOf(entry);if(index!==-1){if(this.clearOverlayFocusRestoreFor(entry),this.retargetOverlayPreFocus(entry),this.overlayStack.splice(index,1),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}},setHidden:hidden=>{if(entry.hidden!==hidden){if(entry.hidden=hidden,hidden){if(this.clearOverlayFocusRestoreFor(entry),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}}else!options2?.nonCapturing&&this.isOverlayVisible(entry)&&(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component));this.requestRender()}},isHidden:()=>entry.hidden,focus:()=>{!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component),this.requestRender())},unfocus:unfocusOptions=>{let isFocused=this.focusedComponent===component,restoreState=this.overlayFocusRestore,hasPendingRestore=restoreState.status!=="inactive"&&restoreState.overlay===entry;if(!(!isFocused&&!hasPendingRestore)){if(restoreState.status==="blocked"&&restoreState.overlay===entry&&this.focusedComponent===restoreState.blockedBy){unfocusOptions?this.overlayFocusRestore={status:"blocked",overlay:entry,blockedBy:restoreState.blockedBy,resume:{status:"focus-target",target:unfocusOptions.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(entry),isFocused||unfocusOptions){let topVisible=this.getTopmostVisibleOverlay(),fallbackTarget=topVisible&&topVisible!==entry?topVisible.component:entry.preFocus;this.setFocus(unfocusOptions?unfocusOptions.target:fallbackTarget)}this.requestRender()}},isFocused:()=>this.focusedComponent===component,getBounds:()=>{if(!(!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||!entry.bounds))return{...entry.bounds}}}}hideOverlay(){let overlay=this.overlayStack[this.overlayStack.length-1];if(overlay){if(this.clearOverlayFocusRestoreFor(overlay),this.retargetOverlayPreFocus(overlay),this.overlayStack.pop(),this.focusedComponent===overlay.component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??overlay.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor()}hasOverlay(){return this.overlayStack.some(o=>this.isOverlayVisible(o))}isOverlayFocused(){return this.overlayStack.some(entry=>entry.component===this.focusedComponent&&this.isOverlayVisible(entry))}resolveMouseFocusTarget(component){for(let index=this.overlayStack.length-1;index>=0;index--){let overlay=this.overlayStack[index];if(this.isOverlayVisible(overlay)&&this.containsComponent(overlay.component,component))return overlay.component}return component}dispatchMouseToOverlay(event){for(let index=this.renderedOverlayLayouts.length-1;index>=0;index--){let layout=this.renderedOverlayLayouts[index];if(event.screenX<layout.col||event.screenX>=layout.col+layout.width||event.screenY<layout.row||event.screenY>=layout.row+layout.height)continue;let result=dispatchMouseEvent(layout.entry.component,{...event,x:event.screenX-layout.col,y:event.screenY-layout.row,width:layout.width,height:layout.height});return result?{hit:!0,result:result.focus?{...result,focusTarget:layout.entry.component}:result}:{hit:!0}}return{hit:!1}}isOverlayVisible(entry){return entry.hidden?!1:entry.options?.visible?entry.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let topmost;for(let overlay of this.overlayStack)overlay.options?.nonCapturing||!this.isOverlayVisible(overlay)||(!topmost||overlay.focusOrder>topmost.focusOrder)&&(topmost=overlay);return topmost}invalidate(){for(let root of this.getMountedRoots())root.invalidate();for(let overlay of this.overlayStack)overlay.component.invalidate()}start(){this.stopped=!1,process.off("exit",this.exitRestoreHandler),process.on("exit",this.exitRestoreHandler),this.beforeTerminalStart(),this.terminal.start(data=>this.handleTerminalInput(data),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.requestRender()}addInputListener(listener){return this.inputListeners.add(listener),()=>{this.inputListeners.delete(listener)}}removeInputListener(listener){this.inputListeners.delete(listener)}onTerminalColorSchemeChange(listener){return this.terminalColorSchemeListeners.add(listener),()=>{this.terminalColorSchemeListeners.delete(listener)}}setTerminalColorSchemeNotifications(enabled){this.terminalColorSchemeNotificationsEnabled!==enabled&&(this.terminalColorSchemeNotificationsEnabled=enabled,this.stopped||this.terminal.write(enabled?"\x1B[?2031h":"\x1B[?2031l"))}queryCellSize(){getCapabilities().images&&this.terminal.write("\x1B[16t")}stop(options2={}){this.stopped=!0,process.off("exit",this.exitRestoreHandler),this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(options2),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(options2)}renderNow(force=!1){force&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.lastRenderAt=performance2.now(),this.doRender()}requestRender(force=!1){if(force){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=!0,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=!0,process.nextTick(()=>{this.immediateRenderScheduled=!1,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),this.renderRequested=!1,this.lastRenderAt=performance2.now(),this.doRender())}))}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let elapsed=performance2.now()-this.lastRenderAt,delay=Math.max(0,_TuiBase.MIN_RENDER_INTERVAL_MS-elapsed);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=performance2.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},delay)}handleTerminalInput(data){if(this.consumeTerminalColorResponse(data)||this.consumeTerminalColorSchemeReport(data))return;if(this.inputListeners.size>0){let current=data;for(let listener of this.inputListeners){let result=listener(current);if(result?.consume)return;result?.data!==void 0&&(current=result.data)}if(current.length===0)return;data=current}if(this.consumeCellSizeResponse(data))return;if(matchesKey(data,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let focusedOverlay=this.overlayStack.find(o=>o.component===this.focusedComponent);if(focusedOverlay&&!this.isOverlayVisible(focusedOverlay)){let topVisible=this.getTopmostVisibleOverlay();topVisible?this.setFocus(topVisible.component):this.setFocusInternal({component:focusedOverlay.preFocus,overlayFocusRestore:"preserve"})}if(!this.overlayStack.some(o=>o.component===this.focusedComponent)){let restoreState=this.getVisibleOverlayFocusRestore();restoreState.status==="eligible"?this.setFocus(restoreState.overlay.component):restoreState.status==="blocked"&&restoreState.blockedBy!==this.focusedComponent&&(restoreState.resume.status==="restore-overlay"?this.setFocus(restoreState.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(restoreState.resume.target)))}if(this.focusedComponent?.handleInput){if(isKeyRelease(data)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(data),this.requestImmediateRender()}}consumeTerminalColorResponse(data){let query=this.pendingTerminalColorQueries[0];if(!query)return!1;if(DEVICE_ATTRIBUTES_RESPONSE_PATTERN.test(data))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(query),!0;let response=parseOscColorResponse(data);if(!response)return!1;let{target,rgb}=response,key=String(target);return!query.deliver||query.replied.has(key)||(query.replied.add(key),target==="foreground"?query.foreground=rgb:target==="background"?query.background=rgb:target<TERMINAL_PALETTE_SIZE&&(query.palette[target]=rgb),query.replied.size===TERMINAL_COLOR_REPLY_COUNT&&this.completeTerminalColorQuery(query)),!0}terminalColorQueryResult(query){let palette=query.palette.every(color=>color!==void 0)?query.palette:void 0;return{foreground:query.foreground,background:query.background,palette}}completeTerminalColorQuery(query){let deliver=query.deliver;query.deliver=void 0,clearTimeout(query.timer),deliver?.(this.terminalColorQueryResult(query))}consumeTerminalColorSchemeReport(data){let scheme=parseTerminalColorSchemeReport(data);if(!scheme)return!1;for(let listener of this.terminalColorSchemeListeners)listener(scheme);return!0}consumeCellSizeResponse(data){let match=data.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!match)return!1;let heightPx=parseInt(match[1],10),widthPx=parseInt(match[2],10);return heightPx<=0||widthPx<=0||(setCellDimensions({widthPx,heightPx}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(options2,overlayHeight,termWidth,termHeight){let opt=options2??{},margin=typeof opt.margin=="number"?{top:opt.margin,right:opt.margin,bottom:opt.margin,left:opt.margin}:opt.margin??{},marginTop=Math.max(0,margin.top??0),marginRight=Math.max(0,margin.right??0),marginBottom=Math.max(0,margin.bottom??0),marginLeft=Math.max(0,margin.left??0),availWidth=Math.max(1,termWidth-marginLeft-marginRight),availHeight=Math.max(1,termHeight-marginTop-marginBottom),width=parseSizeValue(opt.width,termWidth)??Math.min(80,availWidth);opt.minWidth!==void 0&&(width=Math.max(width,opt.minWidth)),width=Math.max(1,Math.min(width,availWidth));let maxHeight=parseSizeValue(opt.maxHeight,termHeight);maxHeight!==void 0&&(maxHeight=Math.max(1,Math.min(maxHeight,availHeight)));let effectiveHeight=maxHeight!==void 0?Math.min(overlayHeight,maxHeight):overlayHeight,row,col;if(opt.row!==void 0)if(typeof opt.row=="string"){let match=opt.row.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxRow=Math.max(0,availHeight-effectiveHeight),percent=parseFloat(match[1])/100;row=marginTop+Math.floor(maxRow*percent)}else row=this.resolveAnchorRow("center",effectiveHeight,availHeight,marginTop)}else row=opt.row;else{let anchor=opt.anchor??"center";row=this.resolveAnchorRow(anchor,effectiveHeight,availHeight,marginTop)}if(opt.col!==void 0)if(typeof opt.col=="string"){let match=opt.col.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxCol=Math.max(0,availWidth-width),percent=parseFloat(match[1])/100;col=marginLeft+Math.floor(maxCol*percent)}else col=this.resolveAnchorCol("center",width,availWidth,marginLeft)}else col=opt.col;else{let anchor=opt.anchor??"center";col=this.resolveAnchorCol(anchor,width,availWidth,marginLeft)}return opt.offsetY!==void 0&&(row+=opt.offsetY),opt.offsetX!==void 0&&(col+=opt.offsetX),row=Math.max(marginTop,Math.min(row,termHeight-marginBottom-effectiveHeight)),col=Math.max(marginLeft,Math.min(col,termWidth-marginRight-width)),{width,row,col,maxHeight}}resolveAnchorRow(anchor,height,availHeight,marginTop){switch(anchor){case"top-left":case"top-center":case"top-right":return marginTop;case"bottom-left":case"bottom-center":case"bottom-right":return marginTop+availHeight-height;case"left-center":case"center":case"right-center":return marginTop+Math.floor((availHeight-height)/2)}}resolveAnchorCol(anchor,width,availWidth,marginLeft){switch(anchor){case"top-left":case"left-center":case"bottom-left":return marginLeft;case"top-right":case"right-center":case"bottom-right":return marginLeft+availWidth-width;case"top-center":case"center":case"bottom-center":return marginLeft+Math.floor((availWidth-width)/2)}}compositeOverlays(lines,termWidth,termHeight){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],lines;let result=[...lines];for(let entry of this.overlayStack)entry.bounds=void 0;let rendered=[],minLinesNeeded=result.length,visibleEntries=this.overlayStack.filter(e=>this.isOverlayVisible(e));visibleEntries.sort((a,b)=>a.focusOrder-b.focusOrder);for(let entry of visibleEntries){let{component,options:options2}=entry,{width,maxHeight}=this.resolveOverlayLayout(options2,0,termWidth,termHeight),overlayLines=this.resolveFakeCursors(component.render(width));maxHeight!==void 0&&overlayLines.length>maxHeight&&(overlayLines=overlayLines.slice(0,maxHeight));let{row,col}=this.resolveOverlayLayout(options2,overlayLines.length,termWidth,termHeight);entry.bounds={row,col,width,height:overlayLines.length},rendered.push({entry,overlayLines,row,col,w:width}),minLinesNeeded=Math.max(minLinesNeeded,row+overlayLines.length)}this.renderedOverlayLayouts=rendered.map(({entry,row,col,w,overlayLines})=>({entry,row,col,width:w,height:overlayLines.length}));let workingHeight=Math.max(result.length,termHeight,minLinesNeeded);for(;result.length<workingHeight;)result.push("");let viewportStart=Math.max(0,workingHeight-termHeight);for(let{overlayLines,row,col,w}of rendered)for(let i=0;i<overlayLines.length;i++){let idx=viewportStart+row+i;if(idx>=0&&idx<result.length){let truncatedOverlayLine=visibleWidth(overlayLines[i])>w?sliceByColumn(overlayLines[i],0,w,!0):overlayLines[i];result[idx]=this.compositeLineAt(result[idx],truncatedOverlayLine,col,w,termWidth)}}return result}applyLineResets(lines){let reset=SEGMENT_RESET;for(let i=0;i<lines.length;i++){let line=lines[i];isImageLine(line)||(lines[i]=normalizeTerminalOutput(line.replaceAll(CURSOR_MARKER,""))+reset)}return lines}compositeLineAt(baseLine,overlayLine,startCol,overlayWidth,totalWidth){return compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth)}extractCursorPosition(lines,height){let viewportTop=Math.max(0,lines.length-height);for(let row=lines.length-1;row>=viewportTop;row--){let line=lines[row],markerIndex=line.indexOf(CURSOR_MARKER);if(markerIndex!==-1){let beforeMarker=line.slice(0,markerIndex),col=visibleWidth(beforeMarker);return lines[row]=line.replaceAll(CURSOR_MARKER,""),{row,col}}}return null}resolveFakeCursors(lines){return lines.map(line=>line.includes(FAKE_CURSOR_START)?(this.showHardwareCursor?line.replace(FOCUSED_FAKE_CURSOR,"$1$2"):line).replaceAll(FAKE_CURSOR_START,"\x1B[7m").replaceAll(FAKE_CURSOR_END,"\x1B[27m"):line)}queryTerminalColors({timeoutMs,onLateReply}){return new Promise(resolve=>{let query={palette:Array.from({length:TERMINAL_PALETTE_SIZE},()=>{}),replied:new Set,deliver:resolve,timer:void 0};query.timer=setTimeout(()=>{query.deliver=onLateReply,resolve(this.terminalColorQueryResult(query))},timeoutMs),this.pendingTerminalColorQueries.push(query),this.terminal.write(TERMINAL_COLOR_QUERY)})}};var Box=class{children=[];paddingX;paddingY;bgFn;cache;mouseLayout;constructor(paddingX=1,paddingY=1,bgFn){this.paddingX=paddingX,this.paddingY=paddingY,this.bgFn=bgFn}addChild(component){this.children.push(component),this.invalidateCache()}removeChild(component){let index=this.children.indexOf(component);index!==-1&&(this.children.splice(index,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(bgFn){this.bgFn=bgFn}setPaddingX(paddingX){this.paddingX=paddingX,this.invalidateCache()}invalidateCache(){this.cache=void 0}matchCache(width,childLines,bgSample){let cache=this.cache;return!!cache&&cache.width===width&&cache.bgSample===bgSample&&cache.childLines.length===childLines.length&&cache.childLines.every((line,i)=>line===childLines[i])}invalidate(){this.invalidateCache();for(let child of this.children)child.invalidate?.()}handleMouse(event){let contentWidth=Math.max(1,event.width-this.paddingX*2),contentY=event.y-this.paddingY,contentX=event.x-this.paddingX;if(contentY<0||contentX<0||contentX>=contentWidth)return;let mouseChildren=this.mouseLayout?.width===contentWidth?this.mouseLayout.children:this.children.map(component=>({component,height:component.render(contentWidth).length})),childY=0;for(let{component:child,height:childHeight}of mouseChildren){if(contentY>=childY&&contentY<childY+childHeight)return dispatchMouseEvent(child,{...event,x:contentX,y:contentY-childY,width:contentWidth,height:childHeight});childY+=childHeight}}render(width){if(this.children.length===0)return[];let contentWidth=Math.max(1,width-this.paddingX*2),leftPad=" ".repeat(this.paddingX),childLines=[],mouseChildren=[];for(let child of this.children){let lines=child.render(contentWidth);mouseChildren.push({component:child,height:lines.length});for(let line of lines)childLines.push(line)}if(this.mouseLayout={width:contentWidth,children:mouseChildren},childLines.length===0)return[];let bgSample=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(width,childLines,bgSample))return this.cache.lines;let result=[];for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));for(let line of childLines)result.push(this.applyBg(leftPad+line,width));for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));return flattenLines(result),this.cache={childLines,width,bgSample,lines:result},result}applyBg(line,width){let visLen=visibleWidth(line),padNeeded=Math.max(0,width-visLen),padded=line+" ".repeat(padNeeded);return this.bgFn?this.bgFn(padded):padded}};var TUI_KEYBINDINGS={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.historyPrevious":{defaultKeys:[],description:"Select previous prompt history entry"},"tui.editor.historyNext":{defaultKeys:[],description:"Select next prompt history entry"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:["pageUp","ctrl+pageUp"],description:"Page up"},"tui.editor.pageDown":{defaultKeys:["pageDown","ctrl+pageDown"],description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:["shift+enter","ctrl+j"],description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"},"tui.altScreen.pageUp":{defaultKeys:"pageUp",description:"Scroll viewport up one page"},"tui.altScreen.pageDown":{defaultKeys:"pageDown",description:"Scroll viewport down one page"},"tui.altScreen.halfPageUp":{defaultKeys:[],description:"Scroll viewport up half a page"},"tui.altScreen.halfPageDown":{defaultKeys:[],description:"Scroll viewport down half a page"},"tui.altScreen.lineUp":{defaultKeys:[],description:"Scroll viewport up one line"},"tui.altScreen.lineDown":{defaultKeys:[],description:"Scroll viewport down one line"},"tui.altScreen.previousPrompt":{defaultKeys:["ctrl+shift+up","ctrl+up"],description:"Jump to previous semantic prompt"},"tui.altScreen.nextPrompt":{defaultKeys:["ctrl+shift+down","ctrl+down"],description:"Jump to next semantic prompt"},"tui.altScreen.search":{defaultKeys:"ctrl+shift+f",description:"Search the primary scroll view"},"tui.altScreen.searchNext":{defaultKeys:["enter","ctrl+g"],description:"Select the next search match"},"tui.altScreen.searchPrevious":{defaultKeys:["shift+enter","ctrl+shift+g"],description:"Select the previous search match"},"tui.altScreen.searchClose":{defaultKeys:"escape",description:"Close transcript search"},"tui.altScreen.top":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"ctrl+end",description:"Scroll viewport to bottom"}};function normalizeKeys(keys){if(keys===void 0)return[];let keyList=Array.isArray(keys)?keys:[keys],seen=new Set,result=[];for(let key of keyList)seen.has(key)||(seen.add(key),result.push(key));return result}var KeybindingsManager=class{definitions;userBindings;keysById=new Map;conflicts=[];constructor(definitions,userBindings={}){this.definitions=definitions,this.userBindings=userBindings,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let userClaims=new Map;for(let[keybinding,keys]of Object.entries(this.userBindings))if(keybinding in this.definitions)for(let key of normalizeKeys(keys)){let claimants=userClaims.get(key)??new Set;claimants.add(keybinding),userClaims.set(key,claimants)}for(let[key,keybindings]of userClaims)keybindings.size>1&&this.conflicts.push({key,keybindings:[...keybindings]});for(let[id,definition]of Object.entries(this.definitions)){let userKeys=this.userBindings[id],keys=normalizeKeys(userKeys===void 0?definition.defaultKeys:userKeys);this.keysById.set(id,keys)}}matches(data,keybinding){let keys=this.keysById.get(keybinding)??[];for(let key of keys)if(matchesKey(data,key))return!0;return!1}getKeys(keybinding){return[...this.keysById.get(keybinding)??[]]}getDefinition(keybinding){return this.definitions[keybinding]}getConflicts(){return this.conflicts.map(conflict=>({...conflict,keybindings:[...conflict.keybindings]}))}setUserBindings(userBindings){this.userBindings=userBindings,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let resolved={};for(let id of Object.keys(this.definitions)){let keys=this.keysById.get(id)??[];resolved[id]=keys.length===1?keys[0]:[...keys]}return resolved}},globalKeybindings=null;function setKeybindings(keybindings){globalKeybindings=keybindings}function getKeybindings(){return globalKeybindings||(globalKeybindings=new KeybindingsManager(TUI_KEYBINDINGS)),globalKeybindings}function getSelectPageIndex(keybindings,data,selectedIndex,itemCount,pageSize){let direction;if(keybindings.matches(data,"tui.select.pageUp"))direction=-1;else if(keybindings.matches(data,"tui.select.pageDown"))direction=1;else return;return Math.max(0,Math.min(itemCount-1,selectedIndex+direction*pageSize))}var Text=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(text="",paddingX=1,paddingY=1,customBgFn){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.customBgFn=customBgFn}setText(text){text!==this.text&&(this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0)}setCustomBgFn(customBgFn){this.customBgFn=customBgFn,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setPaddingX(paddingX){this.paddingX=paddingX,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;if(!this.text||this.text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=this.text.replace(/\t/g," "),paddingX=Math.min(this.paddingX,Math.max(0,Math.floor((width-1)/2))),contentWidth=Math.max(1,width-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 flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};var DEFAULT_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],DEFAULT_INTERVAL_MS=80,Loader=class extends Text{frames=[...DEFAULT_FRAMES];intervalMs=DEFAULT_INTERVAL_MS;currentFrame=0;intervalId=null;ui=null;renderIndicatorVerbatim=!1;spinnerColorFn;messageColorFn;message="Loading...";constructor(ui,spinnerColorFn,messageColorFn,message="Loading...",indicator){super("",1,0),this.ui=ui,this.spinnerColorFn=spinnerColorFn,this.messageColorFn=messageColorFn,this.message=message,this.setIndicator(indicator)}render(width){return["",...super.render(width)]}start(){this.updateDisplay(),this.restartAnimation()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}setMessage(message){this.message=message,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}setIndicator(indicator){this.renderIndicatorVerbatim=indicator!==void 0,this.frames=indicator?.frames!==void 0?[...indicator.frames]:[...DEFAULT_FRAMES],this.intervalMs=indicator?.intervalMs&&indicator.intervalMs>0?indicator.intervalMs:DEFAULT_INTERVAL_MS,this.currentFrame=0,this.start()}restartAnimation(){this.stop(),!(this.frames.length<=1)&&(this.intervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},this.intervalMs))}getRenderedIndicator(){let frame=this.frames[this.currentFrame]??"";return this.renderIndicatorVerbatim?frame:this.spinnerColorFn(frame)}updateDisplay(){let renderedFrame=this.getRenderedIndicator(),indicator=renderedFrame.length>0?`${renderedFrame} `:"";this.setText(`${indicator}${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender()}};var CancellableLoader=class extends Loader{abortController=new AbortController;onAbort;get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(data){getKeybindings().matches(data,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var KillRing=class{ring=[];push(text,opts){if(text)if(opts.accumulate&&this.ring.length>0){let last=this.ring.pop();this.ring.push(opts.prepend?text+last:last+text)}else this.ring.push(text)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let last=this.ring.pop();this.ring.unshift(last)}}get length(){return this.ring.length}};var UndoStack=class{stack=[];push(state){this.stack.push(structuredClone(state))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};var wordSegmenter2=getWordSegmenter();function findWordBackward(text,cursor,options2){if(cursor<=0)return 0;let textBeforeCursor=text.slice(0,cursor),segmentFn=options2?.segment,isAtomic=options2?.isAtomicSegment,segments=segmentFn?[...segmentFn(textBeforeCursor)]:[...wordSegmenter2.segment(textBeforeCursor)],newCursor=cursor;for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||0;if(segments.length===0)return newCursor;let last=segments[segments.length-1];if(isAtomic?.(last.segment))newCursor-=last.segment.length;else if(last.isWordLike){let segment=last.segment,matches=[...segment.matchAll(new RegExp(PUNCTUATION_REGEX,"g"))];if(matches.length<=0)newCursor-=segment.length;else{let lastMatch=matches[matches.length-1];newCursor-=segment.length-(lastMatch.index+lastMatch[0].length)}}else for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&!segments[segments.length-1]?.isWordLike&&!isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||0;return newCursor}function findWordForward(text,cursor,options2){if(cursor>=text.length)return text.length;let textAfterCursor=text.slice(cursor),segmentFn=options2?.segment,isAtomic=options2?.isAtomicSegment,iterator=(segmentFn?segmentFn(textAfterCursor):wordSegmenter2.segment(textAfterCursor))[Symbol.iterator](),next=iterator.next(),newCursor=cursor;for(;!next.done&&!isAtomic?.(next.value.segment)&&isWhitespaceChar(next.value.segment);)newCursor+=next.value.segment.length,next=iterator.next();if(next.done)return newCursor;if(isAtomic?.(next.value.segment))newCursor+=next.value.segment.length;else if(next.value.isWordLike)newCursor+=PUNCTUATION_REGEX.exec(next.value.segment)?.index??next.value.segment.length;else for(;!next.done&&!isAtomic?.(next.value.segment)&&!next.value.isWordLike&&!isWhitespaceChar(next.value.segment);)newCursor+=next.value.segment.length,next=iterator.next();return newCursor}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{capturesViewportInput=!0;items=[];filteredItems=[];selectedIndex=0;mousePressedIndex;maxVisible=5;theme;layout;onSelect;onCancel;onSelectionChange;constructor(items,maxVisible,theme2,layout={}){this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme2,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(),pageIndex=getSelectPageIndex(kb,keyData,this.selectedIndex,this.filteredItems.length,this.maxVisible);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(pageIndex!==void 0){if(this.filteredItems.length===0||pageIndex===this.selectedIndex)return;this.selectedIndex=pageIndex,this.notifySelectionChange()}else kb.matches(keyData,"tui.select.confirm")?this.confirmSelection():kb.matches(keyData,"tui.select.cancel")&&this.onCancel&&this.onCancel()}confirmSelection(){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelect&&this.onSelect(selectedItem)}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,"");if(isSelected)return this.theme.selectedText(`${prefix}${truncatedValue2}${spacing}${truncatedDesc}`);let descText=this.theme.description(spacing+truncatedDesc);return prefix+truncatedValue2+descText}}let maxWidth=width-prefixWidth-2,truncatedValue=this.truncatePrimary(item,isSelected,maxWidth,maxWidth);return isSelected?this.theme.selectedText(`${prefix}${truncatedValue}`):prefix+truncatedValue}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}};var graphemeSegmenter2=getGraphemeSegmenter(),wordSegmenter3=getWordSegmenter(),PASTE_MARKER_REGEX=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,PASTE_MARKER_SINGLE=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function isPasteMarker(segment){return segment.length>=10&&PASTE_MARKER_SINGLE.test(segment)}function segmentWithMarkers(text,baseSegmenter,validIds){if(validIds.size===0||!text.includes("[paste #"))return baseSegmenter.segment(text);let markers=[];for(let m of text.matchAll(PASTE_MARKER_REGEX)){let id=Number.parseInt(m[1],10);validIds.has(id)&&markers.push({start:m.index,end:m.index+m[0].length})}if(markers.length===0)return baseSegmenter.segment(text);let baseSegments=baseSegmenter.segment(text),result=[],markerIdx=0;for(let seg of baseSegments){for(;markerIdx<markers.length&&markers[markerIdx].end<=seg.index;)markerIdx++;let marker=markerIdx<markers.length?markers[markerIdx]:null;if(marker&&seg.index>=marker.start&&seg.index<marker.end){if(seg.index===marker.start){let markerText=text.slice(marker.start,marker.end);result.push({segment:markerText,index:marker.start,input:text})}}else result.push(seg)}return result}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(visibleWidth(line)<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],segments=preSegmented??[...graphemeSegmenter2.segment(line)],currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0;for(let i=0;i<segments.length;i++){let seg=segments[i],grapheme=seg.segment,gWidth=visibleWidth(grapheme),charIndex=seg.index,isWs=!isPasteMarker(grapheme)&&isWhitespaceChar(grapheme);if(currentWidth+gWidth>maxWidth&&(wrapOppIndex>=0&&currentWidth-wrapOppWidth+gWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<charIndex&&(chunks.push({text:line.slice(chunkStart,charIndex),startIndex:chunkStart,endIndex:charIndex}),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&&(isPasteMarker(next.segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=next.index,wrapOppWidth=currentWidth;else if(!isWs&&next&&!isWhitespaceChar(next.segment)){let isCjk=!isPasteMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isPasteMarker(next.segment)&&cjkBreakRegex.test(next.segment);(isCjk||nextIsCjk)&&(wrapOppIndex=next.index,wrapOppWidth=currentWidth)}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:line.length}),chunks}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#"],unquotedAutocompleteSuffixRegex=new RegExp(`(?:(?!${autocompleteSeparatorRegex.source}).)*`,"u"),autocompleteTokenStartSource=`${autocompleteBoundaryRegex.source}[([{<\`]*`;function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`${autocompleteTokenStartSource}(?:@"[^"]*|[${triggerCharacters.map(escapeCharacterClass).join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!=="@").map(escapeCharacterClass);return new RegExp(`${autocompleteTokenStartSource}(?:@(?:"[^"]*|${unquotedAutocompleteSuffixRegex.source})|[${escapedWithoutAt.join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function createScrollBorder(direction,hiddenLineCount,width){let availableWidth=Math.max(0,width),label=` ${direction} ${hiddenLineCount} more `,labelWidth=visibleWidth(label);if(labelWidth+2<=availableWidth){let leftWidth=Math.floor((availableWidth-labelWidth)/2);return"\u2500".repeat(leftWidth)+label+"\u2500".repeat(availableWidth-leftWidth-labelWidth)}let indicator=`\u2500\u2500\u2500 ${direction} ${hiddenLineCount} more `,remaining=availableWidth-visibleWidth(indicator);if(remaining>=0)return indicator+"\u2500".repeat(remaining);let ellipsis="...".slice(0,availableWidth),indicatorWidth=availableWidth-visibleWidth(ellipsis);return sliceByColumn(indicator,0,indicatorWidth,!0)+ellipsis}var Editor=class{state={lines:[""],cursorLine:0,cursorCol:0};focused=!1;get capturesViewportInput(){return this.autocompleteState!==null}tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];autocompleteTriggerPattern=buildTriggerPattern(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=buildDebouncePattern(this.autocompleteTriggerCharacters);autocompleteList;autocompleteState=null;autocompletePrefix="";autocompleteMaxVisible=5;autocompleteAbort;autocompleteDebounceTimer;autocompleteRequestTask=Promise.resolve();autocompleteStartToken=0;autocompleteRequestId=0;pastes=new Map;pasteCounter=0;pasteBuffer="";isInPaste=!1;history=[];historyIndex=-1;historyDraft=null;killRing=new KillRing;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new UndoStack;onSubmit;onChange;disableSubmit=!1;constructor(tui,theme2,options2={}){this.tui=tui,this.theme=theme2,this.borderColor=theme2.borderColor;let paddingX=options2.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0;let maxVisible=options2.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter3:graphemeSegmenter2,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(padding){let newPadding=Number.isFinite(padding)?Math.max(0,Math.floor(padding)):0;this.paddingX!==newPadding&&(this.paddingX=newPadding,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(maxVisible){let newMaxVisible=Number.isFinite(maxVisible)?Math.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(`
62
+ `||data==="\x1BOM")return"enter";if(data==="\0")return"ctrl+space";if(data===" ")return"space";if(data==="\x7F")return"backspace";if(data==="\b")return isWindowsTerminalSession()?"ctrl+backspace":"backspace";if(data==="\x1B[Z")return"shift+tab";if(!_kittyProtocolActive&&data==="\x1B\r")return"alt+enter";if(!_kittyProtocolActive&&data==="\x1B ")return"alt+space";if(data==="\x1B\x7F"||data==="\x1B\b")return"alt+backspace";if(!_kittyProtocolActive&&data==="\x1BB")return"alt+left";if(!_kittyProtocolActive&&data==="\x1BF")return"alt+right";if(!_kittyProtocolActive&&data.length===2&&data[0]==="\x1B"){let code=data.charCodeAt(1);if(code>=1&&code<=26)return`ctrl+alt+${String.fromCharCode(code+96)}`;let key=String.fromCharCode(code);if(code>=97&&code<=122||code>=48&&code<=57||SYMBOL_KEYS.has(key))return`alt+${key}`}if(data==="\x1B[A")return"up";if(data==="\x1B[B")return"down";if(data==="\x1B[C")return"right";if(data==="\x1B[D")return"left";if(data==="\x1B[H"||data==="\x1BOH")return"home";if(data==="\x1B[F"||data==="\x1BOF")return"end";if(data==="\x1B[3~")return"delete";if(data==="\x1B[5~")return"pageUp";if(data==="\x1B[6~")return"pageDown";if(data.length===1){let code=data.charCodeAt(0);if(code>=1&&code<=26)return`ctrl+${String.fromCharCode(code+96)}`;if(code>=32&&code<=126)return data}}var KITTY_CSI_U_REGEX=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,KITTY_PRINTABLE_ALLOWED_MODIFIERS=MODIFIERS.shift|LOCK_MASK;function decodeKittyPrintable(data){let match=data.match(KITTY_CSI_U_REGEX);if(!match)return;let codepoint=Number.parseInt(match[1]??"",10);if(!Number.isFinite(codepoint))return;let shiftedKey=match[2]&&match[2].length>0?Number.parseInt(match[2],10):void 0,modValue=match[4]?Number.parseInt(match[4],10):1,modifier=Number.isFinite(modValue)?modValue-1:0;if((modifier&~KITTY_PRINTABLE_ALLOWED_MODIFIERS)!==0||modifier&(MODIFIERS.alt|MODIFIERS.ctrl))return;let effectiveCodepoint=codepoint;if(modifier&MODIFIERS.shift&&typeof shiftedKey=="number"&&(effectiveCodepoint=shiftedKey),effectiveCodepoint=normalizeKittyFunctionalCodepoint(effectiveCodepoint),!(!Number.isFinite(effectiveCodepoint)||effectiveCodepoint<32)&&!(effectiveCodepoint>=KITTY_FUNCTIONAL_PUA_START&&effectiveCodepoint<=KITTY_FUNCTIONAL_PUA_END))try{return String.fromCodePoint(effectiveCodepoint)}catch{return}}function decodeModifyOtherKeysPrintable(data){let parsed=parseModifyOtherKeysSequence(data);if(!(!parsed||(parsed.modifier&~LOCK_MASK&~MODIFIERS.shift)!==0)&&!(!Number.isFinite(parsed.codepoint)||parsed.codepoint<32))try{return String.fromCodePoint(parsed.codepoint)}catch{return}}function decodePrintableKey(data){return decodeKittyPrintable(data)??decodeModifyOtherKeysPrintable(data)}function hexToRgb(hex){let normalized=hex.startsWith("#")?hex.slice(1):hex,r=parseInt(normalized.slice(0,2),16),g=parseInt(normalized.slice(2,4),16),b=parseInt(normalized.slice(4,6),16);return{r,g,b}}function parseOscHexChannel(channel){if(!/^[0-9a-f]+$/i.test(channel))return;let max=16**channel.length-1;if(!(max<=0))return Math.round(parseInt(channel,16)/max*255)}var OSC_COLOR_RESPONSE_PATTERN=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,COLOR_SCHEME_REPORT_PATTERN=/^(?:\x1b\[\?997;(1|2)n)+$/;function parseOscColorResponse(data){let match=data.match(OSC_COLOR_RESPONSE_PATTERN);return match?{target:match[1]==="10"?"foreground":match[1]==="11"?"background":Number.parseInt(match[2],10),rgb:parseOscColorValue(match[3])}:void 0}function parseOscColorValue(rawValue){let value=rawValue.trim();if(value.startsWith("#")){let hex=value.slice(1);if(/^[0-9a-f]{6}$/i.test(hex))return hexToRgb(value);if(/^[0-9a-f]{12}$/i.test(hex)){let r2=parseOscHexChannel(hex.slice(0,4)),g2=parseOscHexChannel(hex.slice(4,8)),b2=parseOscHexChannel(hex.slice(8,12));return r2!==void 0&&g2!==void 0&&b2!==void 0?{r:r2,g:g2,b:b2}:void 0}return}let rgbValue=value.replace(/^rgba?:/i,""),[red,green,blue]=rgbValue.split("/");if(red===void 0||green===void 0||blue===void 0)return;let r=parseOscHexChannel(red),g=parseOscHexChannel(green),b=parseOscHexChannel(blue);return r!==void 0&&g!==void 0&&b!==void 0?{r,g,b}:void 0}function parseTerminalColorSchemeReport(data){let match=data.match(COLOR_SCHEME_REPORT_PATTERN);if(match)return match[1]==="2"?"light":"dark"}import{execSync}from"node:child_process";import{homedir as homedir2}from"node:os";import{isAbsolute}from"node:path";import{pathToFileURL}from"node:url";var cachedCapabilities=null,capabilityOverrides={},cellDimensions={widthPx:9,heightPx:18};function getCellDimensions(){return cellDimensions}function setCellDimensions(dims){cellDimensions=dims}function probeTmuxHyperlinks(){try{return execSync("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",timeout:250,stdio:["ignore","pipe","ignore"]}).split(",").map(feature=>feature.trim()).includes("hyperlinks")}catch{return!1}}function detectCapabilitiesFromEnvironment(tmuxForwardsHyperlink){let termProgram=process.env.TERM_PROGRAM?.toLowerCase()||"",terminalEmulator=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",term=process.env.TERM?.toLowerCase()||"",colorTerm=process.env.COLORTERM?.toLowerCase()||"",hasTrueColorHint=colorTerm==="truecolor"||colorTerm==="24bit"||term.endsWith("-direct"),isWindowsConsole=process.platform==="win32";return process.env.TMUX||term.startsWith("tmux")?{images:null,trueColor:hasTrueColorHint,hyperlinks:tmuxForwardsHyperlink()}:term.startsWith("screen")?{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}:termProgram==="herdr"?{images:"kitty",trueColor:hasTrueColorHint,hyperlinks:!0}:termProgram==="rex"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="orca"&&process.env.ORCA_IMAGE_PROTOCOL==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.KITTY_WINDOW_ID||termProgram==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="ghostty"||term.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||termProgram==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||termProgram==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:termProgram==="alacritty"||term.startsWith("alacritty")||process.env.ALACRITTY_WINDOW_ID||termProgram==="vscode"||termProgram==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:terminalEmulator==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:isWindowsConsole?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}}function parseBooleanCapabilityOverride(value){return value==="1"?!0:value==="0"?!1:void 0}function detectCapabilities(tmuxForwardsHyperlink=probeTmuxHyperlinks){let hyperlinks=parseBooleanCapabilityOverride(process.env.DRAHT_HYPERLINKS),detected=detectCapabilitiesFromEnvironment(hyperlinks===void 0?tmuxForwardsHyperlink:()=>hyperlinks),imageProtocol=process.env.DRAHT_IMAGE_PROTOCOL?.toLowerCase(),images=imageProtocol==="kitty"||imageProtocol==="iterm2"?imageProtocol:imageProtocol==="none"||imageProtocol==="0"?null:void 0,trueColor=parseBooleanCapabilityOverride(process.env.DRAHT_TRUE_COLOR);return{...detected,...images!==void 0?{images}:{},...trueColor!==void 0?{trueColor}:{},...hyperlinks!==void 0?{hyperlinks}:{}}}function getCapabilities(){if(!cachedCapabilities){let hyperlinks=capabilityOverrides.hyperlinks;cachedCapabilities={...detectCapabilities(hyperlinks===void 0?void 0:()=>hyperlinks),...capabilityOverrides}}return cachedCapabilities}function getTerminalColorMode(capabilities=getCapabilities()){return capabilities.trueColor?"truecolor":"256color"}function resetCapabilitiesCache(){cachedCapabilities=null}function setCapabilityOverrides(overrides){capabilityOverrides.images===overrides.images&&capabilityOverrides.trueColor===overrides.trueColor&&capabilityOverrides.hyperlinks===overrides.hyperlinks||(capabilityOverrides={...overrides},cachedCapabilities=null)}function setCapabilities(caps){cachedCapabilities=caps}var KITTY_PREFIX="\x1B_G",ITERM2_PREFIX="\x1B]1337;File=";function isImageLine(line){return line.startsWith(KITTY_PREFIX)||line.startsWith(ITERM2_PREFIX)?!0:line.includes(KITTY_PREFIX)||line.includes(ITERM2_PREFIX)}function getImageLineExtent(line){let kittyStart=line.indexOf(KITTY_PREFIX);if(kittyStart!==-1){let controls=/\x1b_G([^;]*);/.exec(line)?.[1]??"",columnValue2=/(?:^|,)c=(\d+)(?:,|$)/.exec(controls)?.[1],columns=columnValue2===void 0?getRegisteredKittyImageMetadataFromControls(controls)?.columns:Number.parseInt(columnValue2,10),startCol2=visibleWidth(line.slice(0,kittyStart));return{firstRow:0,lastRow:(getKittyImagePlacementRows(line)??1)-1,startCol:startCol2,endCol:startCol2+(columns??1/0)}}let iterm2Start=line.indexOf(ITERM2_PREFIX);if(iterm2Start===-1)return;let before=line.slice(0,iterm2Start),moveUp=/\x1b\[(\d+)A$/.exec(before),columnValue=/[;=]width=(\d+)[;:]/.exec(line.slice(iterm2Start))?.[1],startCol=visibleWidth(moveUp?before.slice(0,moveUp.index):before);return{firstRow:moveUp?-Number.parseInt(moveUp[1],10):0,lastRow:0,startCol,endCol:startCol+(columnValue===void 0?1/0:Number.parseInt(columnValue,10))}}function stripImageSequences(line){return line.replace(/\x1b_G[^\x1b]*\x1b\\/g,"").replace(/(?:\x1b\[\d+A)?\x1b\]1337;File=[^\x07]*\x07/g,"")}function allocateImageId(){return Math.floor(Math.random()*4294967294)+1}function encodeKitty(base64Data,options2={}){let params=["a=T","f=100","q=2"];if(options2.moveCursor===!1&&params.push("C=1"),options2.columns&&params.push(`c=${options2.columns}`),options2.rows&&params.push(`r=${options2.rows}`),options2.imageId&&params.push(`i=${options2.imageId}`),base64Data.length<=4096)return`\x1B_G${params.join(",")};${base64Data}\x1B\\`;let chunks=[],offset=0,isFirst=!0;for(;offset<base64Data.length;){let chunk=base64Data.slice(offset,offset+4096),isLast=offset+4096>=base64Data.length;isFirst?(chunks.push(`\x1B_G${params.join(",")},m=1;${chunk}\x1B\\`),isFirst=!1):isLast?chunks.push(`\x1B_Gm=0;${chunk}\x1B\\`):chunks.push(`\x1B_Gm=1;${chunk}\x1B\\`),offset+=4096}return chunks.join("")}function deleteKittyImage(imageId){return`\x1B_Ga=d,d=I,i=${imageId},q=2\x1B\\`}function deleteAllKittyImages(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}function deleteAllKittyPlacements(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function encodeITerm2(base64Data,options2={}){let params=[`inline=${options2.inline!==!1?1:0}`,`size=${Buffer.byteLength(base64Data,"base64")}`];if(options2.width!==void 0&&params.push(`width=${options2.width}`),options2.height!==void 0&&params.push(`height=${options2.height}`),options2.name){let nameBase64=Buffer.from(options2.name).toString("base64");params.push(`name=${nameBase64}`)}return options2.preserveAspectRatio===!1&&params.push("preserveAspectRatio=0"),`\x1B]1337;File=${params.join(";")}:${base64Data}\x07`}var kittyImageMetadata=new Map,kittyTransmissionGeneration=0,maxKittyImageRows=0;function registerKittyImageMetadata(metadata){if(kittyTransmissionGeneration+=1,maxKittyImageRows=Math.max(maxKittyImageRows,metadata.rows),kittyImageMetadata.delete(metadata.imageId),kittyImageMetadata.set(metadata.imageId,{...metadata,transmissionGeneration:kittyTransmissionGeneration}),kittyImageMetadata.size>1e3){let oldestImageId=kittyImageMetadata.keys().next().value;oldestImageId!==void 0&&kittyImageMetadata.delete(oldestImageId)}}function getMaxKittyImageRows(){return maxKittyImageRows}function getRegisteredKittyImageMetadataFromControls(controls){let imageId=/(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];return imageId===void 0?void 0:kittyImageMetadata.get(Number.parseInt(imageId,10))}function getRegisteredKittyImageMetadata(line){let controls=/\x1b_G([^;]*);/.exec(line)?.[1];return controls===void 0?void 0:getRegisteredKittyImageMetadataFromControls(controls)}function getExplicitKittyImageRows(controls){let value=/(?:^|,)r=(\d+)(?:,|$)/.exec(controls)?.[1];if(value===void 0)return;let rows=Number.parseInt(value,10);return rows>0?rows:void 0}function getKittyImageRowsFromControls(controls,fallbackRows){return getExplicitKittyImageRows(controls)??fallbackRows}function getKittyImageMetadata(line){let metadata=getRegisteredKittyImageMetadata(line);if(metadata)return{imageId:metadata.imageId,columns:metadata.columns,rows:metadata.rows,widthPx:metadata.widthPx,heightPx:metadata.heightPx}}var KITTY_PLACEMENT_CONTROL_KEYS=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function getKittyImagePlacementRows(line){let controls=/\x1b_G([^;]*);/.exec(line)?.[1];if(controls===void 0)return;let explicitRows=getExplicitKittyImageRows(controls);return explicitRows!==void 0?explicitRows:getRegisteredKittyImageMetadataFromControls(controls)?.rows}function getKittyImagePlacement(line){let match=/\x1b_G([^;]*);/.exec(line);if(!match)return;let metadata=getRegisteredKittyImageMetadataFromControls(match[1]);if(!metadata)return;let commandStart=match.index,commandControls=match[1],transmissionEnd;for(;;){let terminator=line.indexOf("\x1B\\",commandStart+KITTY_PREFIX.length);if(terminator===-1)return;if(transmissionEnd=terminator+2,!/(?:^|,)m=1(?:,|$)/.test(commandControls))break;if(commandStart=transmissionEnd,!line.startsWith(KITTY_PREFIX,commandStart))return;let controlsEnd=line.indexOf(";",commandStart+KITTY_PREFIX.length);if(controlsEnd===-1)return;commandControls=line.slice(commandStart+KITTY_PREFIX.length,controlsEnd)}let sequence=`\x1B_Ga=p,q=2,${match[1].split(",").filter(control=>KITTY_PLACEMENT_CONTROL_KEYS.has(control.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:metadata.imageId,transmissionGeneration:metadata.transmissionGeneration,transmissionBytes:transmissionEnd-match.index,estimatedDecodedBytes:metadata.widthPx*metadata.heightPx*4,rows:getKittyImageRowsFromControls(match[1],metadata.rows),sequence,replacementLine:`${line.slice(0,match.index)}${sequence}${line.slice(transmissionEnd)}`}}function cropKittyImageLine(line,hiddenRows,visibleRows){let metadata=getKittyImageMetadata(line),match=/\x1b_G([^;]*);/.exec(line);if(!metadata||!match||hiddenRows<0||hiddenRows>=metadata.rows||visibleRows<=0)return line;let croppedRows=Math.min(visibleRows,metadata.rows-hiddenRows);if(hiddenRows===0&&croppedRows===metadata.rows)return line;let sourceY=Math.floor(metadata.heightPx*hiddenRows/metadata.rows),sourceEnd=Math.ceil(metadata.heightPx*(hiddenRows+croppedRows)/metadata.rows),sourceHeight=Math.max(1,Math.min(metadata.heightPx,sourceEnd)-sourceY),controls=match[1].split(",").filter(control=>!/^[yhr]=/.test(control));return controls.push(`y=${sourceY}`,`h=${sourceHeight}`,`r=${croppedRows}`),`${line.slice(0,match.index)}\x1B_G${controls.join(",")};${line.slice(match.index+match[0].length)}`}function chooseLessDistortedCellCount(upperCount,idealCount){if(upperCount<=1)return upperCount;let lowerCount=upperCount-1,upperDistortion=Math.max(upperCount/idealCount,idealCount/upperCount);return Math.max(lowerCount/idealCount,idealCount/lowerCount)<upperDistortion?lowerCount:upperCount}function calculateImageCellSize(imageDimensions,maxWidthCells,maxHeightCells,cellDimensions2={widthPx:9,heightPx:18},optimizeAspectRatio=!1){let maxWidth=Math.max(1,Math.floor(maxWidthCells)),maxHeight=maxHeightCells===void 0?void 0:Math.max(1,Math.floor(maxHeightCells)),imageWidth=Math.max(1,imageDimensions.widthPx),imageHeight=Math.max(1,imageDimensions.heightPx),widthScale=maxWidth*cellDimensions2.widthPx/imageWidth,heightScale=maxHeight===void 0?widthScale:maxHeight*cellDimensions2.heightPx/imageHeight,scale=Math.min(widthScale,heightScale),scaledWidthPx=imageWidth*scale,scaledHeightPx=imageHeight*scale,columns=Math.max(1,Math.min(maxWidth,Math.ceil(scaledWidthPx/cellDimensions2.widthPx))),heightRows=scaledHeightPx/cellDimensions2.heightPx,rows=Math.max(1,Math.ceil(heightRows));if(maxHeight!==void 0&&(rows=Math.min(maxHeight,rows)),!optimizeAspectRatio)return{columns,rows};if(widthScale<=heightScale){let idealRows=columns*cellDimensions2.widthPx*imageHeight/(imageWidth*cellDimensions2.heightPx);rows=chooseLessDistortedCellCount(rows,idealRows)}else{let idealColumns=rows*cellDimensions2.heightPx*imageWidth/(imageHeight*cellDimensions2.widthPx);columns=chooseLessDistortedCellCount(columns,idealColumns)}return{columns,rows}}function calculateImageRows(imageDimensions,targetWidthCells,cellDimensions2={widthPx:9,heightPx:18}){return calculateImageCellSize(imageDimensions,targetWidthCells,void 0,cellDimensions2).rows}function getPngDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<24||buffer[0]!==137||buffer[1]!==80||buffer[2]!==78||buffer[3]!==71)return null;let width=buffer.readUInt32BE(16),height=buffer.readUInt32BE(20);return{widthPx:width,heightPx:height}}catch{return null}}function getJpegDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<2||buffer[0]!==255||buffer[1]!==216)return null;let offset=2;for(;offset<buffer.length-9;){if(buffer[offset]!==255){offset++;continue}let marker=buffer[offset+1];if(marker>=192&&marker<=194){let height=buffer.readUInt16BE(offset+5);return{widthPx:buffer.readUInt16BE(offset+7),heightPx:height}}if(offset+3>=buffer.length)return null;let length=buffer.readUInt16BE(offset+2);if(length<2)return null;offset+=2+length}return null}catch{return null}}function getGifDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<10)return null;let sig=buffer.slice(0,6).toString("ascii");if(sig!=="GIF87a"&&sig!=="GIF89a")return null;let width=buffer.readUInt16LE(6),height=buffer.readUInt16LE(8);return{widthPx:width,heightPx:height}}catch{return null}}function getWebpDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<30)return null;let riff=buffer.slice(0,4).toString("ascii"),webp=buffer.slice(8,12).toString("ascii");if(riff!=="RIFF"||webp!=="WEBP")return null;let chunk=buffer.slice(12,16).toString("ascii");if(chunk==="VP8 "){if(buffer.length<30)return null;let width=buffer.readUInt16LE(26)&16383,height=buffer.readUInt16LE(28)&16383;return{widthPx:width,heightPx:height}}else if(chunk==="VP8L"){if(buffer.length<25)return null;let bits=buffer.readUInt32LE(21),width=(bits&16383)+1,height=(bits>>14&16383)+1;return{widthPx:width,heightPx:height}}else if(chunk==="VP8X"){if(buffer.length<30)return null;let width=(buffer[24]|buffer[25]<<8|buffer[26]<<16)+1,height=(buffer[27]|buffer[28]<<8|buffer[29]<<16)+1;return{widthPx:width,heightPx:height}}return null}catch{return null}}function getImageDimensions(base64Data,mimeType){return mimeType==="image/png"?getPngDimensions(base64Data):mimeType==="image/jpeg"?getJpegDimensions(base64Data):mimeType==="image/gif"?getGifDimensions(base64Data):mimeType==="image/webp"?getWebpDimensions(base64Data):null}function renderImage(base64Data,imageDimensions,options2={}){let caps=getCapabilities();if(!caps.images)return null;let maxWidth=options2.maxWidthCells??80,size=calculateImageCellSize(imageDimensions,maxWidth,options2.maxHeightCells,getCellDimensions(),caps.images==="kitty");return caps.images==="kitty"?(options2.imageId!==void 0&&registerKittyImageMetadata({imageId:options2.imageId,columns:size.columns,rows:size.rows,widthPx:imageDimensions.widthPx,heightPx:imageDimensions.heightPx}),{sequence:encodeKitty(base64Data,{columns:size.columns,rows:size.rows,imageId:options2.imageId,moveCursor:options2.moveCursor}),columns:size.columns,rows:size.rows,imageId:options2.imageId}):caps.images==="iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options2.preserveAspectRatio??!0}),columns:size.columns,rows:size.rows}:null}function hyperlink(text,url){return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`}function shortenImagePath(filename){let home=homedir2();return home&&(filename===home||filename.startsWith(`${home}/`)||filename.startsWith(`${home}\\`))?`~${filename.slice(home.length)}`:filename}function imageFallback(mimeType,dimensions,filename){let parts=[];if(filename){let display=shortenImagePath(filename);getCapabilities().hyperlinks&&isAbsolute(filename)?parts.push(hyperlink(display,pathToFileURL(filename).href)):parts.push(display)}return parts.push(`[${mimeType}]`),dimensions&&parts.push(`${dimensions.widthPx}x${dimensions.heightPx}`),`[Image: ${parts.join(" ")}]`}function dispatchMouseEvent(component,event){let result=component.handleMouse?.(event);if(result){if("target"in result){let forwarded=result;return forwarded.focus&&component.handleInput?{...forwarded,focusTarget:component}:forwarded}if(!(!result.handled&&!result.capture&&!result.focus))return{...result,handled:!0,...result.focus?{focusTarget:component}:{},target:{component,originX:event.screenX-event.x,originY:event.screenY-event.y,width:event.width,height:event.height}}}}function retargetMouseEvent(event,target){return{...event,x:event.screenX-target.originX,y:event.screenY-target.originY,width:target.width,height:target.height}}var TERMINAL_PALETTE_SIZE=16,TERMINAL_COLOR_REPLY_COUNT=2+TERMINAL_PALETTE_SIZE,TERMINAL_COLOR_QUERY=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:TERMINAL_PALETTE_SIZE},(_,index)=>`\x1B]4;${index};?\x07`).join("")}\x1B[c`,DEVICE_ATTRIBUTES_RESPONSE_PATTERN=/^\x1b\[\?[\d;]*c$/;function isFocusable(component){return component!==null&&"focused"in component}var CURSOR_MARKER="\x1B_pi:c\x07",FAKE_CURSOR_START="\x1B_pi:fc\x07",FAKE_CURSOR_END="\x1B_pi:/fc\x07",FOCUSED_FAKE_CURSOR=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function renderFakeCursor(text){return`${FAKE_CURSOR_START}${text}${FAKE_CURSOR_END}`}function parseSizeValue(value,referenceSize){if(value===void 0)return;if(typeof value=="number")return value;let match=value.match(/^(\d+(?:\.\d+)?)%$/);if(match)return Math.floor(referenceSize*parseFloat(match[1])/100)}var Container=class{children=[];mouseLayout;addChild(component){this.children.push(component)}removeChild(component){let index=this.children.indexOf(component);index!==-1&&this.children.splice(index,1)}clear(){this.children=[]}invalidate(){for(let child of this.children)child.invalidate?.()}handleMouse(event){if(event.y<0||event.y>=event.height)return;let mouseChildren=this.mouseLayout?.width===event.width?this.mouseLayout.children:this.children.map(component=>({component,height:component.render(event.width).length})),childY=0;for(let{component:child,height:childHeight}of mouseChildren){if(event.y>=childY&&event.y<childY+childHeight){let result=dispatchMouseEvent(child,{...event,y:event.y-childY,height:childHeight});return result?.focus&&this.handleInput?{...result,focusTarget:this}:result}childY+=childHeight}}render(width){let lines=[],mouseChildren=[];for(let child of this.children){let childLines=child.render(width);mouseChildren.push({component:child,height:childLines.length});for(let line of childLines)lines.push(line)}return this.mouseLayout={width,children:mouseChildren},lines}},SEGMENT_RESET="\x1B[0m\x1B]8;;\x07";function compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth){if(isImageLine(baseLine))return baseLine;let afterStart=startCol+overlayWidth,base=extractSegments(baseLine,startCol,afterStart,totalWidth-afterStart,!0),overlay=sliceWithWidth(overlayLine,0,overlayWidth,!0),beforePad=Math.max(0,startCol-base.beforeWidth),overlayPad=Math.max(0,overlayWidth-overlay.width),actualBeforeWidth=Math.max(startCol,base.beforeWidth),actualOverlayWidth=Math.max(overlayWidth,overlay.width),afterTarget=Math.max(0,totalWidth-actualBeforeWidth-actualOverlayWidth),afterPad=Math.max(0,afterTarget-base.afterWidth),result=base.before+" ".repeat(beforePad)+SEGMENT_RESET+overlay.text+" ".repeat(overlayPad)+SEGMENT_RESET+base.after+" ".repeat(afterPad);return visibleWidth(result)<=totalWidth?result:sliceByColumn(result,0,totalWidth,!0)}function hideImagesUnderOverlay(lines,overlay,viewportStart){if(overlay.height!==0)for(let index=Math.max(0,viewportStart-getMaxKittyImageRows());index<lines.length;index++){let line=lines[index],extent=getImageLineExtent(line);if(!extent)continue;let firstRow=index+extent.firstRow-viewportStart,lastRow=index+extent.lastRow-viewportStart;firstRow<overlay.row+overlay.height&&lastRow>=overlay.row&&extent.startCol<overlay.col+overlay.width&&extent.endCol>overlay.col&&(lines[index]=stripImageSequences(line))}}var VIEWPORT_TUI=Symbol.for("@draht/tui/viewport");function isViewportTUI(tui){return tui[VIEWPORT_TUI]===!0}var TuiBase=class _TuiBase extends Container{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(terminal,showHardwareCursor,logDirectory){super(),this.terminal=terminal,this.logDirectory=logDirectory,showHardwareCursor!==void 0&&(this.showHardwareCursor=showHardwareCursor)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(_options){}afterTerminalStop(_options){}getExitRestorePrefix(){return`${this.terminalColorSchemeNotificationsEnabled?"\x1B[?2031l":""}\x1B[?25h`}getExitRestoreSuffix(){return""}exitRestoreHandler=()=>{if(!this.stopped)try{this.terminal.restoreOnExit?.(this.getExitRestorePrefix(),this.getExitRestoreSuffix())}catch{}};get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(enabled){this.showHardwareCursor!==enabled&&(this.showHardwareCursor=enabled,enabled||this.hideTerminalCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(enabled){this.clearOnShrink=enabled}getFocusedComponent(){return this.focusedComponent}setFocus(component){this.setFocusInternal({component,overlayFocusRestore:"clear"})}setFocusInternal({component,overlayFocusRestore}){let previousFocus=this.focusedComponent,nextFocus=component,previousFocusedOverlay=previousFocus?this.overlayStack.find(entry=>entry.component===previousFocus&&this.isOverlayVisible(entry)):void 0,nextFocusIsOverlay=nextFocus?this.overlayStack.some(entry=>entry.component===nextFocus):!1,restoreState=this.getVisibleOverlayFocusRestore();nextFocus&&!nextFocusIsOverlay?restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?restoreState.resume.status==="focus-target"||!this.isComponentMounted(restoreState.blockedBy)?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):this.overlayFocusRestore={status:"blocked",overlay:restoreState.overlay,blockedBy:nextFocus,resume:restoreState.resume}:previousFocusedOverlay&&restoreState.status!=="inactive"&&restoreState.overlay===previousFocusedOverlay&&!this.isOverlayFocusAncestor(previousFocusedOverlay,nextFocus)&&(this.overlayFocusRestore={status:"blocked",overlay:previousFocusedOverlay,blockedBy:nextFocus,resume:{status:"restore-overlay"}}):nextFocus===null&&(restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):overlayFocusRestore==="clear"&&this.clearOverlayFocusRestore()),isFocusable(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=nextFocus,isFocusable(nextFocus)&&(nextFocus.focused=!0);let focusedOverlay=nextFocus?this.overlayStack.find(entry=>entry.component===nextFocus&&this.isOverlayVisible(entry)):void 0;focusedOverlay&&(this.overlayFocusRestore={status:"eligible",overlay:focusedOverlay})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"}}clearOverlayFocusRestoreFor(overlay){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===overlay&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(restoreState){return restoreState.resume.status==="restore-overlay"?restoreState.overlay.component:(this.clearOverlayFocusRestore(),restoreState.resume.target)}getVisibleOverlayFocusRestore(){let restoreState=this.overlayFocusRestore;return restoreState.status==="inactive"?restoreState:!this.overlayStack.includes(restoreState.overlay)||!this.isOverlayVisible(restoreState.overlay)?{status:"inactive"}:restoreState}isOverlayFocusAncestor(entry,component){let visited=new Set,current=entry.preFocus;for(;current&&!visited.has(current);){if(visited.add(current),current===component)return!0;current=this.overlayStack.find(overlay=>overlay.component===current)?.preFocus??null}return!1}retargetOverlayPreFocus(removed){for(let overlay of this.overlayStack)overlay!==removed&&overlay.preFocus===removed.component&&(overlay.preFocus=removed.preFocus)}getMountedRoots(){return this.children}isComponentMounted(component){return this.getMountedRoots().some(child=>this.containsComponent(child,component))}containsComponent(root,target){return root===target?!0:root instanceof Container?root.children.some(child=>this.containsComponent(child,target)):!1}showOverlay(component,options2){let entry={component,...options2===void 0?{}:{options:options2},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(entry),!options2?.nonCapturing&&this.isOverlayVisible(entry)&&this.setFocus(component),this.hideTerminalCursor(),this.requestRender(),{hide:()=>{let index=this.overlayStack.indexOf(entry);if(index!==-1){if(this.clearOverlayFocusRestoreFor(entry),this.retargetOverlayPreFocus(entry),this.overlayStack.splice(index,1),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}},setHidden:hidden=>{if(entry.hidden!==hidden){if(entry.hidden=hidden,hidden){if(this.clearOverlayFocusRestoreFor(entry),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}}else!options2?.nonCapturing&&this.isOverlayVisible(entry)&&(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component));this.requestRender()}},isHidden:()=>entry.hidden,focus:()=>{!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component),this.requestRender())},unfocus:unfocusOptions=>{let isFocused=this.focusedComponent===component,restoreState=this.overlayFocusRestore,hasPendingRestore=restoreState.status!=="inactive"&&restoreState.overlay===entry;if(!(!isFocused&&!hasPendingRestore)){if(restoreState.status==="blocked"&&restoreState.overlay===entry&&this.focusedComponent===restoreState.blockedBy){unfocusOptions?this.overlayFocusRestore={status:"blocked",overlay:entry,blockedBy:restoreState.blockedBy,resume:{status:"focus-target",target:unfocusOptions.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(entry),isFocused||unfocusOptions){let topVisible=this.getTopmostVisibleOverlay(),fallbackTarget=topVisible&&topVisible!==entry?topVisible.component:entry.preFocus;this.setFocus(unfocusOptions?unfocusOptions.target:fallbackTarget)}this.requestRender()}},isFocused:()=>this.focusedComponent===component,getBounds:()=>{if(!(!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||!entry.bounds))return{...entry.bounds}}}}hideOverlay(){let overlay=this.overlayStack[this.overlayStack.length-1];if(overlay){if(this.clearOverlayFocusRestoreFor(overlay),this.retargetOverlayPreFocus(overlay),this.overlayStack.pop(),this.focusedComponent===overlay.component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??overlay.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor()}hasOverlay(){return this.overlayStack.some(o=>this.isOverlayVisible(o))}isOverlayFocused(){return this.overlayStack.some(entry=>entry.component===this.focusedComponent&&this.isOverlayVisible(entry))}resolveMouseFocusTarget(component){for(let index=this.overlayStack.length-1;index>=0;index--){let overlay=this.overlayStack[index];if(this.isOverlayVisible(overlay)&&this.containsComponent(overlay.component,component))return overlay.component}return component}dispatchMouseToOverlay(event){for(let index=this.renderedOverlayLayouts.length-1;index>=0;index--){let layout=this.renderedOverlayLayouts[index];if(event.screenX<layout.col||event.screenX>=layout.col+layout.width||event.screenY<layout.row||event.screenY>=layout.row+layout.height)continue;let result=dispatchMouseEvent(layout.entry.component,{...event,x:event.screenX-layout.col,y:event.screenY-layout.row,width:layout.width,height:layout.height});return result?{hit:!0,result:result.focus?{...result,focusTarget:layout.entry.component}:result}:{hit:!0}}return{hit:!1}}isOverlayVisible(entry){return entry.hidden?!1:entry.options?.visible?entry.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let topmost;for(let overlay of this.overlayStack)overlay.options?.nonCapturing||!this.isOverlayVisible(overlay)||(!topmost||overlay.focusOrder>topmost.focusOrder)&&(topmost=overlay);return topmost}invalidate(){for(let root of this.getMountedRoots())root.invalidate();for(let overlay of this.overlayStack)overlay.component.invalidate()}start(){this.stopped=!1,process.off("exit",this.exitRestoreHandler),process.on("exit",this.exitRestoreHandler),this.beforeTerminalStart(),this.terminal.start(data=>this.handleTerminalInput(data),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.requestRender()}addInputListener(listener){return this.inputListeners.add(listener),()=>{this.inputListeners.delete(listener)}}removeInputListener(listener){this.inputListeners.delete(listener)}onTerminalColorSchemeChange(listener){return this.terminalColorSchemeListeners.add(listener),()=>{this.terminalColorSchemeListeners.delete(listener)}}setTerminalColorSchemeNotifications(enabled){this.terminalColorSchemeNotificationsEnabled!==enabled&&(this.terminalColorSchemeNotificationsEnabled=enabled,this.stopped||this.terminal.write(enabled?"\x1B[?2031h":"\x1B[?2031l"))}queryCellSize(){getCapabilities().images&&this.terminal.write("\x1B[16t")}stop(options2={}){this.stopped=!0,process.off("exit",this.exitRestoreHandler),this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(options2),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(options2)}renderNow(force=!1){force&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.lastRenderAt=performance2.now(),this.doRender()}requestRender(force=!1){if(force){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=!0,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=!0,process.nextTick(()=>{this.immediateRenderScheduled=!1,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),this.renderRequested=!1,this.lastRenderAt=performance2.now(),this.doRender())}))}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let elapsed=performance2.now()-this.lastRenderAt,delay=Math.max(0,_TuiBase.MIN_RENDER_INTERVAL_MS-elapsed);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=performance2.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},delay)}handleTerminalInput(data){if(this.consumeTerminalColorResponse(data)||this.consumeTerminalColorSchemeReport(data))return;if(this.inputListeners.size>0){let current=data;for(let listener of this.inputListeners){let result=listener(current);if(result?.consume)return;result?.data!==void 0&&(current=result.data)}if(current.length===0)return;data=current}if(this.consumeCellSizeResponse(data))return;if(matchesKey(data,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let focusedOverlay=this.overlayStack.find(o=>o.component===this.focusedComponent);if(focusedOverlay&&!this.isOverlayVisible(focusedOverlay)){let topVisible=this.getTopmostVisibleOverlay();topVisible?this.setFocus(topVisible.component):this.setFocusInternal({component:focusedOverlay.preFocus,overlayFocusRestore:"preserve"})}if(!this.overlayStack.some(o=>o.component===this.focusedComponent)){let restoreState=this.getVisibleOverlayFocusRestore();restoreState.status==="eligible"?this.setFocus(restoreState.overlay.component):restoreState.status==="blocked"&&restoreState.blockedBy!==this.focusedComponent&&(restoreState.resume.status==="restore-overlay"?this.setFocus(restoreState.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(restoreState.resume.target)))}if(this.focusedComponent?.handleInput){if(isKeyRelease(data)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(data),this.requestImmediateRender()}}consumeTerminalColorResponse(data){let query=this.pendingTerminalColorQueries[0];if(!query)return!1;if(DEVICE_ATTRIBUTES_RESPONSE_PATTERN.test(data))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(query),!0;let response=parseOscColorResponse(data);if(!response)return!1;let{target,rgb}=response,key=String(target);return!query.deliver||query.replied.has(key)||(query.replied.add(key),target==="foreground"?query.foreground=rgb:target==="background"?query.background=rgb:target<TERMINAL_PALETTE_SIZE&&(query.palette[target]=rgb),query.replied.size===TERMINAL_COLOR_REPLY_COUNT&&this.completeTerminalColorQuery(query)),!0}terminalColorQueryResult(query){let palette=query.palette.every(color=>color!==void 0)?query.palette:void 0;return{foreground:query.foreground,background:query.background,palette}}completeTerminalColorQuery(query){let deliver=query.deliver;query.deliver=void 0,clearTimeout(query.timer),deliver?.(this.terminalColorQueryResult(query))}consumeTerminalColorSchemeReport(data){let scheme=parseTerminalColorSchemeReport(data);if(!scheme)return!1;for(let listener of this.terminalColorSchemeListeners)listener(scheme);return!0}consumeCellSizeResponse(data){let match=data.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!match)return!1;let heightPx=parseInt(match[1],10),widthPx=parseInt(match[2],10);return heightPx<=0||widthPx<=0||(setCellDimensions({widthPx,heightPx}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(options2,overlayHeight,termWidth,termHeight){let opt=options2??{},margin=typeof opt.margin=="number"?{top:opt.margin,right:opt.margin,bottom:opt.margin,left:opt.margin}:opt.margin??{},marginTop=Math.max(0,margin.top??0),marginRight=Math.max(0,margin.right??0),marginBottom=Math.max(0,margin.bottom??0),marginLeft=Math.max(0,margin.left??0),availWidth=Math.max(1,termWidth-marginLeft-marginRight),availHeight=Math.max(1,termHeight-marginTop-marginBottom),width=parseSizeValue(opt.width,termWidth)??Math.min(80,availWidth);opt.minWidth!==void 0&&(width=Math.max(width,opt.minWidth)),width=Math.max(1,Math.min(width,availWidth));let maxHeight=parseSizeValue(opt.maxHeight,termHeight);maxHeight!==void 0&&(maxHeight=Math.max(1,Math.min(maxHeight,availHeight)));let effectiveHeight=maxHeight!==void 0?Math.min(overlayHeight,maxHeight):overlayHeight,row,col;if(opt.row!==void 0)if(typeof opt.row=="string"){let match=opt.row.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxRow=Math.max(0,availHeight-effectiveHeight),percent=parseFloat(match[1])/100;row=marginTop+Math.floor(maxRow*percent)}else row=this.resolveAnchorRow("center",effectiveHeight,availHeight,marginTop)}else row=opt.row;else{let anchor=opt.anchor??"center";row=this.resolveAnchorRow(anchor,effectiveHeight,availHeight,marginTop)}if(opt.col!==void 0)if(typeof opt.col=="string"){let match=opt.col.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxCol=Math.max(0,availWidth-width),percent=parseFloat(match[1])/100;col=marginLeft+Math.floor(maxCol*percent)}else col=this.resolveAnchorCol("center",width,availWidth,marginLeft)}else col=opt.col;else{let anchor=opt.anchor??"center";col=this.resolveAnchorCol(anchor,width,availWidth,marginLeft)}return opt.offsetY!==void 0&&(row+=opt.offsetY),opt.offsetX!==void 0&&(col+=opt.offsetX),row=Math.max(marginTop,Math.min(row,termHeight-marginBottom-effectiveHeight)),col=Math.max(marginLeft,Math.min(col,termWidth-marginRight-width)),{width,row,col,maxHeight}}resolveAnchorRow(anchor,height,availHeight,marginTop){switch(anchor){case"top-left":case"top-center":case"top-right":return marginTop;case"bottom-left":case"bottom-center":case"bottom-right":return marginTop+availHeight-height;case"left-center":case"center":case"right-center":return marginTop+Math.floor((availHeight-height)/2)}}resolveAnchorCol(anchor,width,availWidth,marginLeft){switch(anchor){case"top-left":case"left-center":case"bottom-left":return marginLeft;case"top-right":case"right-center":case"bottom-right":return marginLeft+availWidth-width;case"top-center":case"center":case"bottom-center":return marginLeft+Math.floor((availWidth-width)/2)}}compositeOverlays(lines,termWidth,termHeight){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],lines;let result=[...lines];for(let entry of this.overlayStack)entry.bounds=void 0;let rendered=[],minLinesNeeded=result.length,visibleEntries=this.overlayStack.filter(e=>this.isOverlayVisible(e));visibleEntries.sort((a,b)=>a.focusOrder-b.focusOrder);for(let entry of visibleEntries){let{component,options:options2}=entry,{width,maxHeight}=this.resolveOverlayLayout(options2,0,termWidth,termHeight),overlayLines=this.resolveFakeCursors(component.render(width));maxHeight!==void 0&&overlayLines.length>maxHeight&&(overlayLines=overlayLines.slice(0,maxHeight));let{row,col}=this.resolveOverlayLayout(options2,overlayLines.length,termWidth,termHeight);entry.bounds={row,col,width,height:overlayLines.length},rendered.push({entry,overlayLines,row,col,w:width}),minLinesNeeded=Math.max(minLinesNeeded,row+overlayLines.length)}this.renderedOverlayLayouts=rendered.map(({entry,row,col,w,overlayLines})=>({entry,row,col,width:w,height:overlayLines.length}));let workingHeight=Math.max(result.length,termHeight,minLinesNeeded);for(;result.length<workingHeight;)result.push("");let viewportStart=Math.max(0,workingHeight-termHeight);for(let{overlayLines,row,col,w}of rendered){hideImagesUnderOverlay(result,{row,col,width:w,height:overlayLines.length},viewportStart);for(let i=0;i<overlayLines.length;i++){let idx=viewportStart+row+i;if(idx>=0&&idx<result.length){let truncatedOverlayLine=visibleWidth(overlayLines[i])>w?sliceByColumn(overlayLines[i],0,w,!0):overlayLines[i];result[idx]=this.compositeLineAt(result[idx],truncatedOverlayLine,col,w,termWidth)}}}return result}applyLineResets(lines){let reset=SEGMENT_RESET;for(let i=0;i<lines.length;i++){let line=lines[i];isImageLine(line)||(lines[i]=normalizeTerminalOutput(line.replaceAll(CURSOR_MARKER,""))+reset)}return lines}compositeLineAt(baseLine,overlayLine,startCol,overlayWidth,totalWidth){return compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth)}extractCursorPosition(lines,height){let viewportTop=Math.max(0,lines.length-height);for(let row=lines.length-1;row>=viewportTop;row--){let line=lines[row],markerIndex=line.indexOf(CURSOR_MARKER);if(markerIndex!==-1){let beforeMarker=line.slice(0,markerIndex),col=visibleWidth(beforeMarker);return lines[row]=line.replaceAll(CURSOR_MARKER,""),{row,col}}}return null}resolveFakeCursors(lines){return lines.map(line=>line.includes(FAKE_CURSOR_START)?(this.showHardwareCursor?line.replace(FOCUSED_FAKE_CURSOR,"$1$2"):line).replaceAll(FAKE_CURSOR_START,"\x1B[7m").replaceAll(FAKE_CURSOR_END,"\x1B[27m"):line)}queryTerminalColors({timeoutMs,onLateReply}){return new Promise(resolve=>{let query={palette:Array.from({length:TERMINAL_PALETTE_SIZE},()=>{}),replied:new Set,deliver:resolve,timer:void 0};query.timer=setTimeout(()=>{query.deliver=onLateReply,resolve(this.terminalColorQueryResult(query))},timeoutMs),this.pendingTerminalColorQueries.push(query),this.terminal.write(TERMINAL_COLOR_QUERY)})}};var Box=class{children=[];paddingX;paddingY;bgFn;cache;mouseLayout;constructor(paddingX=1,paddingY=1,bgFn){this.paddingX=paddingX,this.paddingY=paddingY,this.bgFn=bgFn}addChild(component){this.children.push(component),this.invalidateCache()}removeChild(component){let index=this.children.indexOf(component);index!==-1&&(this.children.splice(index,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(bgFn){this.bgFn=bgFn}setPaddingX(paddingX){this.paddingX=paddingX,this.invalidateCache()}invalidateCache(){this.cache=void 0}matchCache(width,childLines,bgSample){let cache=this.cache;return!!cache&&cache.width===width&&cache.bgSample===bgSample&&cache.childLines.length===childLines.length&&cache.childLines.every((line,i)=>line===childLines[i])}invalidate(){this.invalidateCache();for(let child of this.children)child.invalidate?.()}handleMouse(event){let contentWidth=Math.max(1,event.width-this.paddingX*2),contentY=event.y-this.paddingY,contentX=event.x-this.paddingX;if(contentY<0||contentX<0||contentX>=contentWidth)return;let mouseChildren=this.mouseLayout?.width===contentWidth?this.mouseLayout.children:this.children.map(component=>({component,height:component.render(contentWidth).length})),childY=0;for(let{component:child,height:childHeight}of mouseChildren){if(contentY>=childY&&contentY<childY+childHeight)return dispatchMouseEvent(child,{...event,x:contentX,y:contentY-childY,width:contentWidth,height:childHeight});childY+=childHeight}}render(width){if(this.children.length===0)return[];let contentWidth=Math.max(1,width-this.paddingX*2),leftPad=" ".repeat(this.paddingX),childLines=[],mouseChildren=[];for(let child of this.children){let lines=child.render(contentWidth);mouseChildren.push({component:child,height:lines.length});for(let line of lines)childLines.push(line)}if(this.mouseLayout={width:contentWidth,children:mouseChildren},childLines.length===0)return[];let bgSample=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(width,childLines,bgSample))return this.cache.lines;let result=[];for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));for(let line of childLines)result.push(this.applyBg(leftPad+line,width));for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));return flattenLines(result),this.cache={childLines,width,bgSample,lines:result},result}applyBg(line,width){let visLen=visibleWidth(line),padNeeded=Math.max(0,width-visLen),padded=line+" ".repeat(padNeeded);return this.bgFn?this.bgFn(padded):padded}};var TUI_KEYBINDINGS={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.historyPrevious":{defaultKeys:[],description:"Select previous prompt history entry"},"tui.editor.historyNext":{defaultKeys:[],description:"Select next prompt history entry"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:["pageUp","ctrl+pageUp"],description:"Page up"},"tui.editor.pageDown":{defaultKeys:["pageDown","ctrl+pageDown"],description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:["shift+enter","ctrl+j"],description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"},"tui.altScreen.pageUp":{defaultKeys:"pageUp",description:"Scroll viewport up one page"},"tui.altScreen.pageDown":{defaultKeys:"pageDown",description:"Scroll viewport down one page"},"tui.altScreen.halfPageUp":{defaultKeys:[],description:"Scroll viewport up half a page"},"tui.altScreen.halfPageDown":{defaultKeys:[],description:"Scroll viewport down half a page"},"tui.altScreen.lineUp":{defaultKeys:[],description:"Scroll viewport up one line"},"tui.altScreen.lineDown":{defaultKeys:[],description:"Scroll viewport down one line"},"tui.altScreen.previousPrompt":{defaultKeys:["ctrl+shift+up","ctrl+up"],description:"Jump to previous semantic prompt"},"tui.altScreen.nextPrompt":{defaultKeys:["ctrl+shift+down","ctrl+down"],description:"Jump to next semantic prompt"},"tui.altScreen.search":{defaultKeys:"ctrl+shift+f",description:"Search the primary scroll view"},"tui.altScreen.searchNext":{defaultKeys:["enter","ctrl+g"],description:"Select the next search match"},"tui.altScreen.searchPrevious":{defaultKeys:["shift+enter","ctrl+shift+g"],description:"Select the previous search match"},"tui.altScreen.searchClose":{defaultKeys:"escape",description:"Close transcript search"},"tui.altScreen.top":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"ctrl+end",description:"Scroll viewport to bottom"}};function normalizeKeys(keys){if(keys===void 0)return[];let keyList=Array.isArray(keys)?keys:[keys],seen=new Set,result=[];for(let key of keyList)seen.has(key)||(seen.add(key),result.push(key));return result}var KeybindingsManager=class{definitions;userBindings;keysById=new Map;conflicts=[];constructor(definitions,userBindings={}){this.definitions=definitions,this.userBindings=userBindings,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let userClaims=new Map;for(let[keybinding,keys]of Object.entries(this.userBindings))if(keybinding in this.definitions)for(let key of normalizeKeys(keys)){let claimants=userClaims.get(key)??new Set;claimants.add(keybinding),userClaims.set(key,claimants)}for(let[key,keybindings]of userClaims)keybindings.size>1&&this.conflicts.push({key,keybindings:[...keybindings]});for(let[id,definition]of Object.entries(this.definitions)){let userKeys=this.userBindings[id],keys=normalizeKeys(userKeys===void 0?definition.defaultKeys:userKeys);this.keysById.set(id,keys)}}matches(data,keybinding){let keys=this.keysById.get(keybinding)??[];for(let key of keys)if(matchesKey(data,key))return!0;return!1}getKeys(keybinding){return[...this.keysById.get(keybinding)??[]]}getDefinition(keybinding){return this.definitions[keybinding]}getConflicts(){return this.conflicts.map(conflict=>({...conflict,keybindings:[...conflict.keybindings]}))}setUserBindings(userBindings){this.userBindings=userBindings,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let resolved={};for(let id of Object.keys(this.definitions)){let keys=this.keysById.get(id)??[];resolved[id]=keys.length===1?keys[0]:[...keys]}return resolved}},globalKeybindings=null;function setKeybindings(keybindings){globalKeybindings=keybindings}function getKeybindings(){return globalKeybindings||(globalKeybindings=new KeybindingsManager(TUI_KEYBINDINGS)),globalKeybindings}function getSelectPageIndex(keybindings,data,selectedIndex,itemCount,pageSize){let direction;if(keybindings.matches(data,"tui.select.pageUp"))direction=-1;else if(keybindings.matches(data,"tui.select.pageDown"))direction=1;else return;return Math.max(0,Math.min(itemCount-1,selectedIndex+direction*pageSize))}var Text=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(text="",paddingX=1,paddingY=1,customBgFn){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.customBgFn=customBgFn}setText(text){text!==this.text&&(this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0)}setCustomBgFn(customBgFn){this.customBgFn=customBgFn,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setPaddingX(paddingX){this.paddingX=paddingX,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;if(!this.text||this.text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=this.text.replace(/\t/g," "),paddingX=Math.min(this.paddingX,Math.max(0,Math.floor((width-1)/2))),contentWidth=Math.max(1,width-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 flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};var DEFAULT_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],DEFAULT_INTERVAL_MS=80,Loader=class extends Text{frames=[...DEFAULT_FRAMES];intervalMs=DEFAULT_INTERVAL_MS;currentFrame=0;intervalId=null;ui=null;renderIndicatorVerbatim=!1;spinnerColorFn;messageColorFn;message="Loading...";constructor(ui,spinnerColorFn,messageColorFn,message="Loading...",indicator){super("",1,0),this.ui=ui,this.spinnerColorFn=spinnerColorFn,this.messageColorFn=messageColorFn,this.message=message,this.setIndicator(indicator)}render(width){return["",...super.render(width)]}start(){this.updateDisplay(),this.restartAnimation()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}setMessage(message){this.message=message,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}setIndicator(indicator){this.renderIndicatorVerbatim=indicator!==void 0,this.frames=indicator?.frames!==void 0?[...indicator.frames]:[...DEFAULT_FRAMES],this.intervalMs=indicator?.intervalMs&&indicator.intervalMs>0?indicator.intervalMs:DEFAULT_INTERVAL_MS,this.currentFrame=0,this.start()}restartAnimation(){this.stop(),!(this.frames.length<=1)&&(this.intervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},this.intervalMs))}getRenderedIndicator(){let frame=this.frames[this.currentFrame]??"";return this.renderIndicatorVerbatim?frame:this.spinnerColorFn(frame)}updateDisplay(){let renderedFrame=this.getRenderedIndicator(),indicator=renderedFrame.length>0?`${renderedFrame} `:"";this.setText(`${indicator}${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender()}};var CancellableLoader=class extends Loader{abortController=new AbortController;onAbort;get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(data){getKeybindings().matches(data,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var KillRing=class{ring=[];push(text,opts){if(text)if(opts.accumulate&&this.ring.length>0){let last=this.ring.pop();this.ring.push(opts.prepend?text+last:last+text)}else this.ring.push(text)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let last=this.ring.pop();this.ring.unshift(last)}}get length(){return this.ring.length}};var UndoStack=class{stack=[];push(state){this.stack.push(structuredClone(state))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};var wordSegmenter2=getWordSegmenter();function findWordBackward(text,cursor,options2){if(cursor<=0)return 0;let textBeforeCursor=text.slice(0,cursor),segmentFn=options2?.segment,isAtomic=options2?.isAtomicSegment,segments=segmentFn?[...segmentFn(textBeforeCursor)]:[...wordSegmenter2.segment(textBeforeCursor)],newCursor=cursor;for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||0;if(segments.length===0)return newCursor;let last=segments[segments.length-1];if(isAtomic?.(last.segment))newCursor-=last.segment.length;else if(last.isWordLike){let segment=last.segment,matches=[...segment.matchAll(new RegExp(PUNCTUATION_REGEX,"g"))];if(matches.length<=0)newCursor-=segment.length;else{let lastMatch=matches[matches.length-1];newCursor-=segment.length-(lastMatch.index+lastMatch[0].length)}}else for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&!segments[segments.length-1]?.isWordLike&&!isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||0;return newCursor}function findWordForward(text,cursor,options2){if(cursor>=text.length)return text.length;let textAfterCursor=text.slice(cursor),segmentFn=options2?.segment,isAtomic=options2?.isAtomicSegment,iterator=(segmentFn?segmentFn(textAfterCursor):wordSegmenter2.segment(textAfterCursor))[Symbol.iterator](),next=iterator.next(),newCursor=cursor;for(;!next.done&&!isAtomic?.(next.value.segment)&&isWhitespaceChar(next.value.segment);)newCursor+=next.value.segment.length,next=iterator.next();if(next.done)return newCursor;if(isAtomic?.(next.value.segment))newCursor+=next.value.segment.length;else if(next.value.isWordLike)newCursor+=PUNCTUATION_REGEX.exec(next.value.segment)?.index??next.value.segment.length;else for(;!next.done&&!isAtomic?.(next.value.segment)&&!next.value.isWordLike&&!isWhitespaceChar(next.value.segment);)newCursor+=next.value.segment.length,next=iterator.next();return newCursor}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{capturesViewportInput=!0;items=[];filteredItems=[];selectedIndex=0;mousePressedIndex;maxVisible=5;theme;layout;onSelect;onCancel;onSelectionChange;constructor(items,maxVisible,theme2,layout={}){this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme2,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(),pageIndex=getSelectPageIndex(kb,keyData,this.selectedIndex,this.filteredItems.length,this.maxVisible);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(pageIndex!==void 0){if(this.filteredItems.length===0||pageIndex===this.selectedIndex)return;this.selectedIndex=pageIndex,this.notifySelectionChange()}else kb.matches(keyData,"tui.select.confirm")?this.confirmSelection():kb.matches(keyData,"tui.select.cancel")&&this.onCancel&&this.onCancel()}confirmSelection(){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelect&&this.onSelect(selectedItem)}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,"");if(isSelected)return this.theme.selectedText(`${prefix}${truncatedValue2}${spacing}${truncatedDesc}`);let descText=this.theme.description(spacing+truncatedDesc);return prefix+truncatedValue2+descText}}let maxWidth=width-prefixWidth-2,truncatedValue=this.truncatePrimary(item,isSelected,maxWidth,maxWidth);return isSelected?this.theme.selectedText(`${prefix}${truncatedValue}`):prefix+truncatedValue}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}};var graphemeSegmenter2=getGraphemeSegmenter(),wordSegmenter3=getWordSegmenter(),PASTE_MARKER_REGEX=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,PASTE_MARKER_SINGLE=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function isPasteMarker(segment){return segment.length>=10&&PASTE_MARKER_SINGLE.test(segment)}function segmentWithMarkers(text,baseSegmenter,validIds){if(validIds.size===0||!text.includes("[paste #"))return baseSegmenter.segment(text);let markers=[];for(let m of text.matchAll(PASTE_MARKER_REGEX)){let id=Number.parseInt(m[1],10);validIds.has(id)&&markers.push({start:m.index,end:m.index+m[0].length})}if(markers.length===0)return baseSegmenter.segment(text);let baseSegments=baseSegmenter.segment(text),result=[],markerIdx=0;for(let seg of baseSegments){for(;markerIdx<markers.length&&markers[markerIdx].end<=seg.index;)markerIdx++;let marker=markerIdx<markers.length?markers[markerIdx]:null;if(marker&&seg.index>=marker.start&&seg.index<marker.end){if(seg.index===marker.start){let markerText=text.slice(marker.start,marker.end);result.push({segment:markerText,index:marker.start,input:text})}}else result.push(seg)}return result}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(visibleWidth(line)<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],segments=preSegmented??[...graphemeSegmenter2.segment(line)],currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0;for(let i=0;i<segments.length;i++){let seg=segments[i],grapheme=seg.segment,gWidth=visibleWidth(grapheme),charIndex=seg.index,isWs=!isPasteMarker(grapheme)&&isWhitespaceChar(grapheme);if(currentWidth+gWidth>maxWidth&&(wrapOppIndex>=0&&currentWidth-wrapOppWidth+gWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<charIndex&&(chunks.push({text:line.slice(chunkStart,charIndex),startIndex:chunkStart,endIndex:charIndex}),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&&(isPasteMarker(next.segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=next.index,wrapOppWidth=currentWidth;else if(!isWs&&next&&!isWhitespaceChar(next.segment)){let isCjk=!isPasteMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isPasteMarker(next.segment)&&cjkBreakRegex.test(next.segment);(isCjk||nextIsCjk)&&(wrapOppIndex=next.index,wrapOppWidth=currentWidth)}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:line.length}),chunks}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#"],unquotedAutocompleteSuffixRegex=new RegExp(`(?:(?!${autocompleteSeparatorRegex.source}).)*`,"u"),autocompleteTokenStartSource=`${autocompleteBoundaryRegex.source}[([{<\`]*`;function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`${autocompleteTokenStartSource}(?:@"[^"]*|[${triggerCharacters.map(escapeCharacterClass).join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!=="@").map(escapeCharacterClass);return new RegExp(`${autocompleteTokenStartSource}(?:@(?:"[^"]*|${unquotedAutocompleteSuffixRegex.source})|[${escapedWithoutAt.join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function createScrollBorder(direction,hiddenLineCount,width){let availableWidth=Math.max(0,width),label=` ${direction} ${hiddenLineCount} more `,labelWidth=visibleWidth(label);if(labelWidth+2<=availableWidth){let leftWidth=Math.floor((availableWidth-labelWidth)/2);return"\u2500".repeat(leftWidth)+label+"\u2500".repeat(availableWidth-leftWidth-labelWidth)}let indicator=`\u2500\u2500\u2500 ${direction} ${hiddenLineCount} more `,remaining=availableWidth-visibleWidth(indicator);if(remaining>=0)return indicator+"\u2500".repeat(remaining);let ellipsis="...".slice(0,availableWidth),indicatorWidth=availableWidth-visibleWidth(ellipsis);return sliceByColumn(indicator,0,indicatorWidth,!0)+ellipsis}var Editor=class{state={lines:[""],cursorLine:0,cursorCol:0};focused=!1;get capturesViewportInput(){return this.autocompleteState!==null}tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];autocompleteTriggerPattern=buildTriggerPattern(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=buildDebouncePattern(this.autocompleteTriggerCharacters);autocompleteList;autocompleteState=null;autocompletePrefix="";autocompleteMaxVisible=5;autocompleteAbort;autocompleteDebounceTimer;autocompleteRequestTask=Promise.resolve();autocompleteStartToken=0;autocompleteRequestId=0;pastes=new Map;pasteCounter=0;pasteBuffer="";isInPaste=!1;history=[];historyIndex=-1;historyDraft=null;killRing=new KillRing;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new UndoStack;onSubmit;onChange;disableSubmit=!1;constructor(tui,theme2,options2={}){this.tui=tui,this.theme=theme2,this.borderColor=theme2.borderColor;let paddingX=options2.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0;let maxVisible=options2.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter3:graphemeSegmenter2,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(padding){let newPadding=Number.isFinite(padding)?Math.max(0,Math.floor(padding)):0;this.paddingX!==newPadding&&(this.paddingX=newPadding,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(maxVisible){let newMaxVisible=Number.isFinite(maxVisible)?Math.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(`
63
63
  `);this.state.lines=lines.length===0?[""]:lines,this.state.cursorLine=cursorPlacement==="start"?0:this.state.lines.length-1,this.setCursorCol(cursorPlacement==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}renderTopBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2191",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderBottomBorder(width,hiddenLineCount){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;for(let layoutLine of visibleLines){let displayText=layoutLine.text,lineVisibleWidth=visibleWidth(layoutLine.text),cursorInPadding=!1;if(layoutLine.hasCursor&&layoutLine.cursorPos!==void 0){let before=displayText.slice(0,layoutLine.cursorPos),after=displayText.slice(layoutLine.cursorPos),marker=emitCursorMarker?CURSOR_MARKER:"";if(after.length>0){let firstGrapheme=[...this.segment(after,"grapheme")][0]?.segment||"",restAfter=after.slice(firstGrapheme.length),cursor=renderFakeCursor(firstGrapheme);displayText=before+marker+cursor+restAfter}else{let cursor=renderFakeCursor(" ");displayText=before+marker+cursor,lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>contentWidth&&paddingX>0&&(cursorInPadding=!0)}}let padding=" ".repeat(Math.max(0,contentWidth-lineVisibleWidth)),lineRightPadding=cursorInPadding?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){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")||kb.matches(data,"tui.select.pageUp")||kb.matches(data,"tui.select.pageDown")){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()),this.continueCompletionAfter(selected)}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()),this.continueCompletionAfter(selected);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.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===`
64
64
  `&&data.length===1){if(this.shouldSubmitOnBackslashEnter(data,kb)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(kb.matches(data,"tui.input.submit")){if(this.disableSubmit)return;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&currentLine[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(kb.matches(data,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||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 layoutLines.push({text:"",hasCursor:!0,cursorPos:0}),layoutLines;for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",isCurrentLine=i===this.state.cursorLine;if(visibleWidth(line)<=contentWidth)isCurrentLine?layoutLines.push({text:line,hasCursor:!0,cursorPos:this.state.cursorCol}):layoutLines.push({text:line,hasCursor:!1});else{let chunks=wordWrapLine(line,contentWidth,[...this.segment(line,"grapheme")]);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}):layoutLines.push({text:chunk.text,hasCursor:!1})}}}return layoutLines}getText(){return this.state.lines.join(`
65
65
  `)}expandPasteMarkers(text){let result=text;for(let[pasteId,pasteContent]of this.pastes){let markerRegex=new RegExp(`\\[paste #${pasteId}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");result=result.replace(markerRegex,()=>pasteContent)}return result}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(`
@@ -69,7 +69,7 @@ Please report this to https://github.com/markedjs/marked.`,silent){let msg="<p>A
69
69
  `),currentLine=this.state.lines[this.state.cursorLine]||"",beforeCursor=currentLine.slice(0,this.state.cursorCol),afterCursor=currentLine.slice(this.state.cursorCol);insertedLines.length===1?(this.state.lines[this.state.cursorLine]=beforeCursor+normalized+afterCursor,this.setCursorCol(this.state.cursorCol+normalized.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),beforeCursor+insertedLines[0],...insertedLines.slice(1,-1),insertedLines[insertedLines.length-1]+afterCursor,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=insertedLines.length-1,this.setCursorCol((insertedLines[insertedLines.length-1]||"").length)),this.onChange&&this.onChange(this.getText())}insertCharacter(char,skipUndoCoalescing){this.exitHistoryBrowsing(),skipUndoCoalescing||((isWhitespaceChar(char)||this.lastAction!=="type-word")&&this.pushUndoSnapshot(),this.lastAction="type-word");let line=this.state.lines[this.state.cursorLine]||"",before=line.slice(0,this.state.cursorCol),after=line.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=before+char+after,this.setCursorCol(this.state.cursorCol+char.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(char==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(char)||cjkBreakRegex.test(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}handlePaste(pastedText){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let decodedText=pastedText.replace(/\x1b\[(\d+);5u/g,(match,code)=>{let cp=Number(code);return cp>=97&&cp<=122?String.fromCharCode(cp-96):cp>=65&&cp<=90?String.fromCharCode(cp-64):match}),filteredText=this.normalizeText(decodedText).split("").filter(char=>char===`
70
70
  `||char.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(filteredText)){let currentLine=this.state.lines[this.state.cursorLine]||"",charBeforeCursor=this.state.cursorCol>0?currentLine[this.state.cursorCol-1]:"";charBeforeCursor&&/\w/.test(charBeforeCursor)&&(filteredText=` ${filteredText}`)}let pastedLines=filteredText.split(`
71
71
  `),totalChars=filteredText.length;if(pastedLines.length>10||totalChars>1e3){this.pasteCounter++;let pasteId=this.pasteCounter;this.pastes.set(pasteId,filteredText);let marker=pastedLines.length>10?`[paste #${pasteId} +${pastedLines.length} lines]`:`[paste #${pasteId} ${totalChars} chars]`;this.insertTextAtCursorInternal(marker);return}if(pastedLines.length===1){this.insertTextAtCursorInternal(filteredText);return}this.insertTextAtCursorInternal(filteredText)}addNewLine(){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before,this.state.lines.splice(this.state.cursorLine+1,0,after),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(data,kb){if(this.disableSubmit||!matchesKey(data,"enter"))return!1;let submitKeys=kb.getKeys("tui.input.submit");if(!(submitKeys.includes("shift+enter")||submitKeys.includes("shift+return")))return!1;let currentLine=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&currentLine[this.state.cursorCol-1]==="\\"}submitValue(){this.cancelAutocomplete();let result=this.expandPasteMarkers(this.state.lines.join(`
72
- `)).trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(result)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let line=this.state.lines[this.state.cursorLine]||"",beforeCursor=line.slice(0,this.state.cursorCol),graphemes=[...this.segment(beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.length-1],graphemeLength=lastGrapheme?lastGrapheme.segment.length:1,isPastedSegmented=PASTE_MARKER_SINGLE.exec(lastGrapheme.segment);if(isPastedSegmented){let targetId=Number(isPastedSegmented[1]);this.pastes.delete(targetId),this.pasteCounter--;let higherIds=[...this.pastes.keys()].filter(id=>id>targetId).sort((a,b)=>a-b);for(let id of higherIds)this.pastes.set(id-1,this.pastes.get(id)),this.pastes.delete(id);this.state.lines=this.state.lines.map(line2=>line2.replace(PASTE_MARKER_REGEX,(fullMatch,idGroup,suffixGroup)=>{let x=Number(idGroup);return x<=targetId?fullMatch:`[paste #${x-1}${suffixGroup}]`}))}line=this.state.lines[this.state.cursorLine]||"";let before=line.slice(0,this.state.cursorCol-graphemeLength),after=line.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-graphemeLength)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let currentLine=this.state.lines[this.state.cursorLine]||"",previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}setCursorCol(col){this.state.cursorCol=col,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(visualLines,currentVisualLine,targetVisualLine){let currentVL=visualLines[currentVisualLine],targetVL=visualLines[targetVisualLine];if(!(currentVL&&targetVL))return;let currentVisualCol;if(this.snappedFromCursorCol!==null){let vlIndex=this.findVisualLineAt(visualLines,currentVL.logicalLine,this.snappedFromCursorCol);currentVisualCol=this.snappedFromCursorCol-visualLines[vlIndex].startCol}else currentVisualCol=this.state.cursorCol-currentVL.startCol;let sourceMaxVisualCol=currentVisualLine===visualLines.length-1||visualLines[currentVisualLine+1]?.logicalLine!==currentVL.logicalLine?currentVL.length:Math.max(0,currentVL.length-1),targetMaxVisualCol=targetVisualLine===visualLines.length-1||visualLines[targetVisualLine+1]?.logicalLine!==targetVL.logicalLine?targetVL.length:Math.max(0,targetVL.length-1),moveToVisualCol=this.computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol);this.state.cursorLine=targetVL.logicalLine;let targetCol=targetVL.startCol+moveToVisualCol,logicalLine=this.state.lines[targetVL.logicalLine]||"";this.state.cursorCol=Math.min(targetCol,logicalLine.length);let segments=[...this.segment(logicalLine,"grapheme")];for(let seg of segments){if(seg.index>this.state.cursorCol)break;if(!(seg.segment.length<=1)&&this.state.cursorCol<seg.index+seg.segment.length){let isContinuation=seg.index<targetVL.startCol,isMovingDown=targetVisualLine>currentVisualLine;if(isContinuation&&isMovingDown){let segEnd=seg.index+seg.segment.length,next=targetVisualLine+1;for(;next<visualLines.length&&visualLines[next].logicalLine===targetVL.logicalLine&&visualLines[next].startCol<segEnd;)next++;if(next<visualLines.length){this.moveToVisualLine(visualLines,currentVisualLine,next);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=seg.index;return}}this.snappedFromCursorCol=null}computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol){let hasPreferred=this.preferredVisualCol!==null,cursorInMiddle=currentVisualCol<sourceMaxVisualCol,targetTooShort=targetMaxVisualCol<currentVisualCol;if(!hasPreferred||cursorInMiddle)return targetTooShort?(this.preferredVisualCol=currentVisualCol,targetMaxVisualCol):(this.preferredVisualCol=null,currentVisualCol);let targetCantFitPreferred=targetMaxVisualCol<this.preferredVisualCol;if(targetTooShort||targetCantFitPreferred)return targetMaxVisualCol;let result=this.preferredVisualCol;return this.preferredVisualCol=null,result}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(currentLine.length)}deleteToStartOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let deletedText=currentLine.slice(0,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
72
+ `)).trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(result)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let line=this.state.lines[this.state.cursorLine]||"",beforeCursor=line.slice(0,this.state.cursorCol),graphemes=[...this.segment(beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.length-1],graphemeLength=lastGrapheme?lastGrapheme.segment.length:1,isPastedSegmented=PASTE_MARKER_SINGLE.exec(lastGrapheme.segment);if(isPastedSegmented){let targetId=Number(isPastedSegmented[1]);this.pastes.delete(targetId),this.pasteCounter--;let higherIds=[...this.pastes.keys()].filter(id=>id>targetId).sort((a,b)=>a-b);for(let id of higherIds)this.pastes.set(id-1,this.pastes.get(id)),this.pastes.delete(id);this.state.lines=this.state.lines.map(line2=>line2.replace(PASTE_MARKER_REGEX,(fullMatch,idGroup,suffixGroup)=>{let x=Number(idGroup);return x<=targetId?fullMatch:`[paste #${x-1}${suffixGroup??""}]`}))}line=this.state.lines[this.state.cursorLine]||"";let before=line.slice(0,this.state.cursorCol-graphemeLength),after=line.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-graphemeLength)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let currentLine=this.state.lines[this.state.cursorLine]||"",previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}setCursorCol(col){this.state.cursorCol=col,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(visualLines,currentVisualLine,targetVisualLine){let currentVL=visualLines[currentVisualLine],targetVL=visualLines[targetVisualLine];if(!(currentVL&&targetVL))return;let currentVisualCol;if(this.snappedFromCursorCol!==null){let vlIndex=this.findVisualLineAt(visualLines,currentVL.logicalLine,this.snappedFromCursorCol);currentVisualCol=this.snappedFromCursorCol-visualLines[vlIndex].startCol}else currentVisualCol=this.state.cursorCol-currentVL.startCol;let sourceMaxVisualCol=currentVisualLine===visualLines.length-1||visualLines[currentVisualLine+1]?.logicalLine!==currentVL.logicalLine?currentVL.length:Math.max(0,currentVL.length-1),targetMaxVisualCol=targetVisualLine===visualLines.length-1||visualLines[targetVisualLine+1]?.logicalLine!==targetVL.logicalLine?targetVL.length:Math.max(0,targetVL.length-1),moveToVisualCol=this.computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol);this.state.cursorLine=targetVL.logicalLine;let targetCol=targetVL.startCol+moveToVisualCol,logicalLine=this.state.lines[targetVL.logicalLine]||"";this.state.cursorCol=Math.min(targetCol,logicalLine.length);let segments=[...this.segment(logicalLine,"grapheme")];for(let seg of segments){if(seg.index>this.state.cursorCol)break;if(!(seg.segment.length<=1)&&this.state.cursorCol<seg.index+seg.segment.length){let isContinuation=seg.index<targetVL.startCol,isMovingDown=targetVisualLine>currentVisualLine;if(isContinuation&&isMovingDown){let segEnd=seg.index+seg.segment.length,next=targetVisualLine+1;for(;next<visualLines.length&&visualLines[next].logicalLine===targetVL.logicalLine&&visualLines[next].startCol<segEnd;)next++;if(next<visualLines.length){this.moveToVisualLine(visualLines,currentVisualLine,next);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=seg.index;return}}this.snappedFromCursorCol=null}computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol){let hasPreferred=this.preferredVisualCol!==null,cursorInMiddle=currentVisualCol<sourceMaxVisualCol,targetTooShort=targetMaxVisualCol<currentVisualCol;if(!hasPreferred||cursorInMiddle)return targetTooShort?(this.preferredVisualCol=currentVisualCol,targetMaxVisualCol):(this.preferredVisualCol=null,currentVisualCol);let targetCantFitPreferred=targetMaxVisualCol<this.preferredVisualCol;if(targetTooShort||targetCantFitPreferred)return targetMaxVisualCol;let result=this.preferredVisualCol;return this.preferredVisualCol=null,result}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(currentLine.length)}deleteToStartOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let deletedText=currentLine.slice(0,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
73
73
  `,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.length){this.pushUndoSnapshot();let deletedText=currentLine.slice(this.state.cursorCol);this.killRing.push(deletedText,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
74
74
  `,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
75
75
  `,{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(`
@@ -89,7 +89,8 @@ Please report this to https://github.com/markedjs/marked.`,silent){let msg="<p>A
89
89
  `)?void 0:{type:"latex",raw:source.slice(0,closingIndex+closing.length),text}}var TABLE_DELIMITER_ROW_REGEX=/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;function containsTableStart(source){let lines=source.split(`
90
90
  `);for(let index=0;index<lines.length-1;index++){let delimiterRow=lines[index+1];if((delimiterRow.includes("|")||lines[index].includes("|"))&&TABLE_DELIMITER_ROW_REGEX.test(delimiterRow))return!0}return!1}function tokenizeBlockLatex(source){let dollarMatch=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source);if(dollarMatch?.[1]&&!containsTableStart(dollarMatch[1]))return{type:"latexBlock",raw:dollarMatch[0],text:dollarMatch[1].trim()};let bracketMatch=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(source);if(bracketMatch?.[1]&&!containsTableStart(bracketMatch[1]))return{type:"latexBlock",raw:bracketMatch[0],text:bracketMatch[1].trim()};let pendingBracket=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(source);if(pendingBracket?.[1]&&!containsTableStart(pendingBracket[1]))return{type:"latexBlock",raw:pendingBracket[0],text:pendingBracket[1],pending:!0};let pendingDollar=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source);if(pendingDollar?.[1]&&looksLikePendingDollarMath(pendingDollar[1])&&!containsTableStart(pendingDollar[1]))return{type:"latexBlock",raw:pendingDollar[0],text:pendingDollar[1],pending:!0}}var LATEX_MARKDOWN_EXTENSIONS=[{name:"latexBlock",level:"block",start(source){let match=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source);return match?match.index+(match[0].startsWith(`
91
91
  `)?1:0):void 0},tokenizer:tokenizeBlockLatex},{name:"latex",level:"inline",start(source){let indices=[source.indexOf("$"),source.indexOf("\\("),source.indexOf("\\[")].filter(index=>index>=0);return indices.length>0?Math.min(...indices):void 0},tokenizer:tokenizeInlineLatex}];function trimPartialClosingFences(tokens){let token=tokens[tokens.length-1];if(token?.type==="list"){trimPartialClosingFences(token.items[token.items.length-1]?.tokens??[]);return}if(token?.type==="blockquote"){trimPartialClosingFences(token.tokens??[]);return}if(token?.type!=="code")return;let marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1],lastLine=token.raw.split(`
92
- `).pop();!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)||(token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,""))}var HTML_COMMENT_REGEX=/<!--[\s\S]*?(?:-->|$)/g;function stripHtmlComments(html2){return html2.replace(HTML_COMMENT_REGEX,"")}function removeHtmlCommentBlocks(tokens){for(let i=tokens.length-1;i>=0;i--){let token=tokens[i];if(token.type==="list")for(let item of token.items)removeHtmlCommentBlocks(item.tokens);else token.type==="blockquote"?removeHtmlCommentBlocks(token.tokens??[]):token.type==="html"&&stripHtmlComments(token.raw).trim()===""&&(tokens.splice(i,1),tokens[i]?.type==="space"&&(i===0||tokens[i-1]?.type==="space")?tokens.splice(i,1):i===tokens.length&&tokens[i-1]?.type==="space"&&tokens.splice(--i,1))}}var markdownParser=new Marked;markdownParser.setOptions({tokenizer:new MarkdownTokenizer});markdownParser.use({tokenizer:{emStrong:markedCjkFriendly().tokenizer?.emStrong},extensions:[...LATEX_MARKDOWN_EXTENSIONS]});var Markdown=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;cachedTokens;blocks;blockHighlightedCode;constructor(text,paddingX,paddingY,theme2,defaultTextStyle,options2){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.theme=theme2,this.defaultTextStyle=defaultTextStyle,this.options=options2?{...options2}:{}}setText(text){this.text=text,this.clearRenderCache()}invalidate(){this.clearRenderCache(),this.blocks=void 0,this.defaultStylePrefix=void 0}clearRenderCache(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;let contentWidth=Math.max(1,width-this.paddingX*2),text=this.options.transform?.(this.text,contentWidth)??this.text;if(!text||text.trim()===""){this.blocks=void 0;let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=text.replace(/\t/g," "),cached=this.cachedTokens?.deref(),tokens=cached?.source===normalizedText?cached.tokens:void 0;tokens||(tokens=markdownParser.lexer(normalizedText),trimPartialClosingFences(tokens),removeHtmlCommentBlocks(tokens),this.cachedTokens=new WeakRef({source:normalizedText,tokens}));let reuseBlocks=Object.keys(tokens.links).length===0,previousBlocks=this.blocks?.deref(),blocks=new Map;this.blocks=new WeakRef(blocks);let contentLines=[];for(let i=0;i<tokens.length;i++){let token=tokens[i],nextTokenType=tokens[i+1]?.type,block2=(reuseBlocks?blocks.get(token.raw)??previousBlocks?.get(token.raw):void 0)??{width:-1,nextTokenType,lines:[],highlightedCode:new Map};(block2.width!==width||block2.nextTokenType!==nextTokenType)&&this.renderBlock(block2,token,nextTokenType,width,contentWidth),reuseBlocks&&blocks.set(token.raw,block2);for(let line of block2.lines)contentLines.push(line)}let bgFn=this.defaultTextStyle?.bgColor,emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=bgFn?applyBackgroundToLine(emptyLine,width,bgFn):emptyLine;emptyLines.push(line)}flattenLines(emptyLines);let result=emptyLines.concat(contentLines,emptyLines);return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}renderBlock(block2,token,nextTokenType,width,contentWidth){this.blockHighlightedCode=block2.highlightedCode;let leftMargin=" ".repeat(this.paddingX),rightMargin=" ".repeat(this.paddingX),bgFn=this.defaultTextStyle?.bgColor,lines=[];for(let line of this.renderToken(token,contentWidth,nextTokenType)){if(isImageLine(line)){lines.push(line);continue}for(let wrappedLine of wrapTextWithAnsi(line,contentWidth)){let lineWithMargins=leftMargin+wrappedLine+rightMargin;if(bgFn)lines.push(applyBackgroundToLine(lineWithMargins,width,bgFn));else{let paddingNeeded=Math.max(0,width-visibleWidth(lineWithMargins));lines.push(lineWithMargins+" ".repeat(paddingNeeded))}}}this.blockHighlightedCode=void 0,flattenLines(lines),block2.lines=lines,block2.width=width,block2.nextTokenType=nextTokenType}applyDefaultStyle(text){if(!this.defaultTextStyle)return text;let styled=text;return this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled)),styled}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let sentinel="\0",styled=sentinel;this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled));let sentinelIndex=styled.indexOf(sentinel);return this.defaultStylePrefix=sentinelIndex>=0?styled.slice(0,sentinelIndex):"",this.defaultStylePrefix}getStylePrefix(styleFn){let styled=styleFn("\0"),sentinelIndex=styled.indexOf("\0");return sentinelIndex>=0?styled.slice(0,sentinelIndex):""}getDefaultInlineStyleContext(){return{applyText:text=>this.applyDefaultStyle(text),stylePrefix:this.getDefaultStylePrefix()}}renderToken(token,width,nextTokenType,styleContext){let lines=[];switch(token.type){case"heading":{let headingLevel=token.depth,headingPrefix=`${"#".repeat(headingLevel)} `,headingStyleFn;headingLevel===1?headingStyleFn=text=>this.theme.heading(this.theme.bold(this.theme.underline(text))):headingStyleFn=text=>this.theme.heading(this.theme.bold(text));let headingStyleContext={applyText:headingStyleFn,stylePrefix:this.getStylePrefix(headingStyleFn)},headingText=this.renderInlineTokens(token.tokens||[],headingStyleContext),styledHeading=headingLevel>=3?headingStyleFn(headingPrefix)+headingText:headingText;lines.push(styledHeading),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"paragraph":{let paragraphText=this.renderInlineTokens(token.tokens||[],styleContext);lines.push(paragraphText),nextTokenType&&nextTokenType!=="list"&&nextTokenType!=="space"&&lines.push("");break}case"text":lines.push(this.renderInlineTokens([token],styleContext));break;case"latexBlock":{let latexToken=token,rendered=!latexToken.pending&&this.options.renderLatex!==!1?renderLatex(latexToken.text,{display:!0}):void 0;(rendered===void 0||rendered.split(`
92
+ `).pop();!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)||(token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,""))}var HTML_COMMENT_REGEX=/<!--[\s\S]*?(?:-->|$)/g;function stripHtmlComments(html2){return html2.replace(HTML_COMMENT_REGEX,"")}function removeHtmlCommentBlocks(tokens){for(let i=tokens.length-1;i>=0;i--){let token=tokens[i];if(token.type==="list")for(let item of token.items)removeHtmlCommentBlocks(item.tokens);else token.type==="blockquote"?removeHtmlCommentBlocks(token.tokens??[]):token.type==="html"&&stripHtmlComments(token.raw).trim()===""&&(tokens.splice(i,1),tokens[i]?.type==="space"&&(i===0||tokens[i-1]?.type==="space")?tokens.splice(i,1):i===tokens.length&&tokens[i-1]?.type==="space"&&tokens.splice(--i,1))}}var markdownParser=new Marked;markdownParser.setOptions({tokenizer:new MarkdownTokenizer});markdownParser.use({tokenizer:{emStrong:markedCjkFriendly().tokenizer?.emStrong},extensions:[...LATEX_MARKDOWN_EXTENSIONS]});var Markdown=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;cachedTokens;blocks;blockHighlightedCode;constructor(text,paddingX,paddingY,theme2,defaultTextStyle,options2){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.theme=theme2,this.defaultTextStyle=defaultTextStyle,this.options=options2?{...options2}:{}}setText(text){this.text=text,this.clearRenderCache()}invalidate(){this.clearRenderCache(),this.blocks=void 0,this.defaultStylePrefix=void 0}clearRenderCache(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;let contentWidth=Math.max(1,width-this.paddingX*2),text=this.options.transform?.(this.text,contentWidth)??this.text;if(!text||text.trim()===""){this.blocks=void 0;let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=text.replace(/\t/g," "),cached=this.cachedTokens?.deref(),tokens=cached?.source===normalizedText?cached.tokens:void 0;tokens||(tokens=markdownParser.lexer(normalizedText),trimPartialClosingFences(tokens),removeHtmlCommentBlocks(tokens),this.cachedTokens=new WeakRef({source:normalizedText,tokens}));let reuseBlocks=Object.keys(tokens.links).length===0,previousBlocks=this.blocks?.deref(),blocks=new Map;this.blocks=new WeakRef(blocks);let contentLines=[];for(let i=0;i<tokens.length;i++){let token=tokens[i],nextTokenType=tokens[i+1]?.type,block2=(reuseBlocks?blocks.get(token.raw)??previousBlocks?.get(token.raw):void 0)??{width:-1,nextTokenType,lines:[],highlightedCode:new Map};(block2.width!==width||block2.nextTokenType!==nextTokenType)&&this.renderBlock(block2,token,nextTokenType,width,contentWidth),reuseBlocks&&blocks.set(token.raw,block2);for(let line of block2.lines)contentLines.push(line)}let bgFn=this.defaultTextStyle?.bgColor,emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=bgFn?applyBackgroundToLine(emptyLine,width,bgFn):emptyLine;emptyLines.push(line)}flattenLines(emptyLines);let result=emptyLines.concat(contentLines,emptyLines);return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}renderBlock(block2,token,nextTokenType,width,contentWidth){this.blockHighlightedCode=block2.highlightedCode;let leftMargin=" ".repeat(this.paddingX),rightMargin=" ".repeat(this.paddingX),bgFn=this.defaultTextStyle?.bgColor,lines=[],tokenLines=this.renderToken(token,contentWidth,nextTokenType).flatMap(line=>isImageLine(line)?line.split(`
93
+ `):[line]);for(let line of tokenLines){if(isImageLine(line)){lines.push(line);continue}for(let wrappedLine of wrapTextWithAnsi(line,contentWidth)){let lineWithMargins=leftMargin+wrappedLine+rightMargin;if(bgFn)lines.push(applyBackgroundToLine(lineWithMargins,width,bgFn));else{let paddingNeeded=Math.max(0,width-visibleWidth(lineWithMargins));lines.push(lineWithMargins+" ".repeat(paddingNeeded))}}}this.blockHighlightedCode=void 0,flattenLines(lines),block2.lines=lines,block2.width=width,block2.nextTokenType=nextTokenType}applyDefaultStyle(text){if(!this.defaultTextStyle)return text;let styled=text;return this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled)),styled}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let sentinel="\0",styled=sentinel;this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled));let sentinelIndex=styled.indexOf(sentinel);return this.defaultStylePrefix=sentinelIndex>=0?styled.slice(0,sentinelIndex):"",this.defaultStylePrefix}getStylePrefix(styleFn){let styled=styleFn("\0"),sentinelIndex=styled.indexOf("\0");return sentinelIndex>=0?styled.slice(0,sentinelIndex):""}getDefaultInlineStyleContext(){return{applyText:text=>this.applyDefaultStyle(text),stylePrefix:this.getDefaultStylePrefix()}}renderToken(token,width,nextTokenType,styleContext){let lines=[];switch(token.type){case"heading":{let headingLevel=token.depth,headingPrefix=`${"#".repeat(headingLevel)} `,headingStyleFn;headingLevel===1?headingStyleFn=text=>this.theme.heading(this.theme.bold(this.theme.underline(text))):headingStyleFn=text=>this.theme.heading(this.theme.bold(text));let headingStyleContext={applyText:headingStyleFn,stylePrefix:this.getStylePrefix(headingStyleFn)},headingText=this.renderInlineTokens(token.tokens||[],headingStyleContext),styledHeading=headingLevel>=3?headingStyleFn(headingPrefix)+headingText:headingText;lines.push(styledHeading),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"paragraph":{let paragraphText=this.renderInlineTokens(token.tokens||[],styleContext);lines.push(paragraphText),nextTokenType&&nextTokenType!=="list"&&nextTokenType!=="space"&&lines.push("");break}case"text":lines.push(this.renderInlineTokens([token],styleContext));break;case"latexBlock":{let latexToken=token,rendered=!latexToken.pending&&this.options.renderLatex!==!1?renderLatex(latexToken.text,{display:!0}):void 0;(rendered===void 0||rendered.split(`
93
94
  `).some(line=>visibleWidth(line)>width))&&(rendered=latexToken.raw.trim());for(let line of rendered.split(`
94
95
  `))lines.push(this.applyDefaultStyle(line));nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"code":{let indent=this.theme.codeBlockIndent??" ";if(lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang||""}`)),this.theme.highlightCode){let key=`${token.lang??""}\0${token.text}`,highlighted=this.blockHighlightedCode?.get(key);highlighted||(highlighted=this.theme.highlightCode(token.text,token.lang),this.blockHighlightedCode?.set(key,highlighted));for(let hlLine of highlighted)lines.push(`${indent}${hlLine}`)}else{let codeLines=token.text.split(`
95
96
  `);for(let codeLine of codeLines)lines.push(`${indent}${this.theme.codeBlock(codeLine)}`)}lines.push(this.theme.codeBlockBorder("```")),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"list":{let listLines=this.renderList(token,0,width,styleContext);lines.push(...listLines);break}case"table":{let tableLines=this.renderTable(token,width,nextTokenType,styleContext);lines.push(...tableLines);break}case"blockquote":{let quoteStyle=text=>this.theme.quote(this.theme.italic(text)),quoteStylePrefix=this.getStylePrefix(quoteStyle),applyQuoteStyle=line=>{if(!quoteStylePrefix)return quoteStyle(line);let lineWithReappliedStyle=line.replace(/\x1b\[0m/g,`\x1B[0m${quoteStylePrefix}`);return quoteStyle(lineWithReappliedStyle)};if(width<3){let quoteTokens2=token.tokens||[];for(let i=0;i<quoteTokens2.length;i++)for(let line of this.renderToken(quoteTokens2[i],width,quoteTokens2[i+1]?.type,styleContext))lines.push(line);break}let quoteContentWidth=width-2,quoteInlineStyleContext={applyText:text=>text,stylePrefix:quoteStylePrefix},quoteTokens=token.tokens||[],renderedQuoteLines=[];for(let i=0;i<quoteTokens.length;i++){let quoteToken=quoteTokens[i],nextQuoteToken=quoteTokens[i+1];for(let line of this.renderToken(quoteToken,quoteContentWidth,nextQuoteToken?.type,quoteInlineStyleContext))renderedQuoteLines.push(line)}for(;renderedQuoteLines.length>0&&renderedQuoteLines[renderedQuoteLines.length-1]==="";)renderedQuoteLines.pop();for(let quoteLine of renderedQuoteLines){let styledLine=applyQuoteStyle(quoteLine),wrappedLines=wrapTextWithAnsi(styledLine,quoteContentWidth);for(let wrappedLine of wrappedLines)lines.push(this.theme.quoteBorder("\u2502 ")+wrappedLine)}nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"hr":lines.push(this.theme.hr("\u2500".repeat(Math.min(width,80)))),nextTokenType&&nextTokenType!=="space"&&lines.push("");break;case"html":"raw"in token&&typeof token.raw=="string"&&lines.push(this.applyDefaultStyle(stripHtmlComments(token.raw).trim()));break;case"space":lines.push("");break;default:"text"in token&&typeof token.text=="string"&&lines.push(token.text)}return lines}renderInlineTokens(tokens,styleContext){let result="",resolvedStyleContext=styleContext??this.getDefaultInlineStyleContext(),{applyText,stylePrefix}=resolvedStyleContext,applyTextWithNewlines=text=>text.split(`
@@ -99,7 +100,7 @@ Please report this to https://github.com/markedjs/marked.`,silent){let msg="<p>A
99
100
  `);newlineIndex!==-1&&(singleLineText=this.text.substring(0,newlineIndex));let displayText=truncateToWidth(singleLineText,availableWidth),leftPadding=" ".repeat(this.paddingX),rightPadding=" ".repeat(this.paddingX),lineWithPadding=leftPadding+displayText+rightPadding,lineVisibleWidth=visibleWidth(lineWithPadding),paddingNeeded=Math.max(0,width-lineVisibleWidth),finalLine=lineWithPadding+" ".repeat(paddingNeeded);result.push(finalLine);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);return result}};var VStack=class extends Stack{layoutType="vstack";constructor(children=[],options2={}){super(children,options2)}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}};import{createRequire as createRequire2}from"node:module";import*as path from"node:path";import{createRequire}from"node:module";import{dirname as dirname2,join as join2}from"node:path";import{fileURLToPath}from"node:url";var moduleRequire=createRequire(import.meta.url),TUI_PACKAGE_NAME="@draht/tui";function getNativeModuleCandidates(nativePath,options2={}){let moduleDir=dirname2(fileURLToPath(options2.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=(options2.resolvePackage??moduleRequire.resolve)(TUI_PACKAGE_NAME);candidates.push(join2(dirname2(packageEntry),"..",nativePath))}catch{}return candidates.push(join2(moduleDir,"..",nativePath),join2(moduleDir,nativePath),join2(dirname2(options2.execPath??process.execPath),nativePath)),Array.from(new Set(candidates))}var cjsRequire=createRequire2(import.meta.url),helpers=new Map;function loadNativePlatformHelper(platform,suffix=""){let arch=process.arch;if(arch!=="x64"&&arch!=="arm64")return;let nativePath=path.join("native",platform,"prebuilds",`${platform}-${arch}`,`${platform}-platform${suffix}.node`);if(helpers.has(nativePath))return helpers.get(nativePath);for(let modulePath of getNativeModuleCandidates(nativePath))try{let helper=cjsRequire(modulePath);if(typeof helper?.getText=="function"&&typeof helper.getImage=="function")return helpers.set(nativePath,helper),helper}catch{}helpers.set(nativePath,void 0)}function getNativePlatformHelper(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return loadNativePlatformHelper(process.platform)}function getNativeClipboard(){if(process.platform!=="linux")return getNativePlatformHelper();if(process.env.DISPLAY)return loadNativePlatformHelper("linux","-x11")}var PROGRAM_STATUS_QUERY="\x1B]7501;?\x1B\\";function isProgramStatusReply(sequence){return/^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(sequence)}var APP_PATTERN=/^[A-Za-z0-9_.+-]{1,32}$/,MAX_MESSAGE_BYTES=2048;function truncateUtf8(text,maxBytes){if(Buffer.byteLength(text,"utf8")<=maxBytes)return text;let bytes=0,end=0;for(let char of text){let size=Buffer.byteLength(char,"utf8");if(bytes+size>maxBytes)break;bytes+=size,end+=char.length}return text.slice(0,end)}function formatProgramStatus(status){let pairs=[`state=${status.state}`];status.app!==void 0&&APP_PATTERN.test(status.app)&&pairs.push(`app=${status.app}`),status.state==="blocked"&&status.kind&&pairs.push(`kind=${status.kind}`);let message=truncateUtf8(replaceControlCharacters(status.message??"").trim(),MAX_MESSAGE_BYTES);return message&&pairs.push(`msg=${Buffer.from(message,"utf8").toString("base64")}`),`\x1B]7501;${pairs.join(":")}\x1B\\`}import{EventEmitter}from"events";var ESC="\x1B",DEFAULT_SEQUENCE_TIMEOUT_MS=50,DEFAULT_ESCAPE_TIMEOUT_MS=10,BRACKETED_PASTE_START="\x1B[200~",BRACKETED_PASTE_END="\x1B[201~",TERMINAL_REPLY_HEADER_PATTERN=/^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;function isControlString(data){return data.startsWith(`${ESC}]`)||data.startsWith(`${ESC}P`)||data.startsWith(`${ESC}_`)}function isCompleteSequence(data){if(!data.startsWith(ESC))return"not-escape";if(data.length===1)return"incomplete";let afterEsc=data.slice(1);return afterEsc.startsWith("[")?afterEsc.startsWith("[M")?data.length>=6?"complete":"incomplete":isCompleteCsiSequence(data):afterEsc.startsWith("]")?isCompleteOscSequence(data):afterEsc.startsWith("P")?isCompleteDcsSequence(data):afterEsc.startsWith("_")?isCompleteApcSequence(data):afterEsc.startsWith("O")?afterEsc.length>=2?"complete":"incomplete":(afterEsc.length===1,"complete")}function isCompleteCsiSequence(data){if(!data.startsWith(`${ESC}[`))return"complete";if(data.length<3)return"incomplete";let payload=data.slice(2),lastChar=payload[payload.length-1],lastCharCode=lastChar.charCodeAt(0);if(lastCharCode>=64&&lastCharCode<=126){if(payload.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(payload))return"complete";if(lastChar==="M"||lastChar==="m"){let parts=payload.slice(1,-1).split(";");if(parts.length===3&&parts.every(p=>/^\d+$/.test(p)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function isCompleteOscSequence(data){return!data.startsWith(`${ESC}]`)||data.endsWith(`${ESC}\\`)||data.endsWith("\x07")?"complete":"incomplete"}function isCompleteDcsSequence(data){return!data.startsWith(`${ESC}P`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function isCompleteApcSequence(data){return!data.startsWith(`${ESC}_`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function parseUnmodifiedKittyPrintableCodepoint(sequence){let match=sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!match)return;let codepoint=parseInt(match[1],10);return codepoint>=32?codepoint:void 0}function extractCompleteSequences(buffer){let sequences=[],pos=0;for(;pos<buffer.length;){let remaining=buffer.slice(pos);if(remaining.startsWith(ESC)){let terminalReply=isControlString(remaining)&&TERMINAL_REPLY_HEADER_PATTERN.test(remaining),seqEnd=1;for(;seqEnd<=remaining.length;){if(terminalReply&&seqEnd>2){let char=remaining[seqEnd-1];if(char===""||char===""){pos+=seqEnd;break}if(char===ESC&&seqEnd<remaining.length&&remaining[seqEnd]!=="\\"){pos+=seqEnd-1;break}}let candidate=remaining.slice(0,seqEnd),status=isCompleteSequence(candidate);if(status==="complete"){if(candidate==="\x1B\x1B"){let nextChar=remaining[seqEnd];if(nextChar==="["||nextChar==="]"||nextChar==="O"||nextChar==="P"||nextChar==="_"){sequences.push(ESC),pos+=1;break}}sequences.push(candidate),pos+=seqEnd;break}else if(status==="incomplete")seqEnd++;else{sequences.push(candidate),pos+=seqEnd;break}}if(seqEnd>remaining.length)return{sequences,remainder:remaining}}else sequences.push(remaining[0]),pos++}return{sequences,remainder:""}}var StdinBuffer=class extends EventEmitter{buffer="";timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer="";pendingKittyPrintableCodepoint;constructor(options2={}){super(),this.timeoutMs=options2.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options2.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str2;if(Buffer.isBuffer(data))if(data.length===1&&data[0]>127){let byte=data[0]-128;str2=`\x1B${String.fromCharCode(byte)}`}else str2=data.toString();else str2=data;if(str2.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=str2,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let startIndex=this.buffer.indexOf(BRACKETED_PASTE_START);if(startIndex!==-1){if(startIndex>0){let beforePaste=this.buffer.slice(0,startIndex),result2=extractCompleteSequences(beforePaste);for(let sequence of result2.sequences)this.emitDataSequence(sequence)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(startIndex+BRACKETED_PASTE_START.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let result=extractCompleteSequences(this.buffer);this.buffer=result.remainder;for(let sequence of result.sequences)this.emitDataSequence(sequence);if(this.buffer.length>0){if(TERMINAL_REPLY_HEADER_PATTERN.test(this.buffer))return;let timeoutMs=this.buffer===ESC?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let flushed=this.flush();for(let sequence of flushed)sequence.length>2&&isControlString(sequence)?(this.emitDataSequence(sequence.slice(0,2)),this.process(sequence.slice(2))):this.emitDataSequence(sequence)},timeoutMs)}}emitDataSequence(sequence){let rawCodepoint=sequence.length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(sequence),this.emit("data",sequence)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let sequences=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,sequences}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};import*as fs from"node:fs";import*as path2 from"node:path";function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}var TERMINAL_PROGRESS_KEEPALIVE_MS=1e3,TERMINAL_PROGRESS_ACTIVE_SEQUENCE="\x1B]9;4;3\x07",TERMINAL_PROGRESS_CLEAR_SEQUENCE="\x1B]9;4;0\x07",NATIVE_SHIFT_ENTER_SEQUENCE="\x1B[13;2u",DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7,KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS=150,KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u`,DEVICE_ATTRIBUTES_QUERY="\x1B[c";function parseKeyboardProtocolNegotiationSequence(sequence){let kittyFlags=sequence.match(/^\x1b\[\?(\d+)u$/);if(kittyFlags)return{type:"kitty-flags",flags:Number.parseInt(kittyFlags[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(sequence))return{type:"device-attributes"}}function isKeyboardProtocolNegotiationSequencePrefix(sequence){return sequence==="\x1B["||/^\x1b\[\?[\d;]*$/.test(sequence)}function isAppleTerminalSession(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function refreshTerminalDimensions(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH")}catch{}}function isNativeShiftEnterCandidate(data){return data==="\r"||data==="\x1B\r"}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&isNativeShiftEnterCandidate(data)&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100;function resolveEscapeTimeoutMs(env=process.env){let configured=Number(env.DRAHT_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}var ProcessTerminal=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{let env=process.env.DRAHT_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs.statSync(env).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path2.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})();get kittyProtocolActive(){return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){this.inputHandler=onInput,this.resizeHandler=onResize,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs()}),this.stdinBuffer.on("data",sequence=>{if(isProgramStatusReply(sequence)){this.programStatusQueryPending&&(this.programStatusQueryPending=!1,this.programStatusSupported=!0,this.writeProgramStatus());return}let negotiation=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiation==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}negotiation&&this.handleKeyboardProtocolNegotiationSequence(negotiation.parsed)||this.forwardInputSequence(negotiation?.sequence??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),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer();let programStatusOverride=process.env.DRAHT_PROGRAM_STATUS;this.programStatusSupported=programStatusOverride==="1",this.programStatusQueryPending=programStatusOverride!=="1"&&programStatusOverride!=="0";let programStatusQuery=this.programStatusQueryPending?PROGRAM_STATUS_QUERY:"";process.stdout.write(`${KITTY_KEYBOARD_PROTOCOL_QUERY}${programStatusQuery}${DEVICE_ATTRIBUTES_QUERY}`),this.writeProgramStatus()}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1,this.pendingKeyboardProtocolDeviceAttributes===0&&(this.programStatusQueryPending=!1)}return 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(),{parsed:negotiationSequence2,sequence:bufferedSequence};if(isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence))return this.setKeyboardProtocolNegotiationBuffer(bufferedSequence),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let negotiationSequence=parseKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence)return{parsed:negotiationSequence,sequence};if(isKeyboardProtocolNegotiationSequencePrefix(sequence))return this.setKeyboardProtocolNegotiationBuffer(sequence),"pending"}setKeyboardProtocolNegotiationBuffer(sequence){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=sequence}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let sequence=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(sequence)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput()},KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(sequence){if(!this.inputHandler)return;let shouldDetectNativeShiftEnter=isNativeShiftEnterCandidate(sequence)&&(isAppleTerminalSession()||process.platform==="win32"),input=normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnter,shouldDetectNativeShiftEnter&&isNativeModifierPressed("shift"));this.inputHandler(input)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{getNativePlatformHelper()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys();let previousHandler=this.inputHandler;this.inputHandler=void 0;let lastDataTime=Date.now(),onData=()=>{lastDataTime=Date.now()};process.stdin.on("data",onData);let endTime=Date.now()+maxMs;try{for(;;){let now=Date.now(),timeLeft=endTime-now;if(timeLeft<=0||now-lastDataTime>=idleMs)break;await new Promise(resolve=>setTimeout(resolve,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.clearProgressInterval()&&process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus({state:"clear"})),this.programStatusSupported=!1,this.programStatusQueryPending=!1,process.stdout.write("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw)}restoreOnExit(before,after){let sequence=before;this.progressInterval&&(sequence+=TERMINAL_PROGRESS_CLEAR_SEQUENCE),sequence+="\x1B[?2004l",(this.keyboardProtocolPushed||this._kittyProtocolActive)&&(sequence+="\x1B[<u"),this._modifyOtherKeysActive&&(sequence+="\x1B[>4;0m"),sequence+=after;try{fs.writeSync(process.stdout.fd,sequence)}catch{}}write(data){if(process.stdout.write(data),this.writeLogPath)try{fs.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>0?process.stdout.write(`\x1B[${lines}B`):lines<0&&process.stdout.write(`\x1B[${-lines}A`)}hideCursor(){process.stdout.write("\x1B[?25l")}showCursor(){process.stdout.write("\x1B[?25h")}clearLine(){process.stdout.write("\x1B[K")}clearFromCursor(){process.stdout.write("\x1B[J")}clearScreen(){process.stdout.write("\x1B[2J\x1B[H")}setTitle(title){process.stdout.write(`\x1B]0;${replaceControlCharacters(title)}\x07`)}setProgramStatus(status){this.programStatus=status.state==="clear"?void 0:status,this.programStatusSupported&&process.stdout.write(formatProgramStatus(status))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus(this.programStatus))}setProgress(active){active?(process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var segmenter2=getGraphemeSegmenter(),PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function buildSearchCorpus(lines){let chunks=[],spans=[],textLength=0,pendingSeparator=!1,appendSeparator=()=>{pendingSeparator&&(chunks.push(" "),textLength+=1,pendingSeparator=!1)};for(let row=0;row<lines.length;row++){let line=stripTerminalSequences(lines[row]??""),column=0;if(PRINTABLE_ASCII.test(line)){let index=0;for(;index<line.length;){if(line.charCodeAt(index)===32){textLength>0&&(pendingSeparator=!0),column+=1,index+=1;continue}let end=index+1;for(;end<line.length&&line.charCodeAt(end)!==32;)end+=1;appendSeparator();let text=line.slice(index,end);chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+text.length,linearColumns:!0}),textLength+=text.length,column+=text.length,index=end}}else for(let grapheme of segmenter2.segment(line)){let text=grapheme.segment,width=visibleWidth(text);if(/^\s+$/u.test(text)){textLength>0&&(pendingSeparator=!0),column+=width;continue}appendSeparator(),chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+width,linearColumns:!1}),textLength+=text.length,column+=width}textLength>0&&(pendingSeparator=!0)}return{text:chunks.join(""),spans}}function normalizeQuery(query){return query.replace(/\s+/gu," ").trim()}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function findSearchCorpusMatches(corpus,normalizedQuery){if(!normalizedQuery)return[];let expression=new RegExp(escapeRegExp(normalizedQuery),"giu"),matches=[],spanIndex=0;for(let match of corpus.text.matchAll(expression)){let start=match.index,end=start+match[0].length;for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=start;)spanIndex+=1;let segments=[];for(let index=spanIndex;index<corpus.spans.length;index++){let span=corpus.spans[index];if(span.textStart>=end)break;if(span.textEnd<=start)continue;let startCol=span.linearColumns?span.startCol+Math.max(start,span.textStart)-span.textStart:span.startCol,endCol=span.linearColumns?span.startCol+Math.min(end,span.textEnd)-span.textStart:span.endCol,previous=segments[segments.length-1];previous&&previous.row===span.row&&startCol<=previous.endCol?previous.endCol=Math.max(previous.endCol,endCol):segments.push({row:span.row,startCol,endCol})}for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=end;)spanIndex+=1;segments.length>0&&matches.push({segments})}return matches}var AltScreenSearchIndex=class{sourceLines;corpus;normalizedQuery;matches=[];search(lines,query){let sourceChanged=this.sourceLines?.length!==lines.length;if(!sourceChanged&&this.sourceLines){for(let index=0;index<lines.length;index++)if(this.sourceLines[index]!==lines[index]){sourceChanged=!0;break}}(sourceChanged||!this.corpus)&&(this.sourceLines=Array.from(lines),this.corpus=buildSearchCorpus(lines));let normalizedQuery=normalizeQuery(query),changed=sourceChanged||normalizedQuery!==this.normalizedQuery;return changed&&(this.normalizedQuery=normalizedQuery,this.matches=findSearchCorpusMatches(this.corpus,normalizedQuery)),{matches:this.matches,changed}}};function getAltScreenSearchMatchKey(match){let first=match.segments[0],last=match.segments[match.segments.length-1];return first&&last?`${first.row}:${first.startCol}:${last.row}:${last.endCol}`:""}var AltScreenSearchComponent=class{input=new Input({prompt:" ",placeholder:"Find in transcript",placeholderStyle:text=>`\x1B[2m${text}\x1B[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(onQueryChange,navigationButtonStyle=text=>text){this.onQueryChange=onQueryChange,this.navigationButtonStyle=navigationButtonStyle}get focused(){return this._focused}set focused(value){this._focused=value,this.input.focused=value}setResult(index,count){this.resultIndex=index,this.resultCount=count}getNavigationDirectionAt(row,column){if(row===2){if(column>=this.previousButtonStart&&column<this.previousButtonEnd)return-1;if(column>=this.nextButtonStart&&column<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(direction){return direction===this.hoveredNavigationDirection?!1:(this.hoveredNavigationDirection=direction,!0)}handleInput(data){let previous=this.input.getValue();this.input.handleInput(data);let query=this.input.getValue();query!==previous&&this.onQueryChange(query)}invalidate(){this.input.invalidate()}render(width){let safeWidth=Math.max(1,width),innerWidth=Math.max(0,safeWidth-2),formatKey=key=>key?key.split("+").map(part=>process.platform==="darwin"&&part.toLowerCase()==="alt"?"Option":part.charAt(0).toUpperCase()+part.slice(1)).join("+"):"Unbound",keybindings=getKeybindings(),previousKey=formatKey(keybindings.getKeys("tui.altScreen.searchPrevious")[0]),nextKey=formatKey(keybindings.getKeys("tui.altScreen.searchNext")[0]),result=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",resultSpace=Math.max(0,innerWidth-3),visibleResult=truncateToWidth(result,resultSpace,""),resultText=visibleResult?`\x1B[2m ${visibleResult} \x1B[22m`:"",inputWidth=Math.max(0,innerWidth-visibleWidth(resultText)),inputLine=truncateToWidth(this.input.render(Math.max(1,inputWidth))[0]??"",inputWidth,""),inputPadding=" ".repeat(Math.max(0,inputWidth-visibleWidth(inputLine))),content=`${inputLine}${inputPadding}${resultText}`,previousButton=`\u2191 ${previousKey}`,nextButton=`\u2193 ${nextKey}`,separator=" \xB7 ",outerGapWidth=1,availableControlsWidth=Math.max(0,innerWidth-outerGapWidth*2-1),controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton);controlsWidth>availableControlsWidth&&(previousButton="\u2191",nextButton="\u2193",separator=" ",controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton));let showButtons=controlsWidth<=availableControlsWidth,renderedButtons=showButtons?this.navigationButtonStyle(previousButton,this.hoveredNavigationDirection===-1)+separator+this.navigationButtonStyle(nextButton,this.hoveredNavigationDirection===1):"",outerGapsWidth=showButtons?outerGapWidth*2:0,rightRuleWidth=renderedButtons&&innerWidth>controlsWidth+outerGapsWidth?1:0,leftRuleWidth=Math.max(0,innerWidth-(showButtons?controlsWidth:0)-outerGapsWidth-rightRuleWidth),previousStart=1+leftRuleWidth+outerGapWidth;return this.previousButtonStart=showButtons?previousStart:-1,this.previousButtonEnd=showButtons?previousStart+visibleWidth(previousButton):-1,this.nextButtonStart=showButtons?this.previousButtonEnd+visibleWidth(separator):-1,this.nextButtonEnd=showButtons?this.nextButtonStart+visibleWidth(nextButton):-1,safeWidth===1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(innerWidth)}\u2510`,`\u2502${content}\u2502`,`\u2514${"\u2500".repeat(leftRuleWidth)}${renderedButtons?" ":""}${renderedButtons}${renderedButtons?" ":""}${"\u2500".repeat(rightRuleWidth)}\u2518`]}};var DEFAULT_DURATION_MS=1e3,AltScreenFlashContainer=class{entries=[];nextId=0;requestRender;constructor(requestRender){this.requestRender=requestRender}flash(message,durationMs=DEFAULT_DURATION_MS){let id=this.nextId++,timer=setTimeout(()=>{let index=this.entries.findIndex(entry=>entry.id===id);index!==-1&&(this.entries.splice(index,1),this.requestRender())},Math.max(0,durationMs));timer.unref(),this.entries.push({id,message,timer}),this.requestRender()}dispose(){for(let entry of this.entries)clearTimeout(entry.timer);this.entries.length=0}invalidate(){}render(width){return this.entries.map(entry=>`\x1B[7m${truncateToWidth(` ${entry.message} `,width,"")}\x1B[27m`)}};var OSC133_ZONE_PREFIX=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function intersect(a,b){let x=Math.max(a.x,b.x),y=Math.max(a.y,b.y),right=Math.min(a.x+a.width,b.x+b.width),bottom=Math.min(a.y+a.height,b.y+b.height);return{x,y,width:Math.max(0,right-x),height:Math.max(0,bottom-y)}}function renderCached(context,component,width){let safeWidth=Math.max(1,Math.floor(width)),widths=context.renderCache.get(component);widths||(widths=new Map,context.renderCache.set(component,widths));let lines=widths.get(safeWidth);return lines||(lines=component.render(safeWidth),widths.set(safeWidth,lines)),lines}function measureHeight(context,component,width){return renderCached(context,component,width).length}function measureWidth(context,component,width){return renderCached(context,component,width).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)}function withParent(box,parent){return box.parent=parent,box}function translateBox(box,deltaY){box.rect.y+=deltaY;for(let child of box.children)translateBox(child,deltaY)}function updateClips(box,parentClip){box.clip=intersect(parentClip,box.rect);for(let child of box.children)updateClips(child,box.clip)}function layoutComponent(context,component,x,y,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(component);if(!node){let lines=renderCached(context,component,safeWidth),allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>0){let cursorLine=lines.findIndex(line=>line.includes(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x,y,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x,y,width:safeWidth,height:allocatedHeight2}),children:[],lines,lineOffset,layer:0}}if(node.type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x,y-previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.rect.height,viewportHeight=height===void 0?contentHeight:Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x,y,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),box2={component,rect:rect2,clip:childClip,children:[childBox],scrollView,scrollContentLines:renderCached(context,node.component,contentWidth),layer:0};return childBox.parent=box2,updateClips(childBox,childClip),box2}let entries=visibleStackEntries(node.entries,context.viewport),gapTotal=Math.max(0,entries.length-1)*node.gap;if(node.type==="vstack"){let intrinsicHeights2=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureHeight(context,entry.component,safeWidth)),sizes=allocateStackSizes(entries,intrinsicHeights2,height,node.gap),naturalHeight=sizes.reduce((sum,size)=>sum+size,0)+gapTotal,allocatedHeight2=height===void 0?naturalHeight:Math.max(0,Math.floor(height)),rect2={x,y,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y;for(let index=0;index<entries.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=sizes[index]+node.gap;return box2}let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x,y,width:safeWidth,height:allocatedHeight},box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y;node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.push({component:entries[index].component,rect:{x:childX,y:childY,width:0,height:childHeight},clip:{x:childX,y:childY,width:0,height:0},children:[],parent:box,layer:0}):box.children.push(withParent(layoutComponent(context,entries[index].component,childX,childY,childWidth,childHeight,box.clip),box)),childX+=childWidth+node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(line,column),start=graphemeRange?.start??column,end=graphemeRange?.end??column+1,before=sliceByColumn(line,0,start,!0),target=sliceByColumn(line,start,end-start,!0),after=sliceByColumn(line,end,Math.max(0,totalWidth-end),!0),targetPrefix="",targetIndex=0;for(;targetIndex<target.length;){let ansi=extractAnsiCode(target,targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.max(0,column-start)),cellPaddingAfter=" ".repeat(Math.max(0,end-column-1)),targetStyle=`\x1B[0m\x1B]8;;\x07${preserveTargetBackground?getActiveBackgroundAnsi(targetPrefix):""}`;return`${before}${beforePadding}${targetStyle}${cellPaddingBefore}${replacement}${cellPaddingAfter}${after}`}function getScrollbarGeometry(box,includeHiddenAuto=!1){if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.rect.height??box.scrollContentLines?.length??0,trackHeight=box.rect.height,canRevealHiddenAuto=includeHiddenAuto&&box.scrollView.scrollbar==="auto"&&contentHeight>trackHeight;if(!box.scrollView.isScrollbarVisible&&!canRevealHiddenAuto)return;let minThumbHeight=Math.min(2,trackHeight),thumbHeight=Math.max(minThumbHeight,Math.min(trackHeight,Math.round(trackHeight*trackHeight/contentHeight))),maxScrollTop=Math.max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),column=box.rect.x+box.rect.width-1;if(!(column<box.clip.x||column>=box.clip.x+box.clip.width))return{column,trackTop:box.rect.y,trackHeight,thumbTop:box.rect.y+thumbOffset,thumbHeight,maxScrollTop}}function paintScrollbar(box,screen,totalWidth){let geometry=getScrollbarGeometry(box);if(!(!geometry||!box.scrollView))for(let offset=0;offset<geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=geometry.thumbTop&&row<geometry.thumbTop+geometry.thumbHeight?box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive?"\u2588":"\u2503"):box.scrollView.scrollbarTrackStyle("\u2502");screen[row]=replaceScrollbarCell(screen[row]??"",geometry.column,totalWidth,replacement,box.scrollView.scrollbar!=="always")}}function paintBox(box,screen,totalWidth){if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.y+box.clip.height,screen.length);for(let row=firstRow;row<lastRow;row++){let sourceLine=box.lines[offset+row-box.rect.y];if(sourceLine===void 0)continue;let line=sourceLine.replace(OSC133_ZONE_PREFIX,""),imageMetadata=getKittyImageMetadata(line);if(imageMetadata){let clipBottom=Math.min(screen.length,box.clip.y+box.clip.height),visibleRows=Math.min(imageMetadata.rows,clipBottom-row);visibleRows<imageMetadata.rows&&(line=cropKittyImageLine(line,0,visibleRows))}box.rect.x===0&&box.rect.width>=totalWidth&&(isImageLine(line)||!screen[row])?screen[row]=line:screen[row]=compositeTuiLine(screen[row]??"",line,box.rect.x,box.rect.width,totalWidth)}}for(let child of box.children)paintBox(child,screen,totalWidth);if(box.scrollView&&box.scrollContentLines&&box.scrollView.scrollTop>0&&box.rect.height>0){let scrollTop=box.scrollView.scrollTop,minRow=Math.max(0,scrollTop-getMaxKittyImageRows());for(let imageRow=scrollTop-1;imageRow>=minRow;imageRow--){let imageLine=box.scrollContentLines[imageRow]??"";if(!isImageLine(imageLine))continue;let metadata=getKittyImageMetadata(imageLine);if(!metadata)continue;let hiddenRows=scrollTop-imageRow;if(hiddenRows<metadata.rows){let visibleRows=Math.min(box.rect.height,metadata.rows-hiddenRows),cropped=cropKittyImageLine(imageLine,hiddenRows,visibleRows);box.rect.x===0&&box.rect.width>=totalWidth&&(screen[box.rect.y]=cropped)}break}}paintScrollbar(box,screen,totalWidth)}function renderLayoutFrame(root,width,height,requestRender){let safeWidth=Math.max(1,Math.floor(width)),safeHeight=Math.max(1,Math.floor(height)),context={viewport:{width:safeWidth,height:safeHeight},renderCache:new Map,requestRender,primaryScrollView:void 0},rootBox=layoutComponent(context,root,0,0,safeWidth,safeHeight,{x:0,y:0,width:safeWidth,height:safeHeight}),lines=Array.from({length:safeHeight},()=>"");return paintBox(rootBox,lines,safeWidth),{root:rootBox,width:safeWidth,height:safeHeight,lines,...context.primaryScrollView===void 0?{}:{primaryScrollView:context.primaryScrollView}}}function containsPoint(rect,x,y){return x>=rect.x&&x<rect.x+rect.width&&y>=rect.y&&y<rect.y+rect.height}function getLayoutBoxesAt(frame,x,y){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x,y)){result.push({box,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b)=>b.box.layer-a.box.layer||b.depth-a.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x,y){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x,y)){box.scrollView&&containsPoint(box.rect,x,y)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b)=>b.depth-a.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env=process.env;return process.platform==="darwin"&&env.SSH_CONNECTION===void 0&&env.SSH_CLIENT===void 0&&env.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let gap=now-this.lastTime,sameGesture=direction===this.lastDirection&&gap<=200;if(this.lastTime=now,this.lastDirection=direction,!sameGesture)return this.averageGap=void 0,this.carry=0,1;if(gap<5)return 1;this.averageGap=this.averageGap===void 0?gap:(this.averageGap+gap)/2;let lines=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,whole=Math.floor(lines);return this.carry=lines-whole,whole}reset(){this.lastTime=Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var ENTER_ALT_SCREEN="\x1B[?1049h",EXIT_ALT_SCREEN="\x1B[?1049l",DISABLE_AUTOWRAP="\x1B[?7l",ENABLE_AUTOWRAP="\x1B[?7h",ENABLE_BUTTON_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",ENABLE_ALL_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",DISABLE_MOUSE="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",FOCUS_IN="\x1B[I",FOCUS_OUT="\x1B[O",BEGIN_SYNCHRONIZED_OUTPUT="\x1B[?2026h",END_SYNCHRONIZED_OUTPUT="\x1B[?2026l",OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,OSC133_PROMPT_START=/^\x1b\]133;A(?:\x07|\x1b\\)/,PAGE_SCROLL_OVERLAP=4,ALT_WHEEL_SCROLL_MULTIPLIER=5,MAX_CACHED_OFFSCREEN_KITTY_IMAGES=16,MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES=32*1024*1024,MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES=64*1024*1024,DOUBLE_CLICK_INTERVAL_MS=500,COPY_ERROR_FLASH_DURATION_MS=5e3,TERMINAL_WORD_SELECTION_JOINERS=new Set(["/","-","+","\\","~","_","."]),wordSegmenter4=getWordSegmenter(),TuiAltScreen=class extends TuiBase{mode="fullscreen";[VIEWPORT_TUI]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="character";selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScroll;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(terminal,showHardwareCursor,logDirectory,options2={}){super(terminal,showHardwareCursor,logDirectory),this.implicitDocument={render:width=>super.render(width),handleMouse:event=>super.handleMouse(event),invalidate:()=>{for(let child of this.children)child.invalidate()}},this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(options2.wheelScrollLines??1),this.mouseEnabled=options2.mouse??!0,this.searchMatchStyle=options2.searchMatchStyle??(text=>`\x1B[4m${text}\x1B[24m`),this.searchCurrentMatchStyle=options2.searchCurrentMatchStyle??(text=>`\x1B[1;7m${text}\x1B[22;27m`),this.searchNavigationButtonStyle=options2.searchNavigationButtonStyle??(text=>text),this.scrollToEndIndicator=options2.scrollToEndIndicator,this.openUrl=options2.openUrl,this.onRightClickPaste=options2.onRightClickPaste,this.copyOnSelect=options2.copyOnSelect??!0,this.copySelection=options2.copySelection,this.addInputListener(data=>this.handleViewportInput(data))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(lines){this.wheelScroll.setLines(lines)}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(enabled){this.copyOnSelect=enabled}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}resetTextSelection(){this.clearTextSelection(),this.lastClick=void 0}setLayoutRoot(component){this.layoutRoot!==component&&(this.layoutRoot=component,this.currentLayout=void 0,this.requestRender())}render(width){return this.layoutRoot?.render(width)??super.render(width)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let capabilities=getCapabilities();this.imageProtocol=capabilities.images,this.uploadedKittyImages.clear(),capabilities.images==="iterm2"&&(this.savedCapabilities=capabilities,setCapabilities({...capabilities,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let term=process.env.TERM?.toLowerCase()??"",mouseSequence=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||term.startsWith("tmux")||term.startsWith("screen")?ENABLE_BUTTON_MOTION_MOUSE:ENABLE_ALL_MOTION_MOUSE;this.terminal.write(`${ENTER_ALT_SCREEN}${DISABLE_AUTOWRAP}${this.mouseEnabled?mouseSequence:""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(_options){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${this.deleteKittyImages()}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${END_SYNCHRONIZED_OUTPUT}`),this.uploadedKittyImages.clear())}afterTerminalStop(options2){if(this.altScreenActive){if(this.altScreenActive=!1,options2.preserveScreen)this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`);else{let width=Math.max(1,this.terminal.columns),documentLines=this.resolveFakeCursors(this.render(width)).map(line=>line.replace(OSC133_ZONE_PREFIX2,""));this.lastDocument=this.applyLineResets(documentLines.map(line=>line.replaceAll(CURSOR_MARKER,""))).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
100
101
  `),buffer+=`\r\x1B[2K${this.lastDocument[row]??""}`;buffer+=`\x1B[0m${ENABLE_AUTOWRAP}\r
101
102
  \x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}getExitRestorePrefix(){let prefix=super.getExitRestorePrefix();return this.altScreenActive?`${END_SYNCHRONIZED_OUTPUT}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${prefix}`:prefix}getExitRestoreSuffix(){return`${super.getExitRestoreSuffix()}${this.altScreenActive?`${EXIT_ALT_SCREEN}\x1B[?25h`:""}`}deleteKittyImages(){return this.imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={transmissionGeneration:placement.transmissionGeneration,transmissionBytes:placement.transmissionBytes,estimatedDecodedBytes:placement.estimatedDecodedBytes};return cachedImage&&this.uploadedKittyImages.delete(placement.imageId),this.uploadedKittyImages.set(placement.imageId,nextCachedImage),cachedImage?.transmissionGeneration===placement.transmissionGeneration?placement.replacementLine:line}),cachedOffscreenImageCount=0,cachedOffscreenTransmissionBytes=0,cachedOffscreenDecodedBytes=0;for(let[imageId,cachedImage]of this.uploadedKittyImages)visibleImageIds.has(imageId)||(cachedOffscreenImageCount+=1,cachedOffscreenTransmissionBytes+=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes+=cachedImage.estimatedDecodedBytes);let evictedImageDeletion="";for(let[imageId,cachedImage]of this.uploadedKittyImages){if(cachedOffscreenImageCount<=MAX_CACHED_OFFSCREEN_KITTY_IMAGES&&cachedOffscreenTransmissionBytes<=MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES&&cachedOffscreenDecodedBytes<=MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES)break;visibleImageIds.has(imageId)||(evictedImageDeletion+=deleteKittyImage(imageId),this.uploadedKittyImages.delete(imageId),cachedOffscreenImageCount-=1,cachedOffscreenTransmissionBytes-=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes-=cachedImage.estimatedDecodedBytes)}return{lines,evictedImageDeletion}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(lines){this.getPrimaryScrollView().scrollBy(lines),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(direction){if(!this.currentLayout)return;let scrollView=this.getPrimaryScrollView(),lines=getScrollViewBox(this.currentLayout,scrollView)?.scrollContentLines;if(lines){for(let row=scrollView.scrollTop+direction;row>=0&&row<lines.length;row+=direction)if(OSC133_PROMPT_START.test(lines[row]??"")){scrollView.scrollTo(row),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let component=new AltScreenSearchComponent(query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={component,index:new AltScreenSearchIndex,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=search,search.overlay=this.showOverlay(component,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){let search=this.activeSearch;search&&(this.activeSearch=void 0,search.overlay?.hide(),this.requestRender())}updateSearchQuery(query){let search=this.activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){let search=this.activeSearch;search?.query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x,y){let search=this.activeSearch,bounds=search?.overlay?.getBounds();if(!(!search||!bounds)&&!(x<bounds.col||x>=bounds.col+bounds.width||y<bounds.row||y>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y-bounds.row,x-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.getSearchNavigationDirectionAt(event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==0||(event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.matches=[],search.selectedIndex=-1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",result=search.index.search(lines,search.query),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.row??0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInput(){return this.getFocusedComponent()?.capturesViewportInput?!0:this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let lines=this.wheelScroll.next(wheelEvent.direction,performance.now()),wheelDelta=wheelEvent.direction*((wheelEvent.button&8)!==0?lines*ALT_WHEEL_SCROLL_MULTIPLIER:lines),event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):(this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInput()){if(keybindings.matches(data,"tui.altScreen.pageUp"))return isRelease||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageDown"))return isRelease||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.nextPrompt"))return isRelease||this.scrollToPrompt(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){switch(button&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(type,button,x,y,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x,y,screenX:x,screenY:y,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||getLayoutNode(box.component)&&box.component.handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result){let focusTarget=this.resolveMouseFocusTarget(result.focusTarget??result.target.component),focusChanged=result.focus===!0&&this.getFocusedComponent()!==focusTarget;return result.focus&&this.setFocus(focusTarget),result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x,y){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x&&previous.y===y?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x,y},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"release":isMotion?this.decodeMouseButton(raw.button)==="none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(event,targetResult)),raw.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),clickResult=this.dispatchMouseToTarget(clickEvent,target);clickResult&&(render=this.applyMouseDispatchResult(clickEvent,clickResult)||render)}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=result.target,this.mousePressPoint={x:raw.x,y:raw.y},this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(raw)}parseWheelEvent(data){let sgr=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(data);if(sgr){let button=Number.parseInt(sgr[1],10);if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:Number.parseInt(sgr[2],10)-1,y:Number.parseInt(sgr[3],10)-1,button}}if(data.length===6&&data.startsWith("\x1B[M")){let button=data.charCodeAt(3)-32;if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:data.charCodeAt(4)-33,y:data.charCodeAt(5)-33,button}}}routeWheel(event,delta){let remaining=delta,seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll==="contain")break;let primary=this.getPrimaryScrollView();remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){let match=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);if(match)return{button:Number.parseInt(match[1],10),x:Number.parseInt(match[2],10)-1,y:Number.parseInt(match[3],10)-1,release:match[4]==="m"}}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;return!rect||event.release||(event.button&32)!==0||(event.button&3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x,y,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x,y)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x===geometry.column&&y>=geometry.trackTop&&y<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x,y){this.setScrollbarHover(this.getScrollbarTargetAt(x,y,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(target.scrollView);let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,target.geometry,event.y,grabOffset),this.scrollbarDrag={scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x,y){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)return;let pointerRow=Math.max(visibleTop,Math.min(visibleBottom,y)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.max(0,Math.min(this.terminal.columns-1,event.x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.scrollContentLines;if(lines)return lines[point.row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of wordSegmenter4.segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.has(segment.segment);segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.col>=segment.start&&point.col<segment.end);if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)selectionStart=segments[index-1].start;for(let index=clickedSegmentIndex;index<segments.length-1&&canJoin(segments[index],segments[index+1]);index++)selectionEnd=segments[index+1].end;return{start:{...point,col:selectionStart},end:{...point,col:selectionEnd,boundary:!0}}}getLineSelection(point){return{start:{...point,col:0},end:{...point,col:visibleWidth(this.getSelectionSourceLine(point)),boundary:!0}}}updateSelectionFocus(point){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=point;return}let range=this.selectionGranularity==="word"?this.getWordSelection(point):this.getLineSelection(point);if(!range)return;let initial=this.selectionInitialRange;range.start.row<initial.start.row||range.start.row===initial.start.row&&range.start.col<initial.start.col?(this.selectionAnchor=initial.end,this.selectionFocus=range.start):(this.selectionAnchor=initial.start,this.selectionFocus=range.end)}getClickCount(point,word){let now=Date.now(),previous=this.lastClick,count=word&&previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.row===point.row&&previous.scrollView===point.scrollView&&previous.wordStart===word.start.col&&previous.wordEnd===word.end.col?previous.count%3+1:1;return this.lastClick=word?{timestamp:now,count,row:point.row,scrollView:point.scrollView,wordStart:word.start.col,wordEnd:word.end.col}:void 0,count}updateSelectionAutoScroll(event){let scrollView=this.selectionAnchor?.scrollView;if(!scrollView||!this.currentLayout){this.stopSelectionAutoScroll();return}let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0){this.stopSelectionAutoScroll();return}let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(this.selectionDragPointer={x:event.x,y:event.y},this.selectionAutoScrollDirection=event.y<=visibleTop?-1:event.y>=visibleBottom?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref())}autoScrollSelection(){let scrollView=this.selectionAnchor?.scrollView,pointer=this.selectionDragPointer,direction=this.selectionAutoScrollDirection;if(!scrollView||!pointer||direction===0){this.stopSelectionAutoScroll();return}if(scrollView.scrollBy(direction)===direction){this.stopSelectionAutoScroll();return}let point=this.getScrollSelectionPoint(scrollView,pointer.x,pointer.y);point&&this.updateSelectionFocus(point),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(event){let button=event.button&3;if(button!==0&&!(event.release&&button===3))return;let anchorScrollView=this.selectionAnchor?.scrollView,point=this.getSelectionPoint(event,anchorScrollView);if(event.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(point);let isClick=!this.selectionDragged&&this.selectionAnchor.scrollView===point.scrollView&&this.selectionAnchor.row===point.row&&this.selectionAnchor.col===point.col,clickedUrl=isClick?this.pressedUrl:void 0;if(this.pressedUrl=void 0,clickedUrl&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(clickedUrl)}catch{}this.requestRender();return}if(isClick){let clickEvent=this.createMouseEvent("click",event.button,event.x,event.y,{clickCount:this.lastClick?.count??1}),overlay=this.dispatchMouseToOverlay(clickEvent),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(clickEvent));if(result){let render=this.applyMouseDispatchResult(clickEvent,result);this.clearTextSelection(),render&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((event.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(point),this.updateSelectionAutoScroll(event),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let scrollView=!this.hasOverlay()&&this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y)[0]:void 0,anchor=this.getSelectionPoint(event,scrollView),word=this.getWordSelection(anchor),clickCount=this.getClickCount(anchor,word),range=clickCount===2?word:clickCount===3?this.getLineSelection(anchor):void 0;this.selectionGranularity=range?clickCount===2?"word":"line":"character",this.selectionInitialRange=range,this.selectionAnchor=range?.start??anchor,this.selectionFocus=range?.end??anchor,this.selectionDragged=!1,this.pressedUrl=range?void 0:getOsc8LinkAtColumn(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,event.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,event.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let anchorBeforeFocus=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return anchorBeforeFocus?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(line,row,selection,minColumn=0,maxColumn=visibleWidth(line)){let lineWidth=visibleWidth(line),start=Math.max(0,minColumn),end=Math.min(lineWidth,maxColumn);return row===selection.start.row&&(start=getGraphemeCellRange(line,selection.start.col)?.start??Math.min(selection.start.col,lineWidth)),row===selection.end.row&&(end=selection.end.boundary?Math.min(selection.end.col,lineWidth):getGraphemeCellRange(line,selection.end.col)?.end??Math.min(selection.end.col+1,lineWidth)),{start:Math.max(minColumn,start),end:Math.min(maxColumn,end)}}getActiveSelectionText(){let selection=this.getSelectionBounds();if(!selection)return;let sourceLines=this.previousScreen;if(selection.start.scrollView){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,selection.start.scrollView);if(!box?.scrollContentLines)return;sourceLines=box.scrollContentLines}let lines=[];for(let row=selection.start.row;row<=selection.end.row;row++){let line=sourceLines[row]??"",columns=this.getSelectionColumns(line,row,selection);lines.push(stripTerminalSequences(sliceByColumn(line,columns.start,Math.max(0,columns.end-columns.start),!0)).trimEnd())}let text=lines.join(`
102
- `);return text.length===0?void 0:text}async copySelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}async copyTextToClipboard(text){if(this.copySelection){let result=await this.copySelection(text),ok=result===!0;return this.flash(ok?"Copied!":typeof result=="string"?result:"Copy failed",ok?void 0:COPY_ERROR_FLASH_DURATION_MS),ok}return this.terminal.write(`\x1B]52;c;${Buffer.from(text).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(text,current){let style=current?this.searchCurrentMatchStyle:this.searchMatchStyle,result="",plainStart=0,index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){index+=1;continue}index>plainStart&&(result+=style(text.slice(plainStart,index))),result+=ansi.code,index+=ansi.length,plainStart=index}return plainStart<text.length&&(result+=style(text.slice(plainStart))),result}applySearchHighlights(screen,layout){let search=this.activeSearch;if(!search||search.selectedIndex<0||search.matches.length===0)return screen;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView);if(!box)return screen;let rangesByRow=new Map,scrollbarColumn=getScrollbarGeometry(box)?.column,minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length,box.rect.y+box.rect.height,box.clip.y+box.clip.height),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width,scrollbarColumn??Number.POSITIVE_INFINITY),minContentRow=scrollView.scrollTop+minRow-box.rect.y,maxContentRow=scrollView.scrollTop+maxRow-box.rect.y-1,low=0,high=search.matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2),match=search.matches[middle];(match.segments[match.segments.length-1]?.row??-1)<minContentRow?low=middle+1:high=middle}for(let matchIndex=low;matchIndex<search.matches.length;matchIndex++){let match=search.matches[matchIndex];if((match.segments[0]?.row??0)>maxContentRow)break;for(let segment of match.segments){let row=box.rect.y+segment.row-scrollView.scrollTop;if(row<minRow||row>=maxRow)continue;let startCol=Math.max(minColumn,box.rect.x+segment.startCol),endCol=Math.min(maxColumn,box.rect.x+segment.endCol);if(endCol<=startCol)continue;let ranges=rangesByRow.get(row)??[];ranges.push({startCol,endCol,current:matchIndex===search.selectedIndex}),rangesByRow.set(row,ranges)}}let result=[...screen];for(let[row,ranges]of rangesByRow){let line=result[row]??"";if(isImageLine(line))continue;let lineWidth=visibleWidth(line);for(let range of ranges.sort((a,b)=>b.startCol-a.startCol)){let startCol=Math.min(range.startCol,lineWidth),endCol=Math.min(range.endCol,lineWidth);if(endCol<=startCol)continue;let before=sliceByColumn(line,0,startCol,!0),highlighted=sliceByColumn(line,startCol,endCol-startCol,!0),after=sliceByColumn(line,endCol,Math.max(0,lineWidth-endCol),!0);line=`${before}${this.applySearchTextHighlight(highlighted,range.current)}${after}`}result[row]=line}return result}applySelectionHighlight(text){let result="\x1B[7m",index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){result+=text[index],index+=1;continue}result+=ansi.code,ansi.code.endsWith("m")&&(result+="\x1B[7m"),index+=ansi.length}return`${result}\x1B[27m`}applySelection(screen,layout=this.currentLayout){let selection=this.getSelectionBounds();if(!selection)return screen;let screenSelection=selection,minRow=0,maxRow=screen.length-1,minColumn=0,maxColumn=this.terminal.columns;if(selection.start.scrollView){if(!layout)return screen;let box=getScrollViewBox(layout,selection.start.scrollView);if(!box)return screen;minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width),screenSelection={start:{...selection.start,row:box.rect.y+selection.start.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.start.col},end:{...selection.end,row:box.rect.y+selection.end.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.end.col}}}return screen.map((line,row)=>{if(row<minRow||row>maxRow||row<screenSelection.start.row||row>screenSelection.end.row||isImageLine(line))return line;let lineWidth=visibleWidth(line),columns=this.getSelectionColumns(line,row,screenSelection,minColumn,maxColumn);if(columns.end<=columns.start)return line;let before=sliceByColumn(line,0,columns.start,!0),selected=sliceByColumn(line,columns.start,columns.end-columns.start,!0),after=sliceByColumn(line,columns.end,Math.max(0,lineWidth-columns.end),!0);return`${before}${this.applySelectionHighlight(selected)}${after}`})}isMouseSequence(data){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(data)||data.length===6&&data.startsWith("\x1B[M")}compositeScrollToEndIndicator(screen,layout,width){this.scrollToEndIndicatorRect=void 0;let scrollView=layout.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!scrollView.followEnd||scrollView.isFollowingEnd)return screen;let box=getScrollViewBox(layout,scrollView),clip=box?.clip;if(!clip||clip.width<=0||clip.height<=0)return screen;let row=clip.y+clip.height-1;if(row>=screen.length||isImageLine(screen[row]??""))return screen;let scrollbarColumn=box?getScrollbarGeometry(box)?.column:void 0,label=truncateToWidth(this.scrollToEndIndicator(),clip.width,""),labelWidth=visibleWidth(label),column=clip.x+Math.floor((clip.width-labelWidth)/2),rightEdge=scrollbarColumn??clip.x+clip.width,availableWidth=Math.max(0,rightEdge-column),text=truncateToWidth(label,availableWidth,""),textWidth=visibleWidth(text);if(textWidth===0)return screen;let result=[...screen];return result[row]=compositeTuiLine(result[row]??"",text,column,textWidth,width),this.scrollToEndIndicatorRect={row,column,width:textWidth},result}compositeFlashes(screen,width,height){let flashLines=this.flashes.render(width).slice(-height);if(flashLines.length===0)return screen;let result=[...screen];for(;result.length<height;)result.push("");for(let row=0;row<flashLines.length;row++){let line=flashLines[row],flashWidth=visibleWidth(line);flashWidth!==0&&(result[row]=compositeTuiLine(result[row]??"",line,width-flashWidth,flashWidth,width))}return result}doRender(){if(this.stopped||!this.altScreenActive)return;let width=Math.max(1,this.terminal.columns),height=Math.max(1,this.terminal.rows),root=this.layoutRoot??this.implicitScrollView,nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender());this.refreshSearch(nextLayout)&&(nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender()));let screen=this.resolveFakeCursors(nextLayout.lines.map(line=>line.replace(OSC133_ZONE_PREFIX2,"")));screen=this.applySearchHighlights(screen,nextLayout),screen=this.compositeScrollToEndIndicator(screen,nextLayout,width),screen=this.compositeOverlays(screen,width,height),screen.length>height&&(screen=screen.slice(screen.length-height)),screen=this.applySelection(screen,nextLayout),screen=this.compositeFlashes(screen,width,height);let cursorPos=this.extractCursorPosition(screen,height);screen=this.applyLineResets(screen).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,changedRows=screen.map((line,row)=>line!==this.previousScreen[row]),imageAnchorsNeedRedraw=screen.some((line,row)=>changedRows[row]&&(isImageLine(line)||isImageLine(this.previousScreen[row]??""))),isWezTerm=!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()==="wezterm",imageCellsNeedRedraw=!imageAnchorsNeedRedraw&&isWezTerm&&this.imageProtocol==="kitty"&&changedRows.some(Boolean)&&screen.some((line,row)=>{let placementRows=getKittyImagePlacementRows(line);if(placementRows===void 0)return!1;for(let coveredRow=row;coveredRow<row+placementRows;coveredRow++)if(changedRows[coveredRow])return!0;return!1}),imagesNeedRedraw=imageAnchorsNeedRedraw||imageCellsNeedRedraw,redrawImages=fullRedraw||imagesNeedRedraw,hadUploadedKittyImages=this.uploadedKittyImages.size>0,preparedKittyScreen=redrawImages&&this.imageProtocol==="kitty"?this.prepareKittyScreen(screen):{lines:screen,evictedImageDeletion:""},buffer=BEGIN_SYNCHRONIZED_OUTPUT;if(fullRedraw){this.fullRedrawCount+=1;let clearImages=this.imageProtocol==="kitty"&&hadUploadedKittyImages?deleteAllKittyPlacements():this.deleteKittyImages();buffer+=`${clearImages}\x1B[2J`}else imagesNeedRedraw&&(this.imageProtocol==="iterm2"?buffer+="\x1B[2J":this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements()));if(buffer+=preparedKittyScreen.evictedImageDeletion,redrawImages&&this.imageProtocol==="kitty"&&screen.some(isImageLine)&&isWezTerm){for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")||(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")&&(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`)}else for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K${preparedKittyScreen.lines[row]??""}`);cursorPos?(buffer+=`\x1B[${cursorPos.row+1};${Math.min(width,cursorPos.col)+1}H`,buffer+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):buffer+="\x1B[?25l",buffer+=END_SYNCHRONIZED_OUTPUT,this.terminal.write(buffer),this.previousScreen=screen,this.previousScreenWidth=width,this.previousScreenHeight=height,this.currentLayout=nextLayout}};import*as fs2 from"node:fs";import*as os from"node:os";import*as path3 from"node:path";var OSC133_ZONE_PREFIX3=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,KITTY_SEQUENCE_PREFIX="\x1B_G",MAX_RENDER_WRITE_CHARS=1024*1024,BoundedTerminalWriter=class{buffer="";writtenChars=0;write;constructor(write){this.write=write}append(value){let offset=0;for(;offset<value.length;){let capacity=MAX_RENDER_WRITE_CHARS-this.buffer.length;if(capacity===0){this.flush();continue}let end=Math.min(value.length,offset+capacity);if(end<value.length&&value.charCodeAt(end-1)>=55296&&value.charCodeAt(end-1)<=56319&&value.charCodeAt(end)>=56320&&value.charCodeAt(end)<=57343&&end--,end===offset){this.flush();continue}this.buffer+=value.slice(offset,end),offset=end,this.buffer.length===MAX_RENDER_WRITE_CHARS&&this.flush()}}flush(){this.buffer&&(this.write(this.buffer),this.writtenChars+=this.buffer.length,this.buffer="")}get length(){return this.writtenChars+this.buffer.length}};function parseKittyImageHeader(line){let sequenceStart=line.indexOf(KITTY_SEQUENCE_PREFIX);if(sequenceStart===-1)return;let paramsStart=sequenceStart+KITTY_SEQUENCE_PREFIX.length,paramsEnd=line.indexOf(";",paramsStart);if(paramsEnd===-1)return;let ids=[],rows=1;for(let param of line.slice(paramsStart,paramsEnd).split(",")){let[key,value]=param.split("=",2);if(value===void 0)continue;let numberValue=Number(value);!Number.isInteger(numberValue)||numberValue<=0||numberValue>4294967295||(key==="i"?ids.push(numberValue):key==="r"&&(rows=numberValue))}return{ids,rows}}function extractKittyImageIds(line){return parseKittyImageHeader(line)?.ids??[]}function extractKittyImageRows(line){return parseKittyImageHeader(line)?.rows??1}function isTermuxSession(){return!!process.env.TERMUX_VERSION}var TuiMainScreen=class extends TuiBase{mode="regular";previousLines=[];previousKittyImageIds=new Set;previousWidth=0;previousHeight=0;cursorRow=0;hardwareCursorRow=0;maxLinesRendered=0;previousViewportTop=0;captureRenderState(){return{previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.previousLines=state.previousLines.map(line=>isImageLine(line)?"":line),this.previousKittyImageIds=new Set,this.previousWidth=state.previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.cursorRow,this.hardwareCursorRow=state.hardwareCursorRow,this.maxLinesRendered=state.maxLinesRendered,this.previousViewportTop=state.previousViewportTop}resetRenderState(){this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}beforeTerminalStop(options2){if(options2.preserveScreen||this.previousLines.length===0)return;this.terminal.write(" ");let lineDiff=this.previousLines.length-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
103
+ `);return text.length===0?void 0:text}async copySelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}async copyTextToClipboard(text){if(this.copySelection){let result=await this.copySelection(text),ok=result===!0;return this.flash(ok?"Copied!":typeof result=="string"?result:"Copy failed",ok?void 0:COPY_ERROR_FLASH_DURATION_MS),ok}return this.terminal.write(`\x1B]52;c;${Buffer.from(text).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(text,current){let style=current?this.searchCurrentMatchStyle:this.searchMatchStyle,result="",plainStart=0,index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){index+=1;continue}index>plainStart&&(result+=style(text.slice(plainStart,index))),result+=ansi.code,index+=ansi.length,plainStart=index}return plainStart<text.length&&(result+=style(text.slice(plainStart))),result}applySearchHighlights(screen,layout){let search=this.activeSearch;if(!search||search.selectedIndex<0||search.matches.length===0)return screen;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView);if(!box)return screen;let rangesByRow=new Map,scrollbarColumn=getScrollbarGeometry(box)?.column,minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length,box.rect.y+box.rect.height,box.clip.y+box.clip.height),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width,scrollbarColumn??Number.POSITIVE_INFINITY),minContentRow=scrollView.scrollTop+minRow-box.rect.y,maxContentRow=scrollView.scrollTop+maxRow-box.rect.y-1,low=0,high=search.matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2),match=search.matches[middle];(match.segments[match.segments.length-1]?.row??-1)<minContentRow?low=middle+1:high=middle}for(let matchIndex=low;matchIndex<search.matches.length;matchIndex++){let match=search.matches[matchIndex];if((match.segments[0]?.row??0)>maxContentRow)break;for(let segment of match.segments){let row=box.rect.y+segment.row-scrollView.scrollTop;if(row<minRow||row>=maxRow)continue;let startCol=Math.max(minColumn,box.rect.x+segment.startCol),endCol=Math.min(maxColumn,box.rect.x+segment.endCol);if(endCol<=startCol)continue;let ranges=rangesByRow.get(row)??[];ranges.push({startCol,endCol,current:matchIndex===search.selectedIndex}),rangesByRow.set(row,ranges)}}let result=[...screen];for(let[row,ranges]of rangesByRow){let line=result[row]??"";if(isImageLine(line))continue;let lineWidth=visibleWidth(line);for(let range of ranges.sort((a,b)=>b.startCol-a.startCol)){let startCol=Math.min(range.startCol,lineWidth),endCol=Math.min(range.endCol,lineWidth);if(endCol<=startCol)continue;let before=sliceByColumn(line,0,startCol,!0),highlighted=sliceByColumn(line,startCol,endCol-startCol,!0),after=sliceByColumn(line,endCol,Math.max(0,lineWidth-endCol),!0);line=`${before}${this.applySearchTextHighlight(highlighted,range.current)}${after}`}result[row]=line}return result}applySelectionHighlight(text){let result="\x1B[7m",index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){result+=text[index],index+=1;continue}result+=ansi.code,ansi.code.endsWith("m")&&(result+="\x1B[7m"),index+=ansi.length}return`${result}\x1B[27m`}applySelection(screen,layout=this.currentLayout){let selection=this.getSelectionBounds();if(!selection)return screen;let screenSelection=selection,minRow=0,maxRow=screen.length-1,minColumn=0,maxColumn=this.terminal.columns;if(selection.start.scrollView){if(!layout)return screen;let box=getScrollViewBox(layout,selection.start.scrollView);if(!box)return screen;minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width),screenSelection={start:{...selection.start,row:box.rect.y+selection.start.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.start.col},end:{...selection.end,row:box.rect.y+selection.end.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.end.col}}}return screen.map((line,row)=>{if(row<minRow||row>maxRow||row<screenSelection.start.row||row>screenSelection.end.row||isImageLine(line))return line;let lineWidth=visibleWidth(line),columns=this.getSelectionColumns(line,row,screenSelection,minColumn,maxColumn);if(columns.end<=columns.start)return line;let before=sliceByColumn(line,0,columns.start,!0),selected=sliceByColumn(line,columns.start,columns.end-columns.start,!0),after=sliceByColumn(line,columns.end,Math.max(0,lineWidth-columns.end),!0);return`${before}${this.applySelectionHighlight(selected)}${after}`})}isMouseSequence(data){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(data)||data.length===6&&data.startsWith("\x1B[M")}compositeScrollToEndIndicator(screen,layout,width){this.scrollToEndIndicatorRect=void 0;let scrollView=layout.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!scrollView.followEnd||scrollView.isFollowingEnd)return screen;let box=getScrollViewBox(layout,scrollView),clip=box?.clip;if(!clip||clip.width<=0||clip.height<=0)return screen;let row=clip.y+clip.height-1;if(row>=screen.length||isImageLine(screen[row]??""))return screen;let scrollbarColumn=box?getScrollbarGeometry(box)?.column:void 0,label=truncateToWidth(this.scrollToEndIndicator(),clip.width,""),labelWidth=visibleWidth(label),column=clip.x+Math.floor((clip.width-labelWidth)/2),rightEdge=scrollbarColumn??clip.x+clip.width,availableWidth=Math.max(0,rightEdge-column),text=truncateToWidth(label,availableWidth,""),textWidth=visibleWidth(text);if(textWidth===0)return screen;let result=[...screen];return result[row]=compositeTuiLine(result[row]??"",text,column,textWidth,width),this.scrollToEndIndicatorRect={row,column,width:textWidth},result}compositeFlashes(screen,width,height){let flashLines=this.flashes.render(width).slice(-height);if(flashLines.length===0)return screen;let result=[...screen];for(;result.length<height;)result.push("");for(let row=0;row<flashLines.length;row++){let line=flashLines[row],flashWidth=visibleWidth(line);flashWidth!==0&&(result[row]=compositeTuiLine(result[row]??"",line,width-flashWidth,flashWidth,width))}return result}doRender(){if(this.stopped||!this.altScreenActive)return;let width=Math.max(1,this.terminal.columns),height=Math.max(1,this.terminal.rows),root=this.layoutRoot??this.implicitScrollView,nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender());this.refreshSearch(nextLayout)&&(nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender()));let screen=this.resolveFakeCursors(nextLayout.lines.map(line=>line.replace(OSC133_ZONE_PREFIX2,"")));screen=this.applySearchHighlights(screen,nextLayout),screen=this.compositeScrollToEndIndicator(screen,nextLayout,width),screen=this.compositeOverlays(screen,width,height),screen.length>height&&(screen=screen.slice(screen.length-height)),screen=this.applySelection(screen,nextLayout),screen=this.compositeFlashes(screen,width,height);let cursorPos=this.extractCursorPosition(screen,height);screen=this.applyLineResets(screen).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,changedRows=screen.map((line,row)=>line!==this.previousScreen[row]),imageAnchorsNeedRedraw=screen.some((line,row)=>changedRows[row]&&(isImageLine(line)||isImageLine(this.previousScreen[row]??""))),imageCellsNeedRedraw=!imageAnchorsNeedRedraw&&this.imageProtocol==="kitty"&&changedRows.some(Boolean)&&screen.some((line,row)=>{let placementRows=getKittyImagePlacementRows(line);if(placementRows===void 0)return!1;for(let coveredRow=row;coveredRow<row+placementRows;coveredRow++)if(changedRows[coveredRow])return!0;return!1}),imagesNeedRedraw=imageAnchorsNeedRedraw||imageCellsNeedRedraw,redrawImages=fullRedraw||imagesNeedRedraw,hadUploadedKittyImages=this.uploadedKittyImages.size>0,preparedKittyScreen=redrawImages&&this.imageProtocol==="kitty"?this.prepareKittyScreen(screen):{lines:screen,evictedImageDeletion:""},buffer=BEGIN_SYNCHRONIZED_OUTPUT;if(fullRedraw?(this.fullRedrawCount+=1,this.imageProtocol==="kitty"&&hadUploadedKittyImages?buffer+=deleteAllKittyPlacements():buffer+=`${this.deleteKittyImages()}\x1B[2J`):imagesNeedRedraw&&(this.imageProtocol==="iterm2"?buffer+="\x1B[2J":this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements())),buffer+=preparedKittyScreen.evictedImageDeletion,redrawImages&&this.imageProtocol==="kitty"&&screen.some(isImageLine)){for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")||(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")&&(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`)}else for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K${preparedKittyScreen.lines[row]??""}`);cursorPos?(buffer+=`\x1B[${cursorPos.row+1};${Math.min(width,cursorPos.col)+1}H`,buffer+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):buffer+="\x1B[?25l",buffer+=END_SYNCHRONIZED_OUTPUT,this.terminal.write(buffer),this.previousScreen=screen,this.previousScreenWidth=width,this.previousScreenHeight=height,this.currentLayout=nextLayout}};import*as fs2 from"node:fs";import*as os from"node:os";import*as path3 from"node:path";var OSC133_ZONE_PREFIX3=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,KITTY_SEQUENCE_PREFIX="\x1B_G",MAX_RENDER_WRITE_CHARS=1024*1024,BoundedTerminalWriter=class{buffer="";writtenChars=0;write;constructor(write){this.write=write}append(value){let offset=0;for(;offset<value.length;){let capacity=MAX_RENDER_WRITE_CHARS-this.buffer.length;if(capacity===0){this.flush();continue}let end=Math.min(value.length,offset+capacity);if(end<value.length&&value.charCodeAt(end-1)>=55296&&value.charCodeAt(end-1)<=56319&&value.charCodeAt(end)>=56320&&value.charCodeAt(end)<=57343&&end--,end===offset){this.flush();continue}this.buffer+=value.slice(offset,end),offset=end,this.buffer.length===MAX_RENDER_WRITE_CHARS&&this.flush()}}flush(){this.buffer&&(this.write(this.buffer),this.writtenChars+=this.buffer.length,this.buffer="")}get length(){return this.writtenChars+this.buffer.length}};function parseKittyImageHeader(line){let sequenceStart=line.indexOf(KITTY_SEQUENCE_PREFIX);if(sequenceStart===-1)return;let paramsStart=sequenceStart+KITTY_SEQUENCE_PREFIX.length,paramsEnd=line.indexOf(";",paramsStart);if(paramsEnd===-1)return;let ids=[],rows=1;for(let param of line.slice(paramsStart,paramsEnd).split(",")){let[key,value]=param.split("=",2);if(value===void 0)continue;let numberValue=Number(value);!Number.isInteger(numberValue)||numberValue<=0||numberValue>4294967295||(key==="i"?ids.push(numberValue):key==="r"&&(rows=numberValue))}return{ids,rows}}function extractKittyImageIds(line){return parseKittyImageHeader(line)?.ids??[]}function extractKittyImageRows(line){return parseKittyImageHeader(line)?.rows??1}function isTermuxSession(){return!!process.env.TERMUX_VERSION}var TuiMainScreen=class extends TuiBase{mode="regular";previousLines=[];previousKittyImageIds=new Set;previousWidth=0;previousHeight=0;cursorRow=0;hardwareCursorRow=0;maxLinesRendered=0;previousViewportTop=0;captureRenderState(){return{previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.previousLines=state.previousLines.map(line=>isImageLine(line)?"":line),this.previousKittyImageIds=new Set,this.previousWidth=state.previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.cursorRow,this.hardwareCursorRow=state.hardwareCursorRow,this.maxLinesRendered=state.maxLinesRendered,this.previousViewportTop=state.previousViewportTop}resetRenderState(){this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}beforeTerminalStop(options2){if(options2.preserveScreen||this.previousLines.length===0)return;this.terminal.write(" ");let lineDiff=this.previousLines.length-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
103
104
  `)}collectKittyImageIds(lines){let ids=new Set;for(let line of lines)for(let id of extractKittyImageIds(line))ids.add(id);return ids}deleteKittyImages(ids){let buffer="";for(let id of ids)buffer+=deleteKittyImage(id);return buffer}getKittyImageReservedRows(lines,index,maxIndex=lines.length-1){let rows=extractKittyImageRows(lines[index]??"");if(rows<=1)return 1;let maxRows=Math.min(rows,maxIndex-index+1,lines.length-index),reservedRows=1;for(;reservedRows<maxRows;){let line=lines[index+reservedRows]??"";if(isImageLine(line)||visibleWidth(line)>0)break;reservedRows++}return reservedRows}expandChangedRangeForKittyImages(firstChanged,lastChanged,newLines){let expandedFirstChanged=firstChanged,expandedLastChanged=lastChanged,expandForLines=lines=>{for(let i=0;i<lines.length;i++){if(extractKittyImageIds(lines[i]).length===0)continue;let blockEnd=i+this.getKittyImageReservedRows(lines,i)-1;(i>=firstChanged||i<=lastChanged&&blockEnd>=firstChanged)&&(expandedFirstChanged=Math.min(expandedFirstChanged,i),expandedLastChanged=Math.max(expandedLastChanged,blockEnd))}};return expandForLines(this.previousLines),expandForLines(newLines),{firstChanged:expandedFirstChanged,lastChanged:expandedLastChanged}}deleteChangedKittyImages(firstChanged,lastChanged){if(firstChanged<0||lastChanged<firstChanged)return"";let ids=new Set,maxLine=Math.min(lastChanged,this.previousLines.length-1);for(let i=firstChanged;i<=maxLine;i++)for(let id of extractKittyImageIds(this.previousLines[i]??""))ids.add(id);return this.deleteKittyImages(ids)}doRender(){if(this.stopped)return;let width=this.terminal.columns,height=this.terminal.rows,widthChanged=this.previousWidth!==0&&this.previousWidth!==width,heightChanged=this.previousHeight!==0&&this.previousHeight!==height,previousBufferLength=this.previousHeight>0?this.previousViewportTop+this.previousHeight:height,prevViewportTop=heightChanged?Math.max(0,previousBufferLength-height):this.previousViewportTop,viewportTop=prevViewportTop,hardwareCursorRow=this.hardwareCursorRow,computeLineDiff=targetRow=>{let currentScreenRow=hardwareCursorRow-prevViewportTop;return targetRow-viewportTop-currentScreenRow},newLines=this.resolveFakeCursors(this.render(width).map(line=>line.replace(OSC133_ZONE_PREFIX3,"")));this.hasOverlayEntries&&(newLines=this.compositeOverlays(newLines,width,height));let cursorPos=this.extractCursorPosition(newLines,height);newLines=this.applyLineResets(newLines);let fullRender=clear=>{this.fullRedrawCount+=1;let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));output2.append("\x1B[?2026h"),clear&&(output2.append(this.deleteKittyImages(this.previousKittyImageIds)),output2.append("\x1B[2J\x1B[H\x1B[3J"));for(let i=0;i<newLines.length;i++){i>0&&output2.append(`\r
104
105
  `);let line=newLines[i],imageReservedRows=isImageLine(line)?this.getKittyImageReservedRows(newLines,i):1;if(imageReservedRows>1&&imageReservedRows<=height){for(let row=1;row<imageReservedRows;row++)output2.append(`\r
105
106
  `);output2.append(`\x1B[${imageReservedRows-1}A`),output2.append(line),output2.append(`\x1B[${imageReservedRows-1}B`),i+=imageReservedRows-1;continue}output2.append(line)}output2.append("\x1B[?2026l"),output2.flush(),this.cursorRow=Math.max(0,newLines.length-1),this.hardwareCursorRow=this.cursorRow,clear?this.maxLinesRendered=newLines.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length);let bufferLength=Math.max(height,newLines.length);this.previousViewportTop=Math.max(0,bufferLength-height),this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height},redrawLogDirectory=process.env.DRAHT_TUI_DEBUG_REDRAW==="1"?this.logDirectory:void 0,logRedraw=reason=>{if(redrawLogDirectory===void 0)return;let logPath=path3.join(redrawLogDirectory,"draht-tui-debug.log"),msg=`[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})
@@ -117,24 +118,20 @@ Please report this to https://github.com/markedjs/marked.`,silent){let msg="<p>A
117
118
  `):textBuffer,textBuffer=""},index=0;for(;index<html2.length;){if(isSpanOpenTagStart(html2,index)){let tagEndIndex=html2.indexOf(">",index+5);if(tagEndIndex!==-1){flushText();let tag2=html2.slice(index,tagEndIndex+1),scope=getScopeFromSpanTag(tag2);scopes.push(scope),index=tagEndIndex+1;continue}}if(html2.startsWith(SPAN_CLOSE,index)){flushText(),scopes.length>0&&scopes.pop(),index+=SPAN_CLOSE.length;continue}if(html2[index]==="&"){let decoded=decodeHtmlEntityAt(html2,index);if(decoded){textBuffer+=decoded.text,index+=decoded.length;continue}}textBuffer+=html2[index],index++}return flushText(),output}function highlight(code,options2={}){let html2=options2.language?import_core.default.highlight(code,{language:options2.language,ignoreIllegals:options2.ignoreIllegals}).value:import_core.default.highlightAuto(code,options2.languageSubset).value;return renderHighlightedHtml(html2,options2.theme)}function supportsLanguage(name){return import_core.default.getLanguage(name)!==void 0}function getHighlightLanguageCount(){return import_core.default.listLanguages().length}var SYSTEM_THEME_NAME="system",FAMILIES={neutral:{hue:231.49,saturation:{min:.02,max:.08},slot:8},blue:{hue:231.49,saturation:{min:.1,max:.68},slot:4},green:{hue:158.68,saturation:{min:.1,max:.76},slot:2},red:{hue:20,saturation:{min:.1,max:.92},slot:1},yellow:{hue:82.36,saturation:{min:.5,max:1},slot:3},orange:{hue:52,saturation:{min:.12,max:.85},slot:3},violet:{hue:295,saturation:{min:.2,max:.6},slot:5},calamine:{hue:202.43,saturation:{min:.1,max:.74},slot:6},thinkingSlate:{hue:231.49,saturation:{min:.08,max:.2},slot:4},thinkingBlue:{hue:231.49,saturation:{min:.2,max:.45},slot:4},thinkingPeriwinkle:{hue:263.25,saturation:{min:.3,max:.6},slot:6},thinkingViolet:{hue:295,saturation:{min:.4,max:.75},slot:5},thinkingMagenta:{hue:337.5,saturation:{min:.5,max:.85},slot:13},thinkingRed:{hue:20,saturation:{min:.95,max:1},slot:1}},TOKEN_FAMILIES={selectedBg:"blue",searchMatchBg:"orange",userMessageBg:"blue",customMessageBg:"violet",toolPendingBg:"neutral",toolSuccessBg:"green",toolErrorBg:"red",text:"neutral",userMessageText:"neutral",customMessageText:"neutral",toolTitle:"neutral",syntaxOperator:"neutral",syntaxPunctuation:"neutral",muted:"neutral",dim:"neutral",thinkingText:"neutral",toolOutput:"neutral",mdLinkUrl:"neutral",mdQuote:"neutral",mdQuoteBorder:"neutral",mdHr:"neutral",mdCodeBlockBorder:"neutral",toolDiffContext:"neutral",syntaxComment:"neutral",scrollbarTrack:"neutral",scrollbarThumb:"neutral",searchMatchText:"neutral",borderMuted:"neutral",accent:"violet",borderAccent:"violet",customMessageLabel:"violet",mdCode:"violet",mdListBullet:"violet",syntaxType:"violet",border:"blue",mdLink:"blue",syntaxKeyword:"blue",syntaxVariable:"calamine",success:"green",mdCodeBlock:"green",toolDiffAdded:"green",bashMode:"green",syntaxNumber:"green",error:"red",toolDiffRemoved:"red",warning:"yellow",mdHeading:"yellow",syntaxFunction:"yellow",syntaxString:"orange",thinkingOff:"neutral",thinkingMinimal:"thinkingSlate",thinkingLow:"thinkingBlue",thinkingMedium:"thinkingPeriwinkle",thinkingHigh:"thinkingViolet",thinkingXhigh:"thinkingMagenta",thinkingMax:"thinkingRed"},TOKEN_SLOTS={syntaxString:2,syntaxNumber:5,searchMatchBg:3},LEVELS={panel:{dark:{coefficients:[.29131,-.39746,2.33185,-.85524,-1.2076,.86276],reachable:[0,.979]},light:{coefficients:[-3.74073,27.94549,-78.44258,112.6798,-79.60015,22.11277],reachable:[.348,1]}},track:{dark:{coefficients:[.39028,-.23015,.83573,2.43829,-4.38292,2.01582],reachable:[0,.946]},light:{coefficients:[-5.24921,38.37322,-107.28833,152.10005,-106.17127,29.18061],reachable:[.368,1]}},thinking0:{dark:{coefficients:[.52988,-.05809,-.30924,4.63567,-6.52933,2.89108],reachable:[0,.873]},light:{coefficients:[-28.27749,182.85284,-469.62416,603.15916,-384.59976,97.35147],reachable:[.51,1]}},thinking1:{dark:{coefficients:[.55278,-.03667,-.45659,4.95347,-6.90265,3.0706],reachable:[0,.858]},light:{coefficients:[-37.10484,235.86282,-596.62344,754.3633,-474.00763,118.3551],reachable:[.535,1]}},thinking2:{dark:{coefficients:[.57486,-.01765,-.58987,5.25227,-7.27175,3.25532],reachable:[0,.842]},light:{coefficients:[-59.89653,377.05024,-945.07843,1182.03145,-734.96375,181.68658],reachable:[.556,1]}},thinking3:{dark:{coefficients:[.59621,-62e-5,-.71148,5.53588,-7.6392,3.44606],reachable:[0,.827]},light:{coefficients:[-72.07122,445.84082,-1099.57352,1353.88793,-829.53392,202.26164],reachable:[.58,1]}},thinking4:{dark:{coefficients:[.61691,.01462,-.82288,5.80651,-8.00641,3.64333],reachable:[0,.811]},light:{coefficients:[-110.14338,674.21488,-1645.75941,2004.32367,-1215.15899,293.3183],reachable:[.6,1]}},thinking5:{dark:{coefficients:[.63702,.02826,-.92498,6.06465,-8.37246,3.84651],reachable:[0,.795]},light:{coefficients:[-175.47701,1063.54495,-2570.70594,3098.80776,-1860.15527,444.76392],reachable:[.62,1]}},thinking6:{dark:{coefficients:[.65658,.04044,-1.01835,6.30989,-8.73529,4.05439],reachable:[0,.779]},light:{coefficients:[-183.81712,1094.70055,-2602.68539,3088.71276,-1826.91131,430.75931],reachable:[.643,1]}},subtle:{dark:{coefficients:[.56762,-.02475,-.5383,5.12628,-7.10931,3.17324],reachable:[0,.848]},light:{coefficients:[-232.85459,1376.54473,-3249.11801,3827.91186,-2248.29472,526.55751],reachable:[.657,1]}},thumb:{dark:{coefficients:[.60323,.00278,-.73328,5.57157,-7.68067,3.46933],reachable:[0,.823]},light:{coefficients:[-82.89897,511.01355,-1255.98095,1540.76821,-940.68087,228.58523],reachable:[.586,1]}},readable:{dark:{coefficients:[.66937,.04704,-1.06871,6.43941,-8.9332,4.17229],reachable:[0,.77]},light:{coefficients:[-1554.52576,8733.56817,-19604.93507,21977.72696,-12300.99599,2749.81288],reachable:[.751,1]}},emphasis:{dark:{coefficients:[.7303,.07695,-1.31626,7.1681,-10.14436,4.92846],reachable:[0,.712]},light:{coefficients:[-4948.31942,26870.91986,-58334.48399,63280.17197,-34298.01053,7430.30146],reachable:[.811,1]}},textOnPanel:{dark:{coefficients:[.86713,.05232,-.89428,4.79014,-5.5432,1.75023],reachable:[0,.542]},light:{coefficients:[-8570.89457,43954.60805,-90084.00702,92220.6791,-47152.15802,9632.27113],reachable:[.867,1]}},text:{dark:{coefficients:[.89242,.02311,-.44862,2.34417,-.06084,-2.63844],reachable:[0,.5]},light:{coefficients:[-2004.67048,6664.47299,-6060.70202,-1792.61209,5133.82359,-1939.85583],reachable:[.894,1]}}},TOOL_PANELS=["toolPendingBg","toolSuccessBg","toolErrorBg"],MESSAGE_PANELS=["userMessageBg","customMessageBg"],PANELS=["userMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg","selectedBg","searchMatchBg","customMessageBg"],THINKING=["thinkingOff","thinkingMinimal","thinkingLow","thinkingMedium","thinkingHigh","thinkingXhigh","thinkingMax"],THINKING_LEVELS=["thinking0","thinking1","thinking2","thinking3","thinking4","thinking5","thinking6"],each=(tokens,on,level)=>tokens.map(token=>({token,on,level})),RULES=[...each(PANELS,["background"],"panel"),{token:"text",on:["background"],level:"text"},{token:"text",on:["selectedBg"],level:"textOnPanel"},{token:"userMessageText",on:["userMessageBg"],level:"textOnPanel"},{token:"toolTitle",on:TOOL_PANELS,level:"textOnPanel"},...each(["accent","success","error","warning"],["background","selectedBg",...TOOL_PANELS],"readable"),{token:"muted",on:["background","selectedBg","customMessageBg",...TOOL_PANELS],level:"readable"},{token:"dim",on:["background","selectedBg","customMessageBg",...TOOL_PANELS],level:"subtle"},{token:"thinkingText",on:["background"],level:"readable"},{token:"customMessageText",on:["customMessageBg",...TOOL_PANELS],level:"readable"},{token:"customMessageLabel",on:["background","customMessageBg","selectedBg",...TOOL_PANELS],level:"readable"},{token:"toolOutput",on:["background",...TOOL_PANELS],level:"readable"},...each(["mdHeading","mdLink","mdLinkUrl","mdCode","mdQuote","mdCodeBlockBorder","mdListBullet"],["background",...MESSAGE_PANELS],"readable"),{token:"mdCodeBlock",on:["background",...MESSAGE_PANELS,...TOOL_PANELS],level:"readable"},...each(["toolDiffAdded","toolDiffRemoved","toolDiffContext"],["background",...TOOL_PANELS],"readable"),...each(["syntaxComment","syntaxKeyword","syntaxFunction","syntaxVariable","syntaxString","syntaxNumber","syntaxType","syntaxOperator","syntaxPunctuation"],["background",...MESSAGE_PANELS,...TOOL_PANELS],"readable"),{token:"searchMatchText",on:["searchMatchBg"],level:"readable"},...each(["bashMode","border","borderAccent"],["background"],"readable"),{token:"borderMuted",on:["background"],level:"subtle"},...each(["mdQuoteBorder","mdHr"],["background",...MESSAGE_PANELS,...TOOL_PANELS],"readable"),{token:"scrollbarTrack",on:["background"],level:"track"},{token:"scrollbarThumb",on:["scrollbarTrack"],level:"thumb"},...THINKING.map((token,index)=>({token,on:["background"],level:THINKING_LEVELS[index]}))],READABLE_FLOOR={dark:"readable",light:"subtle"},FOREGROUND_LEVEL="emphasis",FOREGROUND_TOKENS=["text","userMessageText","toolTitle"],TEXT_MINIMUM_WCAG_CONTRAST=4.5,SOLVE_ORDER=(()=>{let order=[],visit=token=>{if(!order.includes(token)){for(let rule of RULES)if(rule.token===token)for(let surface of rule.on)surface!=="background"&&visit(surface);order.push(token)}};for(let rule of RULES)visit(rule.token);return order})();function oklabLightness(color){return colorToOklch(rgbColor(color.r,color.g,color.b)).l}function relativeLuminance({r,g,b}){let linear=channel=>{let value=channel/255;return value<=.04045?value/12.92:((value+.055)/1.055)**2.4};return .2126*linear(r)+.7152*linear(g)+.0722*linear(b)}function wcagContrast(first,second){let a=relativeLuminance(first),b=relativeLuminance(second);return(Math.max(a,b)+.05)/(Math.min(a,b)+.05)}function terminalAppearance(background,foreground){let white={r:255,g:255,b:255},black={r:0,g:0,b:0},whiteContrast=wcagContrast(white,background),blackContrast=wcagContrast(black,background);if(foreground){let foregroundL=oklabLightness(foreground),backgroundL=oklabLightness(background);if(Math.abs(foregroundL-backgroundL)>.05){let appearance=foregroundL>backgroundL?"dark":"light";if((appearance==="dark"?whiteContrast:blackContrast)>=TEXT_MINIMUM_WCAG_CONTRAST)return appearance}}return whiteContrast>=blackContrast?"dark":"light"}var clamp2=(value,min,max)=>Math.min(max,Math.max(min,value));function hexOf({r,g,b}){return`#${[r,g,b].map(channel=>Math.round(channel).toString(16).padStart(2,"0")).join("")}`}function bellWeight(lightness){let gaussian=x=>Math.exp(-((x-.5)**2)/.125);return(gaussian(lightness)-gaussian(0))/(1-gaussian(0))}function saturationCurve({saturation:{min,max}},lightness){let floor=max>0?min/max:1;return floor+(1-floor)*bellWeight(lightness)}function levelTarget(level,appearance,surfaceL){let curve=LEVELS[level][appearance];if(!(surfaceL<curve.reachable[0]||surfaceL>curve.reachable[1]))return curve.coefficients.reduce((sum,coefficient,power)=>sum+coefficient*surfaceL**power,0)}function generateSystemThemeColors(input){let saturation=clamp2(input.saturation??1,0,1),{background,foreground}=input;if(!background)return indexedColors(saturation,input.appearanceHint);let palette=input.palette?.length===16?input.palette.map(sourceOf):void 0,appearance=terminalAppearance(background,foreground),lighter=appearance==="dark",extreme=lighter?1:0,backgroundL=oklabLightness(background),paint=(token,oklabL)=>{let lightness=oklabToOkhslLightness(oklabL),family=FAMILIES[TOKEN_FAMILIES[token]];if(!palette){let{min,max}=family.saturation;return okhslColor(family.hue,(min+(max-min)*bellWeight(lightness))*saturation,lightness)}return anchored(palette[TOKEN_SLOTS[token]??family.slot],family,lightness,saturation)},target=(level,surfaceL,t)=>{let reached=levelTarget(level,appearance,surfaceL);if(reached===void 0&&t===0)return;let distance=(reached??extreme)-surfaceL,floor=(levelTarget(READABLE_FLOOR[appearance],appearance,surfaceL)??extreme)-surfaceL,compressed=Math.abs(distance)>Math.abs(floor)?distance-(distance-floor)*Math.min(t,1):distance;return surfaceL+compressed*(1-Math.max(0,t-1))},extremeText=lighter?{r:255,g:255,b:255}:{r:0,g:0,b:0},readable=color=>wcagContrast(extremeText,color)>=TEXT_MINIMUM_WCAG_CONTRAST,limitPanel=(token,l)=>{let color=paint(token,l);if(readable(color))return color;let[low,high]=[backgroundL,l];for(let index=0;index<20;index++){let middle=(low+high)/2;readable(paint(token,middle))?low=middle:high=middle}return paint(token,low)},solve=t=>{let colors2=new Map([["background",background]]);for(let token of SOLVE_ORDER){let targets=[];for(let rule of RULES)if(rule.token===token)for(let surface of rule.on){let value=target(rule.level,oklabLightness(colors2.get(surface)??background),t);if(value===void 0||value<0||value>1)return;targets.push(value)}let l=lighter?Math.max(...targets):Math.min(...targets);colors2.set(token,PANELS.includes(token)?limitPanel(token,l):paint(token,l))}return colors2},relaxation=0,colors=solve(0);if(!colors){let[low,high]=[0,2];colors=solve(high);for(let index=0;index<20;index++){let middle=(low+high)/2,attempt=solve(middle);attempt?[high,colors]=[middle,attempt]:low=middle}relaxation=high}let solved=colors??new Map,surfacesOf=token=>RULES.filter(rule=>rule.token===token).flatMap(rule=>rule.on.map(surface=>solved.get(surface)??background)),result={};for(let token of Object.keys(TOKEN_FAMILIES)){let color=solved.get(token);result[token]=color?hexOf(color):""}for(let token of FOREGROUND_TOKENS){let surfaces=surfacesOf(token),text=solved.get(token);if(foreground){let targets=surfaces.map(surface=>target(FOREGROUND_LEVEL,oklabLightness(surface),relaxation));if(targets.every(value=>value!==void 0&&value>=0&&value<=1)){let needed=lighter?Math.max(...targets):Math.min(...targets),foregroundL=oklabLightness(foreground);if(lighter?foregroundL>=needed:foregroundL<=needed){result[token]="";continue}text=anchored(sourceOf(foreground),FAMILIES.neutral,oklabToOkhslLightness(needed),saturation)}}text&&(result[token]=hexOf(withTextContrast(text,surfaces,lighter)))}return{colors:result,dim:[],appearance}}function okhslOf({r,g,b}){return colorToOkhsl(rgbColor(r,g,b))}function sourceOf(color){return{...okhslOf(color),chroma:colorToOklch(rgbColor(color.r,color.g,color.b)).c}}function anchored(source,family,lightness,saturation){let anchor=saturationCurve(family,source.l),falloff=anchor>0?Math.min(1,saturationCurve(family,lightness)/anchor):1,color=okhslColor(source.h,source.s*falloff*saturation,lightness),cap=source.chroma*falloff*saturation,{l,c:c2}=colorToOklch(color);return c2<=cap?color:colorToRgb(oklchColor(l,cap,source.h))}function withTextContrast(color,surfaces,lighter){let meets=candidate=>surfaces.every(surface=>wcagContrast(candidate,surface)>=TEXT_MINIMUM_WCAG_CONTRAST);if(meets(color))return color;let{h,s,l}=okhslOf(color),at=lightness=>okhslColor(h,s,lightness),extreme=lighter?1:0;if(!meets(at(extreme)))return at(extreme);let[low,high]=[l,extreme];for(let index=0;index<20;index++){let middle=(low+high)/2;meets(at(middle))?high=middle:low=middle}return at(high)}function indexedColors(saturation,appearance){let colors={},dim=[];for(let[token,familyName]of Object.entries(TOKEN_FAMILIES)){if(PANELS.includes(token)){colors[token]="";continue}let neutral=familyName==="neutral";colors[token]=!neutral&&saturation>0?TOKEN_SLOTS[token]??FAMILIES[familyName].slot:"",neutral&&!FOREGROUND_TOKENS.includes(token)&&dim.push(token)}return{colors,dim,appearance}}function defineThemeTokens(tokens){for(let[name,descriptor]of Object.entries(tokens)){if(descriptor.fallback===void 0)continue;let fallback=tokens[descriptor.fallback];if(fallback===void 0)throw new Error(`Theme token ${name} has unknown fallback ${descriptor.fallback}`);if(fallback.slot!==descriptor.slot)throw new Error(`Theme token ${name} has fallback ${descriptor.fallback} in a different color slot`)}return tokens}var THEME_TOKENS=defineThemeTokens({accent:{slot:"foreground",description:"Primary accent color (logo, selected items, cursor)"},border:{slot:"foreground",description:"Normal borders"},borderAccent:{slot:"foreground",description:"Highlighted borders"},borderMuted:{slot:"foreground",description:"Subtle borders"},success:{slot:"foreground",description:"Success states"},error:{slot:"foreground",description:"Error states"},warning:{slot:"foreground",description:"Warning states"},muted:{slot:"foreground",description:"Secondary/dimmed text"},dim:{slot:"foreground",description:"Very dimmed text (more subtle than muted)"},text:{slot:"foreground",description:"Default text color (usually empty string)"},thinkingText:{slot:"foreground",description:"Thinking block text color"},scrollbarTrack:{slot:"foreground",description:"Fullscreen scrollbar track foreground (falls back to muted when omitted)",fallback:"muted"},scrollbarThumb:{slot:"foreground",description:"Fullscreen scrollbar thumb foreground (falls back to text when omitted)",fallback:"text"},selectedBg:{slot:"background",description:"Selected item background"},searchMatchBg:{slot:"background",description:"Transcript search match background and current-match text (falls back to selectedBg when omitted)",fallback:"selectedBg"},searchMatchText:{slot:"foreground",description:"Transcript search match text and current-match background (falls back to text when omitted)",fallback:"text"},userMessageBg:{slot:"background",description:"User message background"},userMessageText:{slot:"foreground",description:"User message text color"},customMessageBg:{slot:"background",description:"Custom message background (hook-injected messages)"},customMessageText:{slot:"foreground",description:"Custom message text color"},customMessageLabel:{slot:"foreground",description:"Custom message type label color"},toolPendingBg:{slot:"background",description:"Tool execution box (pending state)"},toolSuccessBg:{slot:"background",description:"Tool execution box (success state)"},toolErrorBg:{slot:"background",description:"Tool execution box (error state)"},toolTitle:{slot:"foreground",description:"Tool execution box title color"},toolOutput:{slot:"foreground",description:"Tool execution box output text color"},mdHeading:{slot:"foreground",description:"Markdown heading text"},mdLink:{slot:"foreground",description:"Markdown link text"},mdLinkUrl:{slot:"foreground",description:"Markdown link URL"},mdCode:{slot:"foreground",description:"Markdown inline code"},mdCodeBlock:{slot:"foreground",description:"Markdown code block content"},mdCodeBlockBorder:{slot:"foreground",description:"Markdown code block fences"},mdQuote:{slot:"foreground",description:"Markdown blockquote text"},mdQuoteBorder:{slot:"foreground",description:"Markdown blockquote border"},mdHr:{slot:"foreground",description:"Markdown horizontal rule"},mdListBullet:{slot:"foreground",description:"Markdown list bullets/numbers"},toolDiffAdded:{slot:"foreground",description:"Added lines in tool diffs"},toolDiffRemoved:{slot:"foreground",description:"Removed lines in tool diffs"},toolDiffContext:{slot:"foreground",description:"Context lines in tool diffs"},syntaxComment:{slot:"foreground",description:"Syntax highlighting: comments"},syntaxKeyword:{slot:"foreground",description:"Syntax highlighting: keywords"},syntaxFunction:{slot:"foreground",description:"Syntax highlighting: function names"},syntaxVariable:{slot:"foreground",description:"Syntax highlighting: variable names"},syntaxString:{slot:"foreground",description:"Syntax highlighting: string literals"},syntaxNumber:{slot:"foreground",description:"Syntax highlighting: number literals"},syntaxType:{slot:"foreground",description:"Syntax highlighting: type names"},syntaxOperator:{slot:"foreground",description:"Syntax highlighting: operators"},syntaxPunctuation:{slot:"foreground",description:"Syntax highlighting: punctuation"},thinkingOff:{slot:"foreground",description:"Thinking level border: off"},thinkingMinimal:{slot:"foreground",description:"Thinking level border: minimal"},thinkingLow:{slot:"foreground",description:"Thinking level border: low"},thinkingMedium:{slot:"foreground",description:"Thinking level border: medium"},thinkingHigh:{slot:"foreground",description:"Thinking level border: high"},thinkingXhigh:{slot:"foreground",description:"Thinking level border: xhigh"},thinkingMax:{slot:"foreground",description:"Thinking level border: max (falls back to thinkingXhigh when omitted)",fallback:"thinkingXhigh"},bashMode:{slot:"foreground",description:"Editor border color in bash mode"}});var themeJsonValidator;function setThemeJsonValidator(validator){themeJsonValidator=validator}function resolveVarRefs(value,vars,visited=new Set){if(typeof value=="number"||value===""||value.startsWith("#")||/^ok(lch|hsl)\(/i.test(value))return value;if(visited.has(value))throw new Error(`Circular variable reference detected: ${value}`);if(!(value in vars))throw new Error(`Variable reference not found: ${value}`);return visited.add(value),resolveVarRefs(vars[value],vars,visited)}function resolveThemeColors(colors,vars={}){let resolved={};for(let[key,value]of Object.entries(colors))resolved[key]=resolveVarRefs(value,vars);return resolved}function withThemeTokenFallbacks(values){let resolved={...values};for(let[rawName,descriptor]of Object.entries(THEME_TOKENS)){if(!("fallback"in descriptor))continue;let name=rawName;if(resolved[name]!==void 0)continue;let fallback=descriptor.fallback,fallbackValue=resolved[fallback];if(fallbackValue===void 0)throw new Error(`Theme token ${rawName} has unresolved fallback ${descriptor.fallback}`);resolved[name]=fallbackValue}return resolved}var terminalColors={},terminalColorsPending=!1,terminalColorScheme;function setTerminalColors(colors){terminalColors={...colors},terminalColorsPending=!1}function setTerminalColorScheme(scheme){terminalColorScheme=scheme}function markTerminalColorsPending(){terminalColorsPending=!0}var GUESSED_DEFAULT_COLORS={dark:{foreground:parseColor("#e5e5e7"),background:parseColor("#000000")},light:{foreground:parseColor("#000000"),background:parseColor("#ffffff")}};function averageLightness(colors){let fixed=colors.filter(color=>color.kind!=="indexed"||color.index>=16);if(fixed.length!==0)return fixed.reduce((sum,color)=>sum+colorToOklch(color).l,0)/fixed.length}function detectAppearance(foregrounds,backgrounds){let fg=averageLightness(foregrounds),bg=averageLightness(backgrounds);if(fg!==void 0&&bg!==void 0)return bg<fg?"dark":"light";if(bg!==void 0)return bg<.5?"dark":"light";if(fg!==void 0)return fg>.5?"dark":"light"}var Theme=class{name;sourcePath;sourceInfo;mode;fgAnsi=new Map;bgAnsi=new Map;concreteColors={};defaultForegroundTokens=[];defaultBackgroundTokens=[];dimTokens;ownAppearance;resolvedColors;constructor(fgColors,bgColors,mode,options2={}){this.name=options2.name,this.sourcePath=options2.sourcePath,this.sourceInfo=options2.sourceInfo,this.mode=mode,this.dimTokens=new Set(options2.dim);let{fgColors:foregrounds,bgColors:backgrounds}=splitThemeColors(withThemeTokenFallbacks({...fgColors,...bgColors})),concreteForegrounds=[],concreteBackgrounds=[],addToken=(token,value,isBackground)=>{if(value==="")return(isBackground?this.defaultBackgroundTokens:this.defaultForegroundTokens).push(token),isBackground?"\x1B[49m":"\x1B[39m";let color=parseColor(value);return this.concreteColors[token]=color,(isBackground?concreteBackgrounds:concreteForegrounds).push(color),isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode)};for(let[token,value]of Object.entries(foregrounds))this.fgAnsi.set(token,addToken(token,value,!1));for(let[token,value]of Object.entries(backgrounds))this.bgAnsi.set(token,addToken(token,value,!0));this.ownAppearance=options2.appearance??detectAppearance(concreteForegrounds,concreteBackgrounds)}get appearance(){return this.ownAppearance??getTerminalTheme()}get colors(){let terminal=terminalColors;if(this.resolvedColors?.terminal!==terminal){let guess=GUESSED_DEFAULT_COLORS[this.appearance],toColor=(rgb,fallback)=>rgb?rgbColor(rgb.r,rgb.g,rgb.b):fallback,foreground=toColor(terminal.foreground,guess.foreground),background=toColor(terminal.background,guess.background),colors={...this.concreteColors};for(let token of this.defaultForegroundTokens)colors[token]=foreground;for(let token of this.defaultBackgroundTokens)colors[token]=background;for(let token of this.dimTokens){let color=colors[token];color&&(colors[token]=mixColors(color,background,.4))}this.resolvedColors={terminal,colors:Object.freeze(colors)}}return this.resolvedColors.colors}style(text,options2){let{fg,bg}=options2;return typeof fg=="string"&&this.dimTokens.has(fg)&&(options2={...options2,dim:!0}),styleTextWithAnsi(text,fg===void 0?void 0:typeof fg=="string"?this.tokenAnsi(this.fgAnsi,fg):foregroundAnsi(fg,this.mode),bg===void 0?void 0:typeof bg=="string"?this.tokenAnsi(this.bgAnsi,bg):backgroundAnsi(bg,this.mode),options2)}fg(color,text){let ansi=this.tokenAnsi(this.fgAnsi,color);return this.dimTokens.has(color)?`${ansi}\x1B[2m${text}\x1B[22;39m`:`${ansi}${text}\x1B[39m`}bg(color,text){return`${this.tokenAnsi(this.bgAnsi,color)}${text}\x1B[49m`}tokenAnsi(ansi,token){let value=ansi.get(token);if(value===void 0)throw new Error(`Unknown theme color: ${token}`);return value}bold(text){return source_default.bold(text)}italic(text){return source_default.italic(text)}underline(text){return source_default.underline(text)}inverse(text){return source_default.inverse(text)}strikethrough(text){return source_default.strikethrough(text)}getFgAnsi(color){let ansi=this.tokenAnsi(this.fgAnsi,color);return this.dimTokens.has(color)?`${ansi}\x1B[2m`:ansi}getBgAnsi(color){return this.tokenAnsi(this.bgAnsi,color)}getColorMode(){return this.mode}getThinkingBorderColor(level){switch(level){case"off":return str2=>this.fg("thinkingOff",str2);case"minimal":return str2=>this.fg("thinkingMinimal",str2);case"low":return str2=>this.fg("thinkingLow",str2);case"medium":return str2=>this.fg("thinkingMedium",str2);case"high":return str2=>this.fg("thinkingHigh",str2);case"xhigh":return str2=>this.fg("thinkingXhigh",str2);case"max":return str2=>this.fg("thinkingMax",str2);default:return str2=>this.fg("thinkingOff",str2)}}getBashModeBorderColor(){return str2=>this.fg("bashMode",str2)}},BUILTIN_THEMES;function getBuiltinThemes(){if(!BUILTIN_THEMES){let themesDir=getThemesDir(),darkPath=path4.join(themesDir,"dark.json"),lightPath=path4.join(themesDir,"light.json");BUILTIN_THEMES={dark:JSON.parse(stripBom(fs3.readFileSync(darkPath,"utf-8"))),light:JSON.parse(stripBom(fs3.readFileSync(lightPath,"utf-8")))}}return BUILTIN_THEMES}function getAvailableThemes(){return getAvailableThemesWithPaths().map(({name})=>name)}function getAvailableThemesWithPaths(){let themesDir=getThemesDir(),result=[],seen=new Set,addTheme=themeInfo=>{seen.has(themeInfo.name)||(seen.add(themeInfo.name),result.push(themeInfo))};addTheme({name:SYSTEM_THEME_NAME,path:void 0});for(let name of Object.keys(getBuiltinThemes()))addTheme({name,path:path4.join(themesDir,`${name}.json`)});for(let themeInfo of getCustomThemeInfos())addTheme(themeInfo);for(let[name,theme2]of registeredThemes.entries())addTheme({name,path:theme2.sourcePath});return result.sort((a,b)=>a.name===SYSTEM_THEME_NAME?-1:b.name===SYSTEM_THEME_NAME?1:a.name.localeCompare(b.name))}function getCustomThemeInfos(){let customThemesDir=getCustomThemesDir(),result=[];if(!fs3.existsSync(customThemesDir))return result;for(let file of fs3.readdirSync(customThemesDir)){if(!file.endsWith(".json"))continue;let themePath=path4.join(customThemesDir,file);try{let customTheme=loadThemeFromPath(themePath);customTheme.name&&result.push({name:customTheme.name,path:themePath})}catch{}}return result}function assertThemeNameIsValid(name){if(name.includes("/"))throw new Error(`Invalid theme name "${name}": theme names cannot contain "/" because it is reserved for automatic light/dark theme settings.`)}function parseThemeJson(label,json2){if(themeJsonValidator)return themeJsonValidator(label,json2);if(typeof json2!="object"||json2===null||!("colors"in json2))throw new Error(`Invalid theme "${label}": expected an object with a "colors" map.`);return json2}function parseThemeJsonContent(label,content){let json2;try{json2=JSON.parse(stripBom(content))}catch(error){throw new Error(`Failed to parse theme ${label}: ${error}`)}return parseThemeJson(label,json2)}function loadThemeJson(name){let builtinThemes=getBuiltinThemes();if(name in builtinThemes)return builtinThemes[name];let registeredTheme=registeredThemes.get(name);if(registeredTheme?.sourcePath){let content2=fs3.readFileSync(registeredTheme.sourcePath,"utf-8");return parseThemeJsonContent(registeredTheme.sourcePath,content2)}if(registeredTheme)throw new Error(`Theme "${name}" does not have a source path for export`);let customThemesDir=getCustomThemesDir(),themePath=path4.join(customThemesDir,`${name}.json`);if(!fs3.existsSync(themePath))throw new Error(`Theme not found: ${name}`);let content=fs3.readFileSync(themePath,"utf-8");return parseThemeJsonContent(name,content)}function splitThemeColors(colors){let fgColors={},bgColors={};for(let[key,value]of Object.entries(colors))THEME_TOKENS[key].slot==="background"?bgColors[key]=value:fgColors[key]=value;return{fgColors,bgColors}}function createTheme(themeJson,mode,sourcePath){let colorMode=mode??getTerminalColorMode(),resolvedColors=withThemeTokenFallbacks(resolveThemeColors(themeJson.colors,themeJson.vars)),{fgColors,bgColors}=splitThemeColors(resolvedColors);return new Theme(fgColors,bgColors,colorMode,{name:themeJson.name,sourcePath,appearance:themeJson.appearance})}function createSystemTheme(mode){let generated=generateSystemThemeColors({...terminalColors,saturation:terminalColorsPending?0:1,appearanceHint:getTerminalTheme()}),{fgColors,bgColors}=splitThemeColors(withThemeTokenFallbacks(generated.colors));return new Theme(fgColors,bgColors,mode??getTerminalColorMode(),{name:SYSTEM_THEME_NAME,appearance:generated.appearance,dim:generated.dim})}function loadThemeFromPath(themePath,mode){let content=fs3.readFileSync(themePath,"utf-8"),themeJson=parseThemeJsonContent(themePath,content);return createTheme(themeJson,mode,themePath)}function loadTheme(name,mode){if(name===SYSTEM_THEME_NAME)return createSystemTheme(mode);let registeredTheme=registeredThemes.get(name);if(registeredTheme)return registeredTheme;let themeJson=loadThemeJson(name);return createTheme(themeJson,mode)}function getThemeByName(name){try{return loadTheme(name)}catch{return}}function parseAutoThemeSetting(themeSetting){if(!themeSetting)return;let slashIndex=themeSetting.indexOf("/");if(slashIndex===-1||themeSetting.indexOf("/",slashIndex+1)!==-1)return;let lightTheme=themeSetting.slice(0,slashIndex).trim(),darkTheme=themeSetting.slice(slashIndex+1).trim();if(!(!lightTheme||!darkTheme))return{lightTheme,darkTheme}}function resolveThemeSetting(themeSetting,terminalTheme){let autoTheme=parseAutoThemeSetting(themeSetting);if(autoTheme)return terminalTheme==="light"?autoTheme.lightTheme:autoTheme.darkTheme;if(!themeSetting?.includes("/")&&typeof themeSetting=="string")return themeSetting}function detectColorFgBgTheme(env=process.env){let bg=env.COLORFGBG?.split(";").at(-1)?.trim();if(!bg||!/^\d{1,2}$/.test(bg))return;let index=Number(bg);if(!(index>15))return index<=6||index===8?"dark":"light"}function detectTerminalTheme(colors={},reportedScheme,env=process.env){let{background,foreground}=colors;return background?terminalAppearance(background,foreground):reportedScheme??detectColorFgBgTheme(env)??"dark"}function getTerminalTheme(){return detectTerminalTheme(terminalColors,terminalColorScheme)}var THEME_KEY=Symbol.for("@draht/coding-agent:theme"),THEME_KEY_OLD=Symbol.for("@draht/coding-agent:theme"),theme=new Proxy({},{get(_target,prop){let t=globalThis[THEME_KEY];if(!t)throw new Error("Theme not initialized. Call initTheme() first.");return t[prop]}});function getGlobalTheme(){return globalThis[THEME_KEY]}function setGlobalTheme(t){globalThis[THEME_KEY]=t,globalThis[THEME_KEY_OLD]=t}var currentThemeName,themeWatcher,themeReloadTimer,onThemeChangeCallback,registeredThemes=new Map;function setRegisteredThemes(themes){registeredThemes.clear();for(let theme2 of themes)theme2.name&&(assertThemeNameIsValid(theme2.name),registeredThemes.set(theme2.name,theme2))}function initTheme(themeName,enableWatcher=!1){let name=themeName??getTerminalTheme();currentThemeName=name;try{setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher()}catch{let fallback=getTerminalTheme();currentThemeName=fallback,setGlobalTheme(loadTheme(fallback))}}function setTheme(name,enableWatcher=!1){currentThemeName=name;try{return setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher(),onThemeChangeCallback&&onThemeChangeCallback(),{success:!0}}catch(error){let fallback=getTerminalTheme();return currentThemeName=fallback,setGlobalTheme(loadTheme(fallback)),{success:!1,error:error instanceof Error?error.message:String(error)}}}function setThemeInstance(themeInstance){setGlobalTheme(themeInstance),currentThemeName="<in-memory>",stopThemeWatcher(),onThemeChangeCallback&&onThemeChangeCallback()}function onThemeChange(callback){onThemeChangeCallback=callback}function startThemeWatcher(){if(stopThemeWatcher(),!currentThemeName||currentThemeName==="dark"||currentThemeName==="light"||currentThemeName===SYSTEM_THEME_NAME)return;let customThemesDir=getCustomThemesDir(),watchedThemeName=currentThemeName,watchedFileName=`${watchedThemeName}.json`,themeFile=path4.join(customThemesDir,watchedFileName);if(!fs3.existsSync(themeFile))return;let scheduleReload=()=>{themeReloadTimer&&clearTimeout(themeReloadTimer),themeReloadTimer=setTimeout(()=>{if(themeReloadTimer=void 0,currentThemeName===watchedThemeName&&fs3.existsSync(themeFile))try{let reloadedTheme=loadThemeFromPath(themeFile);registeredThemes.set(watchedThemeName,reloadedTheme),setGlobalTheme(reloadedTheme),onThemeChangeCallback&&onThemeChangeCallback()}catch{}},100)};themeWatcher=watchWithErrorHandler(customThemesDir,(_eventType,filename)=>{if(currentThemeName===watchedThemeName){if(!filename){scheduleReload();return}filename===watchedFileName&&scheduleReload()}},()=>{closeWatcher(themeWatcher),themeWatcher=void 0})??void 0}function stopThemeWatcher(){themeReloadTimer&&(clearTimeout(themeReloadTimer),themeReloadTimer=void 0),closeWatcher(themeWatcher),themeWatcher=void 0}function getResolvedThemeColors(themeName){let colors=loadTheme(themeName??currentThemeName??SYSTEM_THEME_NAME).colors;return Object.fromEntries(Object.entries(colors).map(([token,color])=>[token,colorToHex(color)]))}function getThemeExportColors(themeName){let name=themeName??currentThemeName??SYSTEM_THEME_NAME;if(name===SYSTEM_THEME_NAME)return{};try{let themeJson=loadThemeJson(name),exportSection=themeJson.export;if(!exportSection)return{};let vars=themeJson.vars??{},resolve=value=>{if(value===void 0)return;let resolved=resolveVarRefs(value,vars);if(typeof resolved=="number")return colorToHex(indexedColor(resolved));if(resolved!=="")return/^okhsl\(/i.test(resolved)?colorToHex(parseColor(resolved)):resolved};return{pageBg:resolve(exportSection.pageBg),cardBg:resolve(exportSection.cardBg),infoBg:resolve(exportSection.infoBg)}}catch{return{}}}var cachedHighlightThemeFor,cachedCliHighlightTheme;function buildCliHighlightTheme(t){return{keyword:s=>t.fg("syntaxKeyword",s),built_in:s=>t.fg("syntaxType",s),literal:s=>t.fg("syntaxNumber",s),number:s=>t.fg("syntaxNumber",s),regexp:s=>t.fg("syntaxString",s),string:s=>t.fg("syntaxString",s),subst:s=>t.fg("text",s),comment:s=>t.fg("syntaxComment",s),doctag:s=>t.fg("syntaxComment",s),meta:s=>t.fg("muted",s),function:s=>t.fg("syntaxFunction",s),title:s=>t.fg("syntaxFunction",s),class:s=>t.fg("syntaxType",s),type:s=>t.fg("syntaxType",s),tag:s=>t.fg("syntaxPunctuation",s),name:s=>t.fg("syntaxKeyword",s),attr:s=>t.fg("syntaxVariable",s),variable:s=>t.fg("syntaxVariable",s),params:s=>t.fg("syntaxVariable",s),operator:s=>t.fg("syntaxOperator",s),punctuation:s=>t.fg("syntaxPunctuation",s),emphasis:s=>t.italic(s),strong:s=>t.bold(s),link:s=>t.underline(s),addition:s=>t.fg("toolDiffAdded",s),deletion:s=>t.fg("toolDiffRemoved",s)}}function getCliHighlightTheme(t){return(cachedHighlightThemeFor!==t||!cachedCliHighlightTheme)&&(cachedHighlightThemeFor=t,cachedCliHighlightTheme=buildCliHighlightTheme(t)),cachedCliHighlightTheme}function highlightCode(code,lang){let validLang=lang&&supportsLanguage(lang)?lang:void 0;if(!validLang)return code.split(`
118
119
  `).map(line=>theme.fg("mdCodeBlock",line));let opts={language:validLang,ignoreIllegals:!0,theme:getCliHighlightTheme(theme)};try{return highlight(code,opts).split(`
119
120
  `)}catch{return code.split(`
120
- `).map(line=>theme.fg("mdCodeBlock",line))}}var CodeHighlighter=class{last;highlight(code,lang){let currentTheme=getGlobalTheme(),languageCount=getHighlightLanguageCount(),last=this.last;if(last?.code===code&&last.lang===lang&&last.theme===currentTheme&&last.languageCount===languageCount)return last.lines;let lines=highlightCode(code,lang);return this.last={code,lang,theme:currentTheme,languageCount,lines},lines}};function getLanguageFromPath(filePath){let ext=filePath.split(".").pop()?.toLowerCase();return ext?{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",dart:"dart",groovy:"groovy",gradle:"groovy",nix:"nix",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"dockerfile",makefile:"makefile",cmake:"cmake",lua:"lua",perl:"perl",r:"r",scala:"scala",clj:"clojure",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",ml:"ocaml",vim:"vim",graphql:"graphql",proto:"protobuf",tf:"hcl",hcl:"hcl"}[ext]:void 0}function getMarkdownTheme(){return{heading:text=>theme.fg("mdHeading",text),link:text=>theme.fg("mdLink",text),linkUrl:text=>theme.fg("mdLinkUrl",text),code:text=>theme.fg("mdCode",text),codeBlock:text=>theme.fg("mdCodeBlock",text),codeBlockBorder:text=>theme.fg("mdCodeBlockBorder",text),quote:text=>theme.fg("mdQuote",text),quoteBorder:text=>theme.fg("mdQuoteBorder",text),hr:text=>theme.fg("mdHr",text),listBullet:text=>theme.fg("mdListBullet",text),bold:text=>theme.bold(text),italic:text=>theme.italic(text),underline:text=>theme.underline(text),strikethrough:text=>theme.strikethrough(text),highlightCode}}function getSelectListTheme(){return{selectedPrefix:text=>theme.fg("accent",text),selectedText:text=>theme.fg("accent",text),description:text=>theme.fg("muted",text),scrollInfo:text=>theme.fg("muted",text),noMatch:text=>theme.fg("muted",text)}}function getEditorTheme(){return{borderColor:text=>theme.fg("borderMuted",text),selectList:getSelectListTheme()}}function getSettingsListTheme(){return{label:(text,selected)=>selected?theme.fg("accent",text):text,value:(text,selected)=>selected?theme.fg("accent",text):theme.fg("muted",text),description:text=>theme.fg("dim",text),cursor:theme.fg("accent","\u2192 "),hint:text=>theme.fg("dim",text)}}function formatKeyPart(part,options2){let displayPart=process.platform==="darwin"&&part.toLowerCase()==="alt"?"option":part;return options2.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options2={}){return key.split("/").map(k=>k.split("+").map(part=>formatKeyPart(part,options2)).join("+")).join("/")}function formatKeys(keys,options2={}){return keys.length===0?"":formatKeyText(keys.join("/"),options2)}function keyText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding))}var ARROW_GLYPHS={up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192"};function combinedKeyText(keybindings){let perBinding=keybindings.map(id=>getKeybindings().getKeys(id));return perBinding.every(keys=>keys.length===1&&keys[0]in ARROW_GLYPHS)?perBinding.map(keys=>ARROW_GLYPHS[keys[0]]).join(""):keybindings.map(id=>keyText(id)).join("/")}function combinedKeyHint(keybindings,description){return theme.fg("dim",combinedKeyText(keybindings))+theme.fg("muted",` ${description}`)}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}function isValidUsage(value){if(typeof value!="object"||value===null)return!1;let u=value;if(![u.input,u.output,u.cacheRead,u.cacheWrite,u.totalTokens].every(n=>typeof n=="number"&&Number.isFinite(n))||typeof u.cost!="object"||u.cost===null)return!1;let cost=u.cost;return[cost.input,cost.output,cost.cacheRead,cost.cacheWrite,cost.total].every(n=>typeof n=="number"&&Number.isFinite(n))}function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{input:first.input+second.input,output:first.output+second.output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total,totalFromProvider:first.cost.totalFromProvider===!0&&second.cost.totalFromProvider===!0}}}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let entry of entries){let key,usage;if(entry.type==="message"&&entry.message.role==="assistant"?(key=`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage=entry.message.usage):entry.type==="usage"?(key=`${entry.provider}/${entry.model}`,usage=entry.usage):entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage?(key="Tools/summaries",usage=entry.message.usage):(entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage&&(key="Tools/summaries",usage=entry.usage),!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).filter(entry=>entry.cost>0||entry.tokens>0).sort((a,b)=>b.cost-a.cost)}var DEFAULT_MAX_LINES=2e3,DEFAULT_MAX_BYTES=51200;function splitLinesForCounting(content){if(content.length===0)return[];let lines=content.split(`
121
- `);return content.endsWith(`
122
- `)&&lines.pop(),lines}function formatSize(bytes){return bytes<1024?`${bytes}B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)}KB`:`${(bytes/(1024*1024)).toFixed(1)}MB`}function truncateHead(content,options2={}){let maxLines=options2.maxLines??2e3,maxBytes=options2.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};if(Buffer.byteLength(lines[0],"utf-8")>maxBytes)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines,totalBytes,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines";for(let i=0;i<lines.length&&i<maxLines;i++){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(i>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";break}outputLinesArr.push(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
123
- `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content,options2={}){let maxLines=options2.maxLines??2e3,maxBytes=options2.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines",lastLinePartial=!1;for(let i=lines.length-1;i>=0&&outputLinesArr.length<maxLines;i--){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(outputLinesArr.length>0?1:0);if(outputBytesCount+lineBytes>maxBytes){if(truncatedBy="bytes",outputLinesArr.length===0){let truncatedLine=truncateStringToBytesFromEnd(line,maxBytes);outputLinesArr.unshift(truncatedLine),outputBytesCount=Buffer.byteLength(truncatedLine,"utf-8"),lastLinePartial=!0}break}outputLinesArr.unshift(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
124
- `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateStringToBytesFromEnd(str2,maxBytes){let buf=Buffer.from(str2,"utf-8");if(buf.length<=maxBytes)return str2;let start=buf.length-maxBytes;for(;start<buf.length&&(buf[start]&192)===128;)start++;return buf.slice(start).toString("utf-8")}function truncateLine(line,maxChars=500){return line.length<=maxChars?{text:line,wasTruncated:!1}:{text:`${line.slice(0,maxChars)}... [truncated]`,wasTruncated:!0}}import{pathToFileURL as pathToFileURL2}from"node:url";var ST="(?:\\u0007|\\u001B\\u005C|\\u009C)",OSC_START="\\u001B\\]",CSI_START="(?:(?:\\u001B\\[|\\u009B)[<=>]|[\\u001B\\u009B][[\\]()#;?]*)(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",CSI_FINAL="[\\dA-PR-TZcf-nq-uy=><~]",ansiRegex=new RegExp(`(?:${OSC_START}[\\s\\S]*?${ST})|${CSI_START}${CSI_FINAL}`,"g"),unfinishedAnsiAtEndRegex=new RegExp(`(?:${OSC_START}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${CSI_START})$`),MAX_PENDING_ANSI_LENGTH=256;function splitIncompleteAnsiSuffix(value){if(!value.includes("\x1B")&&!value.includes("\x9B"))return{complete:value,pending:""};let windowStart=Math.max(0,value.length-MAX_PENDING_ANSI_LENGTH),match=unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));if(!match)return{complete:value,pending:""};let splitAt=windowStart+match.index;return{complete:value.slice(0,splitAt),pending:value.slice(splitAt)}}function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(ansiRegex,"")}function shortenPath(path5){return typeof path5!="string"?"":shortenHomePath(path5)}function linkPath(styledText,rawPath,cwd){if(!getCapabilities().hyperlinks)return styledText;let absolutePath=resolvePath(rawPath,cwd);return hyperlink(styledText,pathToFileURL2(absolutePath).href)}function str(value){return typeof value=="string"?value:value==null?"":null}function parseLineNumber(value){return typeof value=="string"&&value.trim()!==""&&(value=Number(value)),typeof value=="number"&&Number.isFinite(value)?value:void 0}function formatReadLineRange(offset,limit){if(offset==null&&limit==null)return"";let start=offset==null?1:parseLineNumber(offset);if(start===void 0)return"";if(limit==null)return`:${start}`;let count=parseLineNumber(limit);if(count===void 0)return"";let end=start+count-1;return`:${start}${end?`-${end}`:""}`}function replaceTabs(text){return text.replace(/\t/g," ")}function normalizeDisplayText(text){return text.replace(/\r/g,"")}function getTextOutput(result,showImages){if(!result)return"";let textBlocks=result.content.filter(c2=>c2.type==="text"),imageBlocks=result.content.filter(c2=>c2.type==="image"),output=textBlocks.map(c2=>sanitizeBinaryOutput(stripAnsi(c2.text||"")).replace(/\r/g,"")).join(`
121
+ `).map(line=>theme.fg("mdCodeBlock",line))}}var CodeHighlighter=class{last;highlight(code,lang){let currentTheme=getGlobalTheme(),languageCount=getHighlightLanguageCount(),last=this.last;if(last?.code===code&&last.lang===lang&&last.theme===currentTheme&&last.languageCount===languageCount)return last.lines;let lines=highlightCode(code,lang);return this.last={code,lang,theme:currentTheme,languageCount,lines},lines}};function getLanguageFromPath(filePath){let ext=filePath.split(".").pop()?.toLowerCase();return ext?{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",dart:"dart",groovy:"groovy",gradle:"groovy",nix:"nix",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"dockerfile",makefile:"makefile",cmake:"cmake",lua:"lua",perl:"perl",r:"r",scala:"scala",clj:"clojure",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",ml:"ocaml",vim:"vim",graphql:"graphql",proto:"protobuf",tf:"hcl",hcl:"hcl"}[ext]:void 0}function getMarkdownTheme(){return{heading:text=>theme.fg("mdHeading",text),link:text=>theme.fg("mdLink",text),linkUrl:text=>theme.fg("mdLinkUrl",text),code:text=>theme.fg("mdCode",text),codeBlock:text=>theme.fg("mdCodeBlock",text),codeBlockBorder:text=>theme.fg("mdCodeBlockBorder",text),quote:text=>theme.fg("mdQuote",text),quoteBorder:text=>theme.fg("mdQuoteBorder",text),hr:text=>theme.fg("mdHr",text),listBullet:text=>theme.fg("mdListBullet",text),bold:text=>theme.bold(text),italic:text=>theme.italic(text),underline:text=>theme.underline(text),strikethrough:text=>theme.strikethrough(text),highlightCode}}function getSelectListTheme(){return{selectedPrefix:text=>theme.fg("accent",text),selectedText:text=>theme.fg("accent",text),description:text=>theme.fg("muted",text),scrollInfo:text=>theme.fg("muted",text),noMatch:text=>theme.fg("muted",text)}}function getEditorTheme(){return{borderColor:text=>theme.fg("borderMuted",text),selectList:getSelectListTheme()}}function getSettingsListTheme(){return{label:(text,selected)=>selected?theme.fg("accent",text):text,value:(text,selected)=>selected?theme.fg("accent",text):theme.fg("muted",text),description:text=>theme.fg("dim",text),cursor:theme.fg("accent","\u2192 "),hint:text=>theme.fg("dim",text)}}function formatKeyPart(part,options2){let displayPart=process.platform==="darwin"&&part.toLowerCase()==="alt"?"option":part;return options2.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options2={}){return key.split("/").map(k=>k.split("+").map(part=>formatKeyPart(part,options2)).join("+")).join("/")}function formatKeys(keys,options2={}){return keys.length===0?"":formatKeyText(keys.join("/"),options2)}function keyText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding))}var ARROW_GLYPHS={up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192"};function combinedKeyText(keybindings){let perBinding=keybindings.map(id=>getKeybindings().getKeys(id));return perBinding.every(keys=>keys.length===1&&keys[0]in ARROW_GLYPHS)?perBinding.map(keys=>ARROW_GLYPHS[keys[0]]).join(""):keybindings.map(id=>keyText(id)).join("/")}function combinedKeyHint(keybindings,description){return theme.fg("dim",combinedKeyText(keybindings))+theme.fg("muted",` ${description}`)}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}function isValidUsage(value){if(typeof value!="object"||value===null)return!1;let u=value;if(![u.input,u.output,u.cacheRead,u.cacheWrite,u.totalTokens].every(n=>typeof n=="number"&&Number.isFinite(n))||typeof u.cost!="object"||u.cost===null)return!1;let cost=u.cost;return[cost.input,cost.output,cost.cacheRead,cost.cacheWrite,cost.total].every(n=>typeof n=="number"&&Number.isFinite(n))}function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{input:first.input+second.input,output:first.output+second.output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total,totalFromProvider:first.cost.totalFromProvider===!0&&second.cost.totalFromProvider===!0}}}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let entry of entries){let key,usage;if(entry.type==="message"&&entry.message.role==="assistant"?(key=`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage=entry.message.usage):entry.type==="usage"?(key=`${entry.provider}/${entry.model}`,usage=entry.usage):entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage?(key="Tools/summaries",usage=entry.message.usage):(entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage&&(key="Tools/summaries",usage=entry.usage),!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).filter(entry=>entry.cost>0||entry.tokens>0).sort((a,b)=>b.cost-a.cost)}import{pathToFileURL as pathToFileURL2}from"node:url";var ST="(?:\\u0007|\\u001B\\u005C|\\u009C)",OSC_START="\\u001B\\]",CSI_START="(?:(?:\\u001B\\[|\\u009B)[<=>]|[\\u001B\\u009B][[\\]()#;?]*)(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",CSI_FINAL="[\\dA-PR-TZcf-nq-uy=><~]",ansiRegex=new RegExp(`(?:${OSC_START}[\\s\\S]*?${ST})|${CSI_START}${CSI_FINAL}`,"g"),unfinishedAnsiAtEndRegex=new RegExp(`(?:${OSC_START}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${CSI_START})$`),MAX_PENDING_ANSI_LENGTH=256;function splitIncompleteAnsiSuffix(value){if(!value.includes("\x1B")&&!value.includes("\x9B"))return{complete:value,pending:""};let windowStart=Math.max(0,value.length-MAX_PENDING_ANSI_LENGTH),match=unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));if(!match)return{complete:value,pending:""};let splitAt=windowStart+match.index;return{complete:value.slice(0,splitAt),pending:value.slice(splitAt)}}function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(ansiRegex,"")}function shortenPath(path5){return typeof path5!="string"?"":shortenHomePath(path5)}function linkPath(styledText,rawPath,cwd){if(!getCapabilities().hyperlinks)return styledText;let absolutePath=resolvePath(rawPath,cwd);return hyperlink(styledText,pathToFileURL2(absolutePath).href)}function str(value){return typeof value=="string"?value:value==null?"":null}function parseLineNumber(value){return typeof value=="string"&&value.trim()!==""&&(value=Number(value)),typeof value=="number"&&Number.isFinite(value)?value:void 0}function formatReadLineRange(offset,limit){if(offset==null&&limit==null)return"";let start=offset==null?1:parseLineNumber(offset);if(start===void 0)return"";if(limit==null)return`:${start}`;let count=parseLineNumber(limit);if(count===void 0)return"";let end=start+count-1;return`:${start}${end?`-${end}`:""}`}function replaceTabs(text){return text.replace(/\t/g," ")}function normalizeDisplayText(text){return text.replace(/\r/g,"")}function getTextOutput(result,showImages){if(!result)return"";let textBlocks=result.content.filter(c2=>c2.type==="text"),imageBlocks=result.content.filter(c2=>c2.type==="image"),output=textBlocks.map(c2=>sanitizeBinaryOutput(stripAnsi(c2.text||"")).replace(/\r/g,"")).join(`
125
122
  `),caps=getCapabilities();if(imageBlocks.length>0&&(!caps.images||!showImages)){let imageIndicators=imageBlocks.map(img=>{let mimeType=img.mimeType??"image/unknown",dims=img.data&&img.mimeType?getImageDimensions(img.data,img.mimeType)??void 0:void 0;return imageFallback(mimeType,dims)}).join(`
126
123
  `);output=output?`${output}
127
124
  ${imageIndicators}`:imageIndicators}return output}var COLLAPSED_ARGS_CHARS=100;function formatToolCallWithArgs(title,args,theme2,expanded){let header=theme2.fg("toolTitle",theme2.bold(title));if(args==null)return header;let entries=typeof args=="object"&&!Array.isArray(args)?Object.entries(args):[["args",args]];if(entries.length===0)return header;if(expanded){let lines=entries.map(([key,value])=>{let text=typeof value=="string"?value:JSON.stringify(value,null,2)??String(value);return` ${key}: ${replaceTabs(text).replace(/\r/g,"").split(`
128
125
  `).join(`
129
126
  `)}`});return`${header}
130
127
  ${theme2.fg("muted",lines.join(`
131
- `))}`}let pairs=entries.map(([key,value])=>`${key}=${JSON.stringify(value)??String(value)}`).join(" "),preview=pairs.length>COLLAPSED_ARGS_CHARS?`${pairs.slice(0,COLLAPSED_ARGS_CHARS-3)}...`:pairs;return`${header} ${theme2.fg("muted",preview)}`}function formatToolDuration(ms){let seconds=ms/1e3;if(seconds<60)return`${seconds.toFixed(1)}s`;let totalSeconds=Math.floor(seconds),minutes=Math.floor(totalSeconds/60),remainder=totalSeconds%60;return minutes<60?`${minutes}m ${remainder}s`:`${Math.floor(minutes/60)}h ${minutes%60}m ${remainder}s`}function startToolTimer(context){let state=context.state;context.executionStarted&&state.startedAt===void 0&&(state.startedAt=Date.now(),state.endedAt=void 0)}function toolTimerText(context,isPartial){let state=context.state;if(state.startedAt!==void 0&&isPartial&&!state.interval&&(state.interval=setInterval(()=>context.invalidate(),1e3)),(!isPartial||context.isError)&&(state.endedAt??=Date.now(),state.interval&&(clearInterval(state.interval),state.interval=void 0)),!isPartial&&context.durationMs!==void 0)return`Took ${formatToolDuration(context.durationMs)}`;if(state.startedAt===void 0)return;let endTime=state.endedAt??Date.now();return`${isPartial?"Elapsed":"Took"} ${formatToolDuration(endTime-state.startedAt)}`}function invalidArgText(theme2){return theme2.fg("error","[invalid arg]")}function renderToolPath(rawPath,theme2,cwd,options2){if(rawPath===null)return invalidArgText(theme2);let value=rawPath||options2?.emptyFallback;return value?linkPath(theme2.fg("accent",shortenPath(value)),value,cwd):theme2.fg("toolOutput","...")}import{randomBytes}from"node:crypto";import{createWriteStream}from"node:fs";import{writeFile}from"node:fs/promises";import{tmpdir as tmpdir2}from"node:os";import{join as join7}from"node:path";var OUTPUT_FILE_MODE=384;function createOutputFilePath(prefix,extension){return join7(tmpdir2(),`${prefix}-${randomBytes(8).toString("hex")}${extension}`)}async function writeOutputFile(prefix,extension,data){let path5=createOutputFilePath(prefix,extension);return await writeFile(path5,data,{mode:OUTPUT_FILE_MODE,flag:"wx"}),path5}function createOutputFileStream(prefix,extension){let path5=createOutputFilePath(prefix,extension);return{path:path5,stream:createWriteStream(path5,{mode:OUTPUT_FILE_MODE,flags:"wx"})}}function truncateToVisualLines(text,maxVisualLines,width,paddingX=0,keep="end"){if(!text)return{visualLines:[],skippedCount:0};let allVisualLines=new Text(text,paddingX,0).render(width);if(allVisualLines.length<=maxVisualLines)return{visualLines:allVisualLines,skippedCount:0};let truncatedLines=keep==="start"?allVisualLines.slice(0,maxVisualLines):allVisualLines.slice(-maxVisualLines),skippedCount=allVisualLines.length-maxVisualLines;return{visualLines:truncatedLines,skippedCount}}var VisualLinePreview=class{options;cachedWidth;cachedLines;constructor(options2){this.options=options2}render(width){if(this.cachedLines===void 0||this.cachedWidth!==width){let{text,maxVisualLines,keep,formatHint}=this.options,preview=truncateToVisualLines(text,maxVisualLines,width,0,keep),lines=preview.visualLines;if(preview.skippedCount>0){let hint=truncateToWidth(formatHint(preview.skippedCount),width,"...");this.cachedLines=keep==="start"?[...lines,hint]:[hint,...lines]}else this.cachedLines=lines;this.cachedWidth=width}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}};var TOOL_SEARCH_TOOL_NAME="tool_search",DEFAULT_TOOL_SEARCH_LIMIT=8,wordSegmenter5=new Intl.Segmenter(void 0,{granularity:"word"}),STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","this","to","with"]);function stem(term){return term.length>4&&term.endsWith("ies")?`${term.slice(0,-3)}y`:term.length>4&&/(ches|shes|sses|xes|zes)$/.test(term)?term.slice(0,-2):term.length>3&&term.endsWith("s")&&!term.endsWith("ss")?term.slice(0,-1):term}function tokenize(text){let normalized=text.normalize("NFC").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu," ");return(/^[a-z0-9 ]*$/.test(normalized)?normalized.split(" "):Array.from(wordSegmenter5.segment(normalized),segment=>segment.isWordLike?segment.segment:"")).filter(word=>word.length>0&&!STOP_WORDS.has(word)).map(word=>/^[a-z0-9]+$/.test(word)?stem(word):word)}function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function schemaText(schema,parts){if(isObject(schema)){if(typeof schema.description=="string"&&parts.push(schema.description),isObject(schema.properties))for(let[name,property]of Object.entries(schema.properties))parts.push(name),schemaText(property,parts);schemaText(schema.items,parts);for(let key of["anyOf","oneOf","allOf"]){let variants=schema[key];if(Array.isArray(variants))for(let variant of variants)schemaText(variant,parts)}}}function createToolSearchDocument(tool,namespace){let parts=[tool.description];schemaText(tool.parameters,parts);let namespaceText=namespace?[namespace.name,namespace.description??"",namespace.instructions??""].join(" "):"";return{name:tool.name,text:parts.filter(part=>part.trim()).join(" "),namespaceText}}function normalizeName(name){return name.trim().toLowerCase().replace(/[^a-z0-9_$]/g,"_")}function isExactNameQuery(query,name){let normalized=normalizeName(name);return normalized===query||normalized.endsWith(`__${query}`)}function indexDocument(document){let textCounts=new Map;for(let term of tokenize(document.text))textCounts.set(term,(textCounts.get(term)??0)+1);let segments=document.name.split("__");return{name:document.name,nameTerms:new Set(tokenize(document.name)),localNameTerms:[...new Set(tokenize(segments[segments.length-1]))],textCounts,textLength:[...textCounts.values()].reduce((sum,count)=>sum+count,0),namespaceTerms:new Set(tokenize(document.namespaceText??""))}}var NAME_WEIGHT=3,NAMESPACE_WEIGHT=.5,Bm25Ranker=class{k1;b;constructor(options2={}){this.k1=options2.k1??1.2,this.b=options2.b??.75}rank(query,documents,limit){let queryTerms=new Set(tokenize(query));if(queryTerms.size===0||documents.length===0||limit<=0)return[];let indexed=documents.map(indexDocument),averageLength=indexed.reduce((sum,document)=>sum+document.textLength,0)/indexed.length||1,idf=new Map([...queryTerms].map(term=>{let frequency=indexed.filter(document=>document.nameTerms.has(term)||document.textCounts.has(term)||document.namespaceTerms.has(term)).length;return[term,Math.log(1+(indexed.length-frequency+.5)/(frequency+.5))]})),fullNameBonus=[...idf.values()].reduce((sum,value)=>sum+value,0),exactQuery=normalizeName(query),matches=[];for(let document of indexed){let norm=this.k1*(1-this.b+this.b*document.textLength/averageLength),score=0,covered=0;for(let term of queryTerms){let count=document.textCounts.get(term)??0,weight=(document.nameTerms.has(term)?NAME_WEIGHT:0)+(document.namespaceTerms.has(term)?NAMESPACE_WEIGHT:0)+count*(this.k1+1)/(count+norm);weight>0&&covered++,score+=(idf.get(term)??0)*weight}if(score===0)continue;let local=document.localNameTerms;local.length>0&&local.every(term=>queryTerms.has(term))&&(score+=fullNameBonus),matches.push({name:document.name,score,covered,exact:isExactNameQuery(exactQuery,document.name)})}return matches.sort((a,b)=>Number(b.exact)-Number(a.exact)||b.covered-a.covered||b.score-a.score).slice(0,limit).map(({name,score})=>({name,score}))}},toolSearchSchema=typebox_exports.Object({query:typebox_exports.String({description:"Search query for deferred tools."}),limit:typebox_exports.Optional(typebox_exports.Number({description:`Maximum number of tools to return. Defaults to ${DEFAULT_TOOL_SEARCH_LIMIT}.`}))});function isSearchable(exposure){return exposure==="codemode"||exposure==="deferred"}function searchAndLoad(tools,query,limit){let active=tools.getActiveTools(),candidates=tools.getAllTools().filter(tool=>isSearchable(tool.exposure)&&!active.includes(tool.name)),documents=candidates.map(tool=>createToolSearchDocument(tool,tool.namespace)),matches=new Bm25Ranker().rank(query,documents,limit);return matches.length>0&&tools.setActiveTools([...active,...matches.map(match=>match.name)]),matches.map(match=>({name:match.name,description:candidates.find(tool=>tool.name===match.name)?.description??""}))}var TOOL_SEARCH_DESCRIPTION=`# Tool discovery
128
+ `))}`}let pairs=entries.map(([key,value])=>`${key}=${JSON.stringify(value)??String(value)}`).join(" "),preview=pairs.length>COLLAPSED_ARGS_CHARS?`${pairs.slice(0,COLLAPSED_ARGS_CHARS-3)}...`:pairs;return`${header} ${theme2.fg("muted",preview)}`}function formatToolDuration(ms){let seconds=ms/1e3;if(seconds<60)return`${seconds.toFixed(1)}s`;let totalSeconds=Math.floor(seconds),minutes=Math.floor(totalSeconds/60),remainder=totalSeconds%60;return minutes<60?`${minutes}m ${remainder}s`:`${Math.floor(minutes/60)}h ${minutes%60}m ${remainder}s`}function startToolTimer(context){let state=context.state;context.executionStarted&&state.startedAt===void 0&&(state.startedAt=Date.now(),state.endedAt=void 0)}function toolTimerText(context,isPartial){let state=context.state;if(state.startedAt!==void 0&&isPartial&&!state.interval&&(state.interval=setInterval(()=>context.invalidate(),1e3)),(!isPartial||context.isError)&&(state.endedAt??=Date.now(),state.interval&&(clearInterval(state.interval),state.interval=void 0)),!isPartial&&context.durationMs!==void 0)return`Took ${formatToolDuration(context.durationMs)}`;if(state.startedAt===void 0)return;let endTime=state.endedAt??Date.now();return`${isPartial?"Elapsed":"Took"} ${formatToolDuration(endTime-state.startedAt)}`}function invalidArgText(theme2){return theme2.fg("error","[invalid arg]")}function renderToolPath(rawPath,theme2,cwd,options2){if(rawPath===null)return invalidArgText(theme2);let value=rawPath||options2?.emptyFallback;return value?linkPath(theme2.fg("accent",shortenPath(value)),value,cwd):theme2.fg("toolOutput","...")}import{randomBytes}from"node:crypto";import{createWriteStream}from"node:fs";import{writeFile}from"node:fs/promises";import{tmpdir as tmpdir2}from"node:os";import{join as join7}from"node:path";var OUTPUT_FILE_MODE=384;function createOutputFilePath(prefix,extension){return join7(tmpdir2(),`${prefix}-${randomBytes(8).toString("hex")}${extension}`)}async function writeOutputFile(prefix,extension,data){let path5=createOutputFilePath(prefix,extension);return await writeFile(path5,data,{mode:OUTPUT_FILE_MODE,flag:"wx"}),path5}function createOutputFileStream(prefix,extension){let path5=createOutputFilePath(prefix,extension);return{path:path5,stream:createWriteStream(path5,{mode:OUTPUT_FILE_MODE,flags:"wx"})}}function truncateToVisualLines(text,maxVisualLines,width,paddingX=0,keep="end"){if(!text)return{visualLines:[],skippedCount:0};let allVisualLines=new Text(text,paddingX,0).render(width);if(allVisualLines.length<=maxVisualLines)return{visualLines:allVisualLines,skippedCount:0};let truncatedLines=keep==="start"?allVisualLines.slice(0,maxVisualLines):allVisualLines.slice(-maxVisualLines),skippedCount=allVisualLines.length-maxVisualLines;return{visualLines:truncatedLines,skippedCount}}var VisualLinePreview=class{options;cachedWidth;cachedLines;constructor(options2){this.options=options2}render(width){if(this.cachedLines===void 0||this.cachedWidth!==width){let{text,maxVisualLines,keep,formatHint}=this.options,preview=truncateToVisualLines(text,maxVisualLines,width,0,keep),lines=preview.visualLines;if(preview.skippedCount>0){let hint=truncateToWidth(formatHint(preview.skippedCount),width,"...");this.cachedLines=keep==="start"?[...lines,hint]:[hint,...lines]}else this.cachedLines=lines;this.cachedWidth=width}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}};var TOOL_SEARCH_TOOL_NAME="tool_search",DEFAULT_TOOL_SEARCH_LIMIT=8,wordSegmenter5=new Intl.Segmenter(void 0,{granularity:"word"}),STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","this","to","with"]);function stem(term){return term.length>4&&term.endsWith("ies")?`${term.slice(0,-3)}y`:term.length>4&&/(ches|shes|sses|xes|zes)$/.test(term)?term.slice(0,-2):term.length>3&&term.endsWith("s")&&!term.endsWith("ss")?term.slice(0,-1):term}function tokenize(text){let normalized=text.normalize("NFC").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu," ");return(/^[a-z0-9 ]*$/.test(normalized)?normalized.split(" "):Array.from(wordSegmenter5.segment(normalized),segment=>segment.isWordLike?segment.segment:"")).filter(word=>word.length>0&&!STOP_WORDS.has(word)).map(word=>/^[a-z0-9]+$/.test(word)?stem(word):word)}function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function schemaText(schema,root,parts,seen){if(isObject(schema)){if(typeof schema.$ref=="string"){let target=resolveSchemaRef(schema.$ref,root);isObject(target)&&!seen.has(target)&&(seen.add(target),schemaText(target,root,parts,seen))}if(typeof schema.description=="string"&&parts.push(schema.description),isObject(schema.properties))for(let[name,property]of Object.entries(schema.properties))parts.push(name),schemaText(property,root,parts,seen);schemaText(schema.items,root,parts,seen);for(let key of["anyOf","oneOf","allOf"]){let variants=schema[key];if(Array.isArray(variants))for(let variant of variants)schemaText(variant,root,parts,seen)}}}function createToolSearchDocument(tool,namespace){let parts=[tool.description];schemaText(tool.parameters,tool.parameters,parts,new Set([tool.parameters]));let namespaceText=namespace?[namespace.name,namespace.description??"",namespace.instructions??""].join(" "):"";return{name:tool.name,text:parts.filter(part=>part.trim()).join(" "),namespaceText}}function normalizeName(name){return name.trim().toLowerCase().replace(/[^a-z0-9_$]/g,"_")}function isExactNameQuery(query,name){let normalized=normalizeName(name);return normalized===query||normalized.endsWith(`__${query}`)}function indexDocument(document){let textCounts=new Map;for(let term of tokenize(document.text))textCounts.set(term,(textCounts.get(term)??0)+1);let segments=document.name.split("__");return{name:document.name,nameTerms:new Set(tokenize(document.name)),localNameTerms:[...new Set(tokenize(segments[segments.length-1]))],textCounts,textLength:[...textCounts.values()].reduce((sum,count)=>sum+count,0),namespaceTerms:new Set(tokenize(document.namespaceText??""))}}var NAME_WEIGHT=3,NAMESPACE_WEIGHT=.5,Bm25Ranker=class{k1;b;constructor(options2={}){this.k1=options2.k1??1.2,this.b=options2.b??.75}rank(query,documents,limit){let queryTerms=new Set(tokenize(query));if(queryTerms.size===0||documents.length===0||limit<=0)return[];let indexed=documents.map(indexDocument),averageLength=indexed.reduce((sum,document)=>sum+document.textLength,0)/indexed.length||1,idf=new Map([...queryTerms].map(term=>{let frequency=indexed.filter(document=>document.nameTerms.has(term)||document.textCounts.has(term)||document.namespaceTerms.has(term)).length;return[term,Math.log(1+(indexed.length-frequency+.5)/(frequency+.5))]})),fullNameBonus=[...idf.values()].reduce((sum,value)=>sum+value,0),exactQuery=normalizeName(query),matches=[];for(let document of indexed){let norm=this.k1*(1-this.b+this.b*document.textLength/averageLength),score=0,covered=0;for(let term of queryTerms){let count=document.textCounts.get(term)??0,weight=(document.nameTerms.has(term)?NAME_WEIGHT:0)+(document.namespaceTerms.has(term)?NAMESPACE_WEIGHT:0)+count*(this.k1+1)/(count+norm);weight>0&&covered++,score+=(idf.get(term)??0)*weight}if(score===0)continue;let local=document.localNameTerms;local.length>0&&local.every(term=>queryTerms.has(term))&&(score+=fullNameBonus),matches.push({name:document.name,score,covered,exact:isExactNameQuery(exactQuery,document.name)})}return matches.sort((a,b)=>Number(b.exact)-Number(a.exact)||b.covered-a.covered||b.score-a.score).slice(0,limit).map(({name,score})=>({name,score}))}},toolSearchSchema=typebox_exports.Object({query:typebox_exports.String({description:"Search query for deferred tools."}),limit:typebox_exports.Optional(typebox_exports.Number({description:`Maximum number of tools to return. Defaults to ${DEFAULT_TOOL_SEARCH_LIMIT}.`}))});function isSearchable(exposure){return exposure==="codemode"||exposure==="deferred"}function searchAndLoad(tools,query,limit){let active=tools.getActiveTools(),candidates=tools.getAllTools().filter(tool=>isSearchable(tool.exposure)&&!active.includes(tool.name)),documents=candidates.map(tool=>createToolSearchDocument(tool,tool.namespace)),matches=new Bm25Ranker().rank(query,documents,limit);return matches.length>0&&tools.setActiveTools([...active,...matches.map(match=>match.name)]),matches.map(match=>({name:match.name,description:candidates.find(tool=>tool.name===match.name)?.description??""}))}var TOOL_SEARCH_DESCRIPTION=`# Tool discovery
132
129
 
133
130
  Searches over deferred tool metadata with BM25 and exposes matching tools for the next model call.
134
131
 
135
132
  Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;function createToolSearchToolDefinition(options2={}){return{name:TOOL_SEARCH_TOOL_NAME,label:TOOL_SEARCH_TOOL_NAME,description:TOOL_SEARCH_DESCRIPTION,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:toolSearchSchema,exposure:"model-only",reachesTools:()=>"all",async execute(_toolCallId,{query,limit}){if(query.trim()==="")throw new Error("query must not be empty");let max=limit??DEFAULT_TOOL_SEARCH_LIMIT;if(!Number.isInteger(max)||max<=0)throw new Error("limit must be a positive integer");let tools=options2.tools?searchAndLoad(options2.tools,query,max):[];return{content:[{type:"text",text:tools.length===0?"No matching tools found.":`Loaded ${tools.length} tool${tools.length===1?"":"s"}. They are available from your next call:
136
133
  ${tools.map(tool=>`- ${tool.name}: ${tool.description.trim().split(/\r?\n/)[0]}`).join(`
137
- `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join8}from"node:path";function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-ZI7T2SUH.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme2,hidden,noun){return`${theme2.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme2.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(2):cost.toPrecision(2)}`}function statusIcon(call,theme2){switch(call.status){case"running":return theme2.fg("warning","\u2026");case"ok":return theme2.fg("success","\u2713");case"error":return theme2.fg("error","\u2717");case"cancelled":return theme2.fg("muted","\u2298")}}function formatCall(call,theme2,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme2)} ${theme2.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme2.fg("muted",args)}`),duration&&(line+=` ${theme2.fg("dim",duration)}`),call.cost&&(line+=` ${theme2.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
134
+ `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join8}from"node:path";function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-KGJOWTPG.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme2,hidden,noun){return`${theme2.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme2.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(2):cost.toPrecision(2)}`}function statusIcon(call,theme2){switch(call.status){case"running":return theme2.fg("warning","\u2026");case"ok":return theme2.fg("success","\u2713");case"error":return theme2.fg("error","\u2717");case"cancelled":return theme2.fg("muted","\u2298")}}function formatCall(call,theme2,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme2)} ${theme2.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme2.fg("muted",args)}`),duration&&(line+=` ${theme2.fg("dim",duration)}`),call.cost&&(line+=` ${theme2.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
138
135
  ${theme2.fg("error",call.error.split(`
139
136
  `).join(`
140
137
  `))}`),line}var codemodeRenderers={renderCall(args,theme2,context){startToolTimer(context);let code=str(args?.code),title=theme2.fg("toolTitle",theme2.bold("codemode")),component=context.lastComponent??new Container;if(component.clear(),code===null)return component.addChild(new Text(`${title} ${theme2.fg("error","[invalid arg]")}`,0,0)),component;if(component.addChild(new Text(title,0,0)),code){let state=context.state;state.scriptHighlighter??=new CodeHighlighter;let highlighted=state.scriptHighlighter.highlight(replaceTabs(code.replace(/\r/g,"").trimEnd()),"javascript").join(`
@@ -153,7 +150,7 @@ ${description}`:""}`)}for(let entry of visible)toolSections.push(entry.section)}
153
150
 
154
151
  `)),sections.join(`
155
152
 
156
- `)}function describeFields(schema,depth){if(typeof schema!="object"||schema===null)return;let{type,properties,required}=schema;if(type!=="object"||typeof properties!="object"||properties===null)return;let requiredNames=new Set(Array.isArray(required)?required:[]);return`{ ${Object.entries(properties).map(([name,field])=>{let constValue=field?.const,nested=constValue!==void 0?JSON.stringify(constValue):depth>0?describeFields(field,depth-1):void 0;return`${name}${requiredNames.has(name)?"":"?"}${nested?`: ${nested}`:""}`}).join(", ")} }`}function describeOutput(name,schema){let type=renderToolOutputType(schema);if(type==="string")return"a string";let fields=describeFields(schema,1)??describeUnionFields(schema);return fields?`\`${fields}\``:type.includes(`
157
- `)?`a value; \`await describeTool(${JSON.stringify(name)})\` shows its type`:`\`${type}\``}function describeUnionFields(schema){if(typeof schema!="object"||schema===null)return;let{anyOf,oneOf}=schema,variants=anyOf??oneOf;if(!Array.isArray(variants)||variants.length===0)return;let described=variants.map(variant=>describeFields(variant,0));return described.every(fields=>fields!==void 0)?described.join(" | "):void 0}function describeScriptCall(tool){return`${tool.description.trim()}
153
+ `)}function describeFields(schema,root,depth){let resolved=followRef(schema,root);if(typeof resolved!="object"||resolved===null)return;let{type,properties,required}=resolved;if(type!=="object"||typeof properties!="object"||properties===null)return;let requiredNames=new Set(Array.isArray(required)?required:[]);return`{ ${Object.entries(properties).map(([name,field])=>{let constValue=followRef(field,root)?.const,nested=constValue!==void 0?JSON.stringify(constValue):depth>0?describeFields(field,root,depth-1):void 0;return`${name}${requiredNames.has(name)?"":"?"}${nested?`: ${nested}`:""}`}).join(", ")} }`}function describeOutput(name,schema){let type=renderToolOutputType(schema);if(type==="string")return"a string";let fields=schema===void 0?void 0:describeFields(schema,schema,1)??describeUnionFields(schema,schema);return fields?`\`${fields}\``:type.includes(`
154
+ `)?`a value; \`await describeTool(${JSON.stringify(name)})\` shows its type`:`\`${type}\``}function describeUnionFields(schema,root){let resolved=followRef(schema,root);if(typeof resolved!="object"||resolved===null)return;let{anyOf,oneOf}=resolved,variants=anyOf??oneOf;if(!Array.isArray(variants)||variants.length===0)return;let described=variants.map(variant=>describeFields(variant,root,0));return described.every(fields=>fields!==void 0)?described.join(" | "):void 0}function followRef(schema,root){let seen=new Set,current=schema;for(;typeof current=="object"&&current!==null&&!seen.has(current);){let ref=current.$ref;if(typeof ref!="string")break;let target=resolveSchemaRef(ref,root);if(target===void 0)break;seen.add(current),current=target}return current}function describeScriptCall(tool){return`${tool.description.trim()}
158
155
 
159
- Codemode: \`tools.${toCodemodeIdentifier(tool.name)}(args)\` resolves to ${describeOutput(tool.name,toCodemodeDeclaration(tool).outputSchema)}.`}function prepareCodemodeLoadout(loadout,options2){let mode=options2.getMode?.()??SETTINGS_DEFAULTS.codemode.mode,isDirect=tool=>loadout.getExposure(tool.name)==="direct",callable=getCodemodeCallableTools(loadout.callable),callableNames=new Set(callable.map(tool=>tool.name)),descriptions={};if(mode==="on")for(let tool of loadout.declared)callableNames.has(tool.name)&&(descriptions[tool.name]=describeScriptCall(tool));let listed=mode==="only"?callable:callable.filter(tool=>!isDirect(tool)),namespaces=new Map(listed.flatMap(tool=>{let namespace=loadout.getNamespace(tool.name);return namespace?[[tool.name,namespace]]:[]})),guidelines=new Map(listed.map(tool=>[tool.name,loadout.getPromptGuidelines(tool.name)]));descriptions[CODEMODE_TOOL_NAME]=createCodemodeDescription(listed,{models:options2.models===!0,namespaces,guidelines,deferred:new Set(listed.filter(tool=>loadout.getExposure(tool.name)==="deferred").map(tool=>tool.name)),inlineBudget:options2.getInlineBudget?.()??DEFAULT_CODEMODE_INLINE_BUDGET});let declaredNames=new Set(loadout.declared.map(tool=>tool.name));return{descriptions,hiddenDeclarations:mode==="only"?callable.filter(tool=>isDirect(tool)&&declaredNames.has(tool.name)).map(tool=>tool.name):[]}}var DISCOVERY_GLOBALS=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function getScriptReach(code){return typeof code!="string"?[]:DISCOVERY_GLOBALS.test(code)?"all":code.match(/\w+/g)??[]}function createCodemodeToolDefinition(options2={}){return{name:CODEMODE_TOOL_NAME,label:CODEMODE_TOOL_NAME,description:createCodemodeDescription([],{models:options2.models===!0}),promptSnippet:codemodeToolSystemPromptContribution.snippet,promptGuidelines:[...codemodeToolSystemPromptContribution.guidelines],parameters:codemodeSchema,exposure:"model-only",prepareLoadout:loadout=>prepareCodemodeLoadout(loadout,options2),reachesTools:input=>getScriptReach(input.code),constrainedSampling:{type:"grammar",variants:{openai_lark:CODEMODE_SOURCE_GRAMMAR}},execute:async(toolCallId,params,signal,onUpdate,ctx)=>(await loadCodemodeExecutor()).executeCodemode(toolCallId,params,signal,onUpdate,ctx,options2),...codemodeRenderers}}export{Marked,fuzzyMatch,fuzzyFilter,visibleWidth,replaceControlCharacters,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,parseColor,mixColors,foregroundAnsi,Key,isKeyRelease,isKeyRepeat,matchesKey,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,hyperlink,CURSOR_MARKER,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,getSelectPageIndex,Text,Loader,CancellableLoader,SelectList,Editor,setImageTranscoder,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguages,SYSTEM_THEME_NAME,THEME_TOKENS,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,CodeHighlighter,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,combinedKeyHint,keyDisplayText,keyHint,rawKeyHint,isValidUsage,createUsageTotals,addUsageToTotals,combineUsage,getUsageCostBreakdown,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,splitIncompleteAnsiSuffix,stripAnsi,shortenPath,str,formatReadLineRange,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,startToolTimer,toolTimerText,invalidArgText,renderToolPath,writeOutputFile,createOutputFileStream,wrapToolDefinition,createToolDefinitionFromAgentTool,truncateToVisualLines,VisualLinePreview,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};
156
+ Codemode: \`tools.${toCodemodeIdentifier(tool.name)}(args)\` resolves to ${describeOutput(tool.name,toCodemodeDeclaration(tool).outputSchema)}.`}function prepareCodemodeLoadout(loadout,options2){let mode=options2.getMode?.()??SETTINGS_DEFAULTS.codemode.mode,isDirect=tool=>loadout.getExposure(tool.name)==="direct",callable=getCodemodeCallableTools(loadout.callable),callableNames=new Set(callable.map(tool=>tool.name)),descriptions={};if(mode==="on")for(let tool of loadout.declared)callableNames.has(tool.name)&&(descriptions[tool.name]=describeScriptCall(tool));let listed=mode==="only"?callable:callable.filter(tool=>!isDirect(tool)),namespaces=new Map(listed.flatMap(tool=>{let namespace=loadout.getNamespace(tool.name);return namespace?[[tool.name,namespace]]:[]})),guidelines=new Map(listed.map(tool=>[tool.name,loadout.getPromptGuidelines(tool.name)]));descriptions[CODEMODE_TOOL_NAME]=createCodemodeDescription(listed,{models:options2.models===!0,namespaces,guidelines,deferred:new Set(listed.filter(tool=>loadout.getExposure(tool.name)==="deferred").map(tool=>tool.name)),inlineBudget:options2.getInlineBudget?.()??DEFAULT_CODEMODE_INLINE_BUDGET});let declaredNames=new Set(loadout.declared.map(tool=>tool.name));return{descriptions,hiddenDeclarations:mode==="only"?callable.filter(tool=>isDirect(tool)&&declaredNames.has(tool.name)).map(tool=>tool.name):[]}}var DISCOVERY_GLOBALS=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function getScriptReach(code){return typeof code!="string"?[]:DISCOVERY_GLOBALS.test(code)?"all":code.match(/\w+/g)??[]}function createCodemodeToolDefinition(options2={}){return{name:CODEMODE_TOOL_NAME,label:CODEMODE_TOOL_NAME,description:createCodemodeDescription([],{models:options2.models===!0}),promptSnippet:codemodeToolSystemPromptContribution.snippet,promptGuidelines:[...codemodeToolSystemPromptContribution.guidelines],parameters:codemodeSchema,exposure:"model-only",prepareLoadout:loadout=>prepareCodemodeLoadout(loadout,options2),reachesTools:input=>getScriptReach(input.code),constrainedSampling:{type:"grammar",variants:{openai_lark:CODEMODE_SOURCE_GRAMMAR}},execute:async(toolCallId,params,signal,onUpdate,ctx)=>(await loadCodemodeExecutor()).executeCodemode(toolCallId,params,signal,onUpdate,ctx,options2),...codemodeRenderers}}export{Marked,fuzzyMatch,fuzzyFilter,visibleWidth,replaceControlCharacters,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,parseColor,mixColors,foregroundAnsi,Key,isKeyRelease,isKeyRepeat,matchesKey,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,hyperlink,CURSOR_MARKER,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,getSelectPageIndex,Text,Loader,CancellableLoader,SelectList,Editor,setImageTranscoder,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguages,SYSTEM_THEME_NAME,THEME_TOKENS,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,CodeHighlighter,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,combinedKeyHint,keyDisplayText,keyHint,rawKeyHint,isValidUsage,createUsageTotals,addUsageToTotals,combineUsage,getUsageCostBreakdown,splitIncompleteAnsiSuffix,stripAnsi,shortenPath,str,formatReadLineRange,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,startToolTimer,toolTimerText,invalidArgText,renderToolPath,writeOutputFile,createOutputFileStream,wrapToolDefinition,createToolDefinitionFromAgentTool,truncateToVisualLines,VisualLinePreview,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};