@draht/coding-agent 2026.10.16 → 2026.10.19-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 (173) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -0
  3. package/dist/bundle/chunks/{anthropic-messages-GAKYXF65.js → anthropic-messages-E2P6C3P7.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-ZIXMK6JO.js → azure-openai-responses-JZMSTDIM.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +20 -20
  6. package/dist/bundle/chunks/chunk-2JZLKNZ4.js +3 -0
  7. package/dist/bundle/chunks/{chunk-OWGSPJPZ.js → chunk-3DQNSI5W.js} +5 -5
  8. package/dist/bundle/chunks/{chunk-JFDPOIUH.js → chunk-4COXSQRQ.js} +1 -1
  9. package/dist/bundle/chunks/chunk-5QJFWTKA.js +4 -0
  10. package/dist/bundle/chunks/{chunk-TJ3AW62W.js → chunk-CQF6U56X.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-RZKPFWMH.js → chunk-D3HO453P.js} +2 -2
  12. package/dist/bundle/chunks/{chunk-KVH4HR57.js → chunk-FHX2S5IG.js} +1 -1
  13. package/dist/bundle/chunks/chunk-GBFVS2SF.js +12 -0
  14. package/dist/bundle/chunks/{chunk-6APPDDHH.js → chunk-I2SOJ4JN.js} +3 -3
  15. package/dist/bundle/chunks/{chunk-BXSHCX3G.js → chunk-KY2BG6BC.js} +1 -1
  16. package/dist/bundle/chunks/chunk-LO6CVU2L.js +6 -0
  17. package/dist/bundle/chunks/{chunk-MIUVNYYW.js → chunk-QPCP4VHF.js} +123 -111
  18. package/dist/bundle/chunks/{chunk-KU5HAKZL.js → chunk-QVTLBSTH.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-2VAF4XJI.js → chunk-U6LDZZGM.js} +10 -10
  20. package/dist/bundle/chunks/{chunk-D6TMD5Q2.js → chunk-UTRX2VHB.js} +8 -8
  21. package/dist/bundle/chunks/chunk-VXUJMEMO.js +2 -0
  22. package/dist/bundle/chunks/{chunk-NHTOADU6.js → chunk-X3YFUSCK.js} +1 -1
  23. package/dist/bundle/chunks/{cli-U7Y4VNNI.js → cli-VCHSHNKT.js} +1 -1
  24. package/dist/bundle/chunks/{execute-ZWB4PIQQ.js → execute-AGEWJLIO.js} +1 -1
  25. package/dist/bundle/chunks/{google-generative-ai-RPUPQ6PM.js → google-generative-ai-HPNDIAZD.js} +1 -1
  26. package/dist/bundle/chunks/{google-vertex-EZES5QVQ.js → google-vertex-KPAWJ4SP.js} +1 -1
  27. package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +13 -0
  28. package/dist/bundle/chunks/lib-ULKZYRGD.js +9 -0
  29. package/dist/bundle/chunks/{mistral-conversations-AOYGU43Y.js → mistral-conversations-FMSPWQ7A.js} +1 -1
  30. package/dist/bundle/chunks/{multipart-parser-AZP5BX2W.js → multipart-parser-HMCXZ4BD.js} +1 -1
  31. package/dist/bundle/chunks/{node-LQ52KV6B.js → node-4JNG6XQO.js} +1 -1
  32. package/dist/bundle/chunks/{node-C2JGH2OB.js → node-6IIDYB3K.js} +1 -1
  33. package/dist/bundle/chunks/{openai-codex-responses-M2Y77JEQ.js → openai-codex-responses-TU7NGPXE.js} +1 -1
  34. package/dist/bundle/chunks/{openai-completions-A4OKYOYV.js → openai-completions-GANCQQO5.js} +1 -1
  35. package/dist/bundle/chunks/{openai-responses-6IXV53T3.js → openai-responses-ASDPAX3E.js} +1 -1
  36. package/dist/bundle/chunks/{openrouter-images-LYV4NKFM.js → openrouter-images-NROSQXMZ.js} +1 -1
  37. package/dist/bundle/chunks/{pi-messages-KKMEUT3Z.js → pi-messages-2QEJYOAO.js} +1 -1
  38. package/dist/bundle/chunks/{runtime-PXJK4L7Y.js → runtime-2B56SZM6.js} +1 -1
  39. package/dist/bundle/chunks/{runtime-363BOYEO.js → runtime-TJ3EAMJK.js} +1 -1
  40. package/dist/bundle/chunks/{settings-manager-GEOZJXFQ.js → settings-manager-HC5RR36T.js} +1 -1
  41. package/dist/bundle/chunks/src-KDGO7EGF.js +4 -0
  42. package/dist/bundle/chunks/{virtual-modules-BEJ4ZJ3D.js → virtual-modules-XT4MP2GI.js} +1 -1
  43. package/dist/bundle/cli-runtime.js +1 -1
  44. package/dist/bundle/index.js +1 -1
  45. package/dist/bundle/rpc-entry.js +1 -1
  46. package/dist/core/agent-session.d.ts.map +1 -1
  47. package/dist/core/agent-session.js +4 -0
  48. package/dist/core/agent-session.js.map +1 -1
  49. package/dist/core/builtins/duet.d.ts +7 -1
  50. package/dist/core/builtins/duet.d.ts.map +1 -1
  51. package/dist/core/builtins/duet.js +83 -14
  52. package/dist/core/builtins/duet.js.map +1 -1
  53. package/dist/core/builtins/polyphase.d.ts.map +1 -1
  54. package/dist/core/builtins/polyphase.js +21 -2
  55. package/dist/core/builtins/polyphase.js.map +1 -1
  56. package/dist/core/builtins/subagent.d.ts +59 -2
  57. package/dist/core/builtins/subagent.d.ts.map +1 -1
  58. package/dist/core/builtins/subagent.js +258 -62
  59. package/dist/core/builtins/subagent.js.map +1 -1
  60. package/dist/core/extensions/loader.d.ts.map +1 -1
  61. package/dist/core/extensions/loader.js +23 -0
  62. package/dist/core/extensions/loader.js.map +1 -1
  63. package/dist/core/extensions/runner.d.ts.map +1 -1
  64. package/dist/core/extensions/runner.js +2 -0
  65. package/dist/core/extensions/runner.js.map +1 -1
  66. package/dist/core/extensions/types.d.ts +12 -0
  67. package/dist/core/extensions/types.d.ts.map +1 -1
  68. package/dist/core/extensions/types.js.map +1 -1
  69. package/dist/core/keybindings.d.ts +5 -0
  70. package/dist/core/keybindings.d.ts.map +1 -1
  71. package/dist/core/keybindings.js +4 -0
  72. package/dist/core/keybindings.js.map +1 -1
  73. package/dist/core/multi-agent/permission-gate.d.ts +18 -6
  74. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  75. package/dist/core/multi-agent/permission-gate.js +867 -59
  76. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  77. package/dist/core/polyphase/approval.d.ts +6 -2
  78. package/dist/core/polyphase/approval.d.ts.map +1 -1
  79. package/dist/core/polyphase/approval.js +23 -35
  80. package/dist/core/polyphase/approval.js.map +1 -1
  81. package/dist/core/polyphase/child-events.js +1 -1
  82. package/dist/core/polyphase/child-events.js.map +1 -1
  83. package/dist/core/polyphase/child-process.d.ts.map +1 -1
  84. package/dist/core/polyphase/child-process.js +65 -7
  85. package/dist/core/polyphase/child-process.js.map +1 -1
  86. package/dist/core/polyphase/commands.d.ts.map +1 -1
  87. package/dist/core/polyphase/commands.js +46 -5
  88. package/dist/core/polyphase/commands.js.map +1 -1
  89. package/dist/core/polyphase/details.d.ts.map +1 -1
  90. package/dist/core/polyphase/details.js +5 -0
  91. package/dist/core/polyphase/details.js.map +1 -1
  92. package/dist/core/polyphase/permission-bridge.d.ts +128 -0
  93. package/dist/core/polyphase/permission-bridge.d.ts.map +1 -0
  94. package/dist/core/polyphase/permission-bridge.js +357 -0
  95. package/dist/core/polyphase/permission-bridge.js.map +1 -0
  96. package/dist/core/polyphase/render/run-block.d.ts.map +1 -1
  97. package/dist/core/polyphase/render/run-block.js +13 -4
  98. package/dist/core/polyphase/render/run-block.js.map +1 -1
  99. package/dist/core/polyphase/render/snapshot.d.ts +4 -0
  100. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -1
  101. package/dist/core/polyphase/render/snapshot.js +4 -0
  102. package/dist/core/polyphase/render/snapshot.js.map +1 -1
  103. package/dist/core/polyphase/result-text.d.ts.map +1 -1
  104. package/dist/core/polyphase/result-text.js +23 -3
  105. package/dist/core/polyphase/result-text.js.map +1 -1
  106. package/dist/core/polyphase/session.d.ts +15 -1
  107. package/dist/core/polyphase/session.d.ts.map +1 -1
  108. package/dist/core/polyphase/session.js +36 -1
  109. package/dist/core/polyphase/session.js.map +1 -1
  110. package/dist/core/polyphase/settings.d.ts +1 -0
  111. package/dist/core/polyphase/settings.d.ts.map +1 -1
  112. package/dist/core/polyphase/settings.js +1 -1
  113. package/dist/core/polyphase/settings.js.map +1 -1
  114. package/dist/core/polyphase/store.d.ts +18 -0
  115. package/dist/core/polyphase/store.d.ts.map +1 -1
  116. package/dist/core/polyphase/store.js +38 -0
  117. package/dist/core/polyphase/store.js.map +1 -1
  118. package/dist/core/polyphase/types.d.ts +60 -3
  119. package/dist/core/polyphase/types.d.ts.map +1 -1
  120. package/dist/core/polyphase/types.js.map +1 -1
  121. package/dist/core/polyphase/ui/inspector.js +1 -1
  122. package/dist/core/polyphase/ui/inspector.js.map +1 -1
  123. package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -1
  124. package/dist/core/polyphase/workflow/agent-host.js +17 -3
  125. package/dist/core/polyphase/workflow/agent-host.js.map +1 -1
  126. package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -1
  127. package/dist/core/polyphase/workflow/guidance.js +16 -5
  128. package/dist/core/polyphase/workflow/guidance.js.map +1 -1
  129. package/dist/core/polyphase/workflow/launch.d.ts +2 -1
  130. package/dist/core/polyphase/workflow/launch.d.ts.map +1 -1
  131. package/dist/core/polyphase/workflow/launch.js +22 -3
  132. package/dist/core/polyphase/workflow/launch.js.map +1 -1
  133. package/dist/core/polyphase/workflow/limits.d.ts +80 -0
  134. package/dist/core/polyphase/workflow/limits.d.ts.map +1 -0
  135. package/dist/core/polyphase/workflow/limits.js +234 -0
  136. package/dist/core/polyphase/workflow/limits.js.map +1 -0
  137. package/dist/core/polyphase/workflow/runtime.d.ts +1 -1
  138. package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -1
  139. package/dist/core/polyphase/workflow/runtime.js.map +1 -1
  140. package/dist/core/polyphase/workflow/tool.d.ts +1 -0
  141. package/dist/core/polyphase/workflow/tool.d.ts.map +1 -1
  142. package/dist/core/polyphase/workflow/tool.js +23 -2
  143. package/dist/core/polyphase/workflow/tool.js.map +1 -1
  144. package/dist/core/usage-totals.d.ts +5 -0
  145. package/dist/core/usage-totals.d.ts.map +1 -1
  146. package/dist/core/usage-totals.js +16 -0
  147. package/dist/core/usage-totals.js.map +1 -1
  148. package/dist/main.d.ts.map +1 -1
  149. package/dist/main.js +4 -0
  150. package/dist/main.js.map +1 -1
  151. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  152. package/dist/modes/interactive/interactive-mode.js +2 -0
  153. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  154. package/dist/utils/shell.d.ts.map +1 -1
  155. package/dist/utils/shell.js +3 -0
  156. package/dist/utils/shell.js.map +1 -1
  157. package/docs/duet.md +1 -1
  158. package/docs/environment-variables.md +3 -1
  159. package/docs/extensions.md +2 -1
  160. package/docs/keybindings.md +1 -0
  161. package/docs/polyphase.md +97 -33
  162. package/docs/settings.md +2 -2
  163. package/package.json +10 -10
  164. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +0 -6
  165. package/dist/bundle/chunks/chunk-6ZJKIMU7.js +0 -2
  166. package/dist/bundle/chunks/chunk-736QBNUZ.js +0 -12
  167. package/dist/bundle/chunks/chunk-IWTUBX6V.js +0 -4
  168. package/dist/bundle/chunks/chunk-TIA2T6EO.js +0 -3
  169. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +0 -13
  170. package/dist/bundle/chunks/lib-XOG5PI3Y.js +0 -9
  171. package/dist/bundle/chunks/src-TIBHS42X.js +0 -4
  172. /package/dist/bundle/chunks/{chunk-ZZD35WKM.js → chunk-FBU742QF.js} +0 -0
  173. /package/dist/bundle/chunks/{chunk-SVNWI7EV.js → chunk-XHCO4PPH.js} +0 -0
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- 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-6MSE6LZ3.js";import{getBinDir,getCustomThemesDir,getThemesDir,resolvePath,stripBom}from"./chunk-6ZJKIMU7.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,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getImageDimensions:()=>getImageDimensions,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,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,renderImage:()=>renderImage,renderLatex:()=>renderLatex,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,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(regex2,opt=""){let source=typeof regex2=="string"?regex2:regex2.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{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{getBinDir,getCustomThemesDir,getThemesDir,resolvePath,stripBom}from"./chunk-VXUJMEMO.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,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getImageDimensions:()=>getImageDimensions,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,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,renderImage:()=>renderImage,renderLatex:()=>renderLatex,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,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(regex2,opt=""){let source=typeof regex2=="string"?regex2:regex2.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,`
@@ -60,7 +60,7 @@ Please report this to https://github.com/markedjs/marked.`,silent){let msg="<p>A
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":return modifier!==0?!1:matchesLegacySequence(data,LEGACY_KEY_SEQUENCES[key])}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)}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===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)return formatParsedKey(kitty.codepoint,kitty.modifier,kitty.baseLayoutKey);let modifyOtherKeys=parseModifyOtherKeysSequence(data);if(modifyOtherKeys)return formatParsedKey(modifyOtherKeys.codepoint,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
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))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}: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"||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;function registerKittyImageMetadata(metadata){if(kittyTransmissionGeneration+=1,kittyImageMetadata.delete(metadata.imageId),kittyImageMetadata.set(metadata.imageId,{...metadata,transmissionGeneration:kittyTransmissionGeneration}),kittyImageMetadata.size>1e3){let oldestImageId=kittyImageMetadata.keys().next().value;oldestImageId!==void 0&&kittyImageMetadata.delete(oldestImageId)}}function getRegisteredKittyImageMetadata(line){let controls=/\x1b_G([^;]*);/.exec(line)?.[1];if(!controls)return;let imageId=/(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];return imageId===void 0?void 0:kittyImageMetadata.get(Number.parseInt(imageId,10))}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 getKittyImagePlacement(line){let match=/\x1b_G([^;]*);/.exec(line),metadata=getRegisteredKittyImageMetadata(line);if(!match||!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,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";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){}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,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,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=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)+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.slice(0,markerIndex)+line.slice(markerIndex+CURSOR_MARKER.length),{row,col}}}return null}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}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 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+home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+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:"home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"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}var Text=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(text="",paddingX=1,paddingY=1,customBgFn){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.customBgFn=customBgFn}setText(text){this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(customBgFn){this.customBgFn=customBgFn,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;if(!this.text||this.text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=this.text.replace(/\t/g," "),paddingX=Math.min(this.paddingX,Math.max(0,Math.floor((width-1)/2))),contentWidth=Math.max(1,width-paddingX*2),wrappedLines=wrapTextWithAnsi(normalizedText,contentWidth),leftMargin=" ".repeat(paddingX),rightMargin=" ".repeat(paddingX),contentLines=[];for(let line of wrappedLines){let lineWithMargins=leftMargin+line+rightMargin;if(this.customBgFn)contentLines.push(applyBackgroundToLine(lineWithMargins,width,this.customBgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);contentLines.push(lineWithMargins+" ".repeat(paddingNeeded))}}let emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=this.customBgFn?applyBackgroundToLine(emptyLine,width,this.customBgFn):emptyLine;emptyLines.push(line)}let result=[...emptyLines,...contentLines,...emptyLines];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};var DEFAULT_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{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();kb.matches(keyData,"tui.select.up")?(this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange()):kb.matches(keyData,"tui.select.down")?(this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange()):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;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
- `);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=`\x1B[7m${firstGrapheme}\x1B[0m`;displayText=before+marker+cursor+restAfter}else displayText=before+marker+"\x1B[7m \x1B[0m",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")){this.autocompleteList.handleInput(data);return}if(kb.matches(data,"tui.input.tab")){let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(kb.matches(data,"tui.select.confirm")){let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);if(this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.autocompletePrefix.startsWith("/"))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(kb.matches(data,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(kb.matches(data,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteCharBackward")||matchesKey(data,"shift+backspace")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")||matchesKey(data,"shift+delete")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(kb.matches(data,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(kb.matches(data,"tui.input.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===`
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=`\x1B[7m${firstGrapheme}\x1B[0m`;displayText=before+marker+cursor+restAfter}else displayText=before+marker+"\x1B[7m \x1B[0m",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")){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(`
66
66
  `))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(text){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let normalized=this.normalizeText(text);this.getText()!==normalized&&this.pushUndoSnapshot(),this.pastes.clear(),this.pasteCounter=0,this.setTextInternal(normalized)}insertTextAtCursor(text){text&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing(),this.insertTextAtCursorInternal(text))}normalizeText(text){return text.replace(/\r\n/g,`
@@ -75,7 +75,7 @@ Please report this to https://github.com/markedjs/marked.`,silent){let msg="<p>A
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(`
76
76
  `,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let wasKill=this.lastAction==="kill",oldCursorCol=this.state.cursorCol;this.moveWordForwards();let deleteTo=this.state.cursorCol;this.setCursorCol(oldCursorCol);let deletedText=currentLine.slice(this.state.cursorCol,deleteTo);this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)+currentLine.slice(deleteTo)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.length){this.pushUndoSnapshot();let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=[...this.segment(afterCursor,"grapheme")][0],graphemeLength=firstGrapheme?firstGrapheme.segment.length:1,before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol+graphemeLength);this.state.lines[this.state.cursorLine]=before+after}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(width){let visualLines=[];for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",lineVisWidth=visibleWidth(line);if(line.length===0)visualLines.push({logicalLine:i,startCol:0,length:0});else if(lineVisWidth<=width)visualLines.push({logicalLine:i,startCol:0,length:line.length});else{let chunks=wordWrapLine(line,width,[...this.segment(line,"grapheme")]);for(let chunk of chunks)visualLines.push({logicalLine:i,startCol:chunk.startIndex,length:chunk.endIndex-chunk.startIndex})}}return visualLines}findVisualLineAt(visualLines,line,col){for(let i=0;i<visualLines.length;i++){let vl=visualLines[i];if(!vl||vl.logicalLine!==line)continue;let offset=col-vl.startCol,isLastSegmentOfLine=i===visualLines.length-1||visualLines[i+1]?.logicalLine!==vl.logicalLine;if(offset>=0&&(offset<vl.length||isLastSegmentOfLine&&offset===vl.length))return i}return visualLines.length-1}findCurrentVisualLine(visualLines){return this.findVisualLineAt(visualLines,this.state.cursorLine,this.state.cursorCol)}moveCursor(deltaLine,deltaCol){this.lastAction=null;let visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.findCurrentVisualLine(visualLines);if(deltaLine!==0){let targetVisualLine=currentVisualLine+deltaLine;targetVisualLine>=0&&targetVisualLine<visualLines.length&&this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}if(deltaCol!==0){let currentLine=this.state.lines[this.state.cursorLine]||"";if(deltaCol>0)if(this.state.cursorCol<currentLine.length){let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=[...this.segment(afterCursor,"grapheme")][0];this.setCursorCol(this.state.cursorCol+(firstGrapheme?firstGrapheme.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let currentVL=visualLines[currentVisualLine];currentVL&&(this.preferredVisualCol=this.state.cursorCol-currentVL.startCol)}else if(this.state.cursorCol>0){let beforeCursor=currentLine.slice(0,this.state.cursorCol),graphemes=[...this.segment(beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.length-1];this.setCursorCol(this.state.cursorCol-(lastGrapheme?lastGrapheme.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(direction){this.lastAction=null;let terminalRows=this.tui.terminal.rows,pageSize=Math.max(5,Math.floor(terminalRows*.3)),visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.findCurrentVisualLine(visualLines),targetVisualLine=Math.max(0,Math.min(visualLines.length-1,currentVisualLine+direction*pageSize));this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}moveWordBackwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}return}this.setCursorCol(findWordBackward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}insertYankedText(text){this.exitHistoryBrowsing();let lines=text.split(`
77
77
  `);if(lines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+text+after,this.setCursorCol(this.state.cursorCol+text.length)}else{let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+(lines[0]||"");for(let i=1;i<lines.length-1;i++)this.state.lines.splice(this.state.cursorLine+i,0,lines[i]||"");let lastLineIndex=this.state.cursorLine+lines.length-1;this.state.lines.splice(lastLineIndex,0,(lines[lines.length-1]||"")+after),this.state.cursorLine=lastLineIndex,this.setCursorCol((lines[lines.length-1]||"").length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){let yankedText=this.killRing.peek();if(!yankedText)return;let yankLines=yankedText.split(`
78
- `);if(yankLines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",deleteLen=yankedText.length,before=currentLine.slice(0,this.state.cursorCol-deleteLen),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-deleteLen)}else{let startLine=this.state.cursorLine-(yankLines.length-1),startCol=(this.state.lines[startLine]||"").length-(yankLines[0]||"").length,afterCursor=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),beforeYank=(this.state.lines[startLine]||"").slice(0,startCol);this.state.lines.splice(startLine,yankLines.length,beforeYank+afterCursor),this.state.cursorLine=startLine,this.setCursorCol(startCol)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let snapshot=this.undoStack.pop();snapshot&&(Object.assign(this.state,snapshot.state),this.pastes=snapshot.pastes,this.pasteCounter=snapshot.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(char,direction){this.lastAction=null;let isForward=direction==="forward",lines=this.state.lines,end=isForward?lines.length:-1,step=isForward?1:-1;for(let lineIdx=this.state.cursorLine;lineIdx!==end;lineIdx+=step){let line=lines[lineIdx]||"",searchFrom=lineIdx===this.state.cursorLine?isForward?this.state.cursorCol+1:this.state.cursorCol-1:void 0,idx=isForward?line.indexOf(char,searchFrom):line.lastIndexOf(char,searchFrom);if(idx!==-1){this.state.cursorLine=lineIdx,this.setCursorCol(idx);return}}}moveWordForwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(findWordForward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return beforeCursor.trim()===""||beforeCursor.trim()==="/"}isInSlashCommandContext(textBeforeCursor){return this.isSlashMenuAllowed()&&textBeforeCursor.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(items,prefix){if(!prefix)return-1;let firstPrefixIndex=-1;for(let i=0;i<items.length;i++){let value=items[i].value;if(value===prefix)return i;firstPrefixIndex===-1&&value.startsWith(prefix)&&(firstPrefixIndex=i)}return firstPrefixIndex}createAutocompleteList(prefix,items){let layout=prefix.startsWith("/")?SLASH_COMMAND_SELECT_LIST_LAYOUT:void 0,list2=new SelectList(items,this.autocompleteMaxVisible,this.theme.selectList,layout);return list2.onSelect=selected=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},list2}tryTriggerAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!1,explicitTab})}handleTabCompletion(){if(!this.autocompleteProvider)return;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(beforeCursor)&&!beforeCursor.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!0,explicitTab})}requestAutocomplete(options2){if(!this.autocompleteProvider||options2.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let startToken=++this.autocompleteStartToken,debounceMs=this.getAutocompleteDebounceMs(options2);if(debounceMs>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(startToken,options2)},debounceMs);return}this.startAutocompleteRequest(startToken,options2)}async startAutocompleteRequest(startToken,options2){let previousTask=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await previousTask,startToken!==this.autocompleteStartToken||!this.autocompleteProvider)return;let controller=new AbortController;this.autocompleteAbort=controller;let requestId=++this.autocompleteRequestId,snapshotText=this.getText(),snapshotLine=this.state.cursorLine,snapshotCol=this.state.cursorCol;await this.runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options2)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(triggerCharacters){let next=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];for(let character of triggerCharacters)character.length!==1||character==="/"||isWhitespaceChar(character)||next.includes(character)||next.push(character);this.autocompleteTriggerCharacters=next,this.autocompleteTriggerPattern=buildTriggerPattern(next),this.autocompleteDebouncePattern=buildDebouncePattern(next)}getAutocompleteDebounceMs(options2){if(options2.explicitTab||options2.force)return 0;let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(textBeforeCursor)?ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS:0}async runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options2){if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:controller.signal,force:options2.force});if(this.isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol)){if(this.autocompleteAbort=void 0,!suggestions||!Array.isArray(suggestions.items)||suggestions.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(options2.force&&options2.explicitTab&&suggestions.items.length===1){let item=suggestions.items[0];this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,item,suggestions.prefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(suggestions,options2.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol){return!controller.signal.aborted&&requestId===this.autocompleteRequestId&&this.getText()===snapshotText&&this.state.cursorLine===snapshotLine&&this.state.cursorCol===snapshotCol}applyAutocompleteSuggestions(suggestions,state){this.autocompletePrefix=suggestions.prefix,this.autocompleteList=this.createAutocompleteList(suggestions.prefix,suggestions.items);let bestMatchIndex=this.getBestAutocompleteMatchIndex(suggestions.items,suggestions.prefix);bestMatchIndex>=0&&this.autocompleteList.setSelectedIndex(bestMatchIndex),this.autocompleteState=state}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var LAYOUT_NODE=Symbol.for("@draht/tui/layout-node");function getLayoutNode(component){let candidate=component;return typeof candidate[LAYOUT_NODE]=="function"?candidate[LAYOUT_NODE]():void 0}function isStackEntry(child){return!("render"in child)}function normalizeSize(value,fallback){return value===void 0||!Number.isFinite(value)?fallback:Math.max(0,Math.floor(value))}var Stack=class extends Container{entries=[];gap;align;constructor(children=[],options2={}){super(),this.gap=normalizeSize(options2.gap,0),this.align=options2.align??"stretch";for(let child of children)isStackEntry(child)?this.addChild(child.component,child):this.addChild(child)}addChild(component,options2={}){super.addChild(component),this.entries.push({component,...options2.basis===void 0?{}:{basis:options2.basis},...options2.grow===void 0?{}:{grow:normalizeSize(options2.grow,0)},...options2.shrink===void 0?{}:{shrink:normalizeSize(options2.shrink,1)},...options2.minSize===void 0?{}:{minSize:normalizeSize(options2.minSize,0)},...options2.maxSize===void 0?{}:{maxSize:normalizeSize(options2.maxSize,Number.MAX_SAFE_INTEGER)},...options2.visible===void 0?{}:{visible:options2.visible}})}removeChild(component){super.removeChild(component);let index=this.entries.findIndex(entry=>entry.component===component);index!==-1&&this.entries.splice(index,1)}clear(){super.clear(),this.entries.length=0}[LAYOUT_NODE](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function visibleStackEntries(entries,viewport){return entries.filter(entry=>entry.visible?.(viewport)??!0)}function clampSize(size,entry){let min=Math.max(0,Math.floor(entry.minSize??0)),max=Math.max(min,Math.floor(entry.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(min,Math.min(max,Math.max(0,Math.floor(size))))}function distribute(sizes,entries,amount,mode){let remaining=amount;for(;remaining>0;){let candidates=entries.map((entry,index)=>({entry,index})).filter(({entry,index})=>mode==="grow"?(entry.grow??0)>0&&sizes[index]<(entry.maxSize??Number.MAX_SAFE_INTEGER):(entry.shrink??1)>0&&sizes[index]>(entry.minSize??0));if(candidates.length===0)return;let totalWeight=candidates.reduce((sum,{entry,index})=>sum+(mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index])),0),distributed=0;for(let{entry,index}of candidates){if(remaining<=0)break;let weight=mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index]),proposed=Math.max(1,Math.floor(remaining*weight/totalWeight)),capacity=mode==="grow"?(entry.maxSize??Number.MAX_SAFE_INTEGER)-sizes[index]:sizes[index]-(entry.minSize??0),delta=Math.min(remaining,proposed,capacity);delta<=0||(sizes[index]=sizes[index]+(mode==="grow"?delta:-delta),remaining-=delta,distributed+=delta)}if(distributed===0)return}}function allocateStackSizes(entries,intrinsicSizes,availableSize,gap){let sizes=entries.map((entry,index)=>clampSize(entry.basis===void 0||entry.basis==="auto"?intrinsicSizes[index]??0:entry.basis,entry));if(availableSize===void 0)return sizes;let contentSize=Math.max(0,Math.floor(availableSize)-Math.max(0,entries.length-1)*gap),total=sizes.reduce((sum,size)=>sum+size,0);return total<contentSize?distribute(sizes,entries,contentSize-total,"grow"):total>contentSize&&distribute(sizes,entries,total-contentSize,"shrink"),sizes}var HStack=class extends Stack{layoutType="hstack";constructor(children=[],options2={}){super(children,options2)}render(width){let safeWidth=Math.max(1,width),viewport={width:safeWidth,height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport);if(entries.length===0)return[];let intrinsicWidths=entries.map(entry=>entry.component.render(safeWidth).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,this.gap),rendered=entries.map((entry,index)=>widths[index]===0?[]:entry.component.render(widths[index])),height=rendered.reduce((max,lines)=>Math.max(max,lines.length),0),result=Array.from({length:height},()=>""),x=0;for(let index=0;index<rendered.length;index++){let lines=rendered[index],childWidth=widths[index],offset=0;this.align==="center"?offset=Math.floor((height-lines.length)/2):this.align==="end"&&(offset=height-lines.length);for(let row=0;row<lines.length;row++){let target=row+offset;target<0||target>=result.length||(result[target]=compositeTuiLine(result[target],lines[row],x,childWidth,safeWidth))}x+=childWidth+this.gap}return result}};var Image=class{base64Data;mimeType;dimensions;theme;options;imageId;cachedLines;cachedWidth;constructor(base64Data,mimeType,theme2,options2={},dimensions){this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme2,this.options=options2,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options2.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(width){if(this.cachedLines&&this.cachedWidth===width)return this.cachedLines;let maxWidth=Math.max(1,Math.min(width-2,this.options.maxWidthCells??60)),cellDimensions2=getCellDimensions(),defaultMaxHeight=Math.max(1,Math.ceil(maxWidth*cellDimensions2.widthPx/cellDimensions2.heightPx)),maxHeight=this.options.maxHeightCells??defaultMaxHeight,caps=getCapabilities(),lines;if(caps.images){caps.images==="kitty"&&this.imageId===void 0&&(this.imageId=allocateImageId());let result=renderImage(this.base64Data,this.dimensions,{maxWidthCells:maxWidth,maxHeightCells:maxHeight,imageId:this.imageId,moveCursor:!1});if(result)if(result.imageId&&(this.imageId=result.imageId),caps.images==="kitty"){lines=[result.sequence];for(let i=0;i<result.rows-1;i++)lines.push("")}else{lines=[];for(let i=0;i<result.rows-1;i++)lines.push("");let rowOffset=result.rows-1,moveUp=rowOffset>0?`\x1B[${rowOffset}A`:"";lines.push(moveUp+result.sequence)}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}return this.cachedLines=lines,this.cachedWidth=width,lines}};var segmenter=getGraphemeSegmenter(),Input=class{value="";cursor=0;prompt;placeholder;placeholderStyle;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new KillRing;lastAction=null;undoStack=new UndoStack;constructor(options2={}){this.prompt=options2.prompt??"> ",this.placeholder=options2.placeholder??"",this.placeholderStyle=options2.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,value.length)}handleInput(data){if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining&&this.handleInput(remaining)}return}let kb=getKeybindings();if(kb.matches(data,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(kb.matches(data,"tui.input.submit")||data===`
78
+ `);if(yankLines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",deleteLen=yankedText.length,before=currentLine.slice(0,this.state.cursorCol-deleteLen),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-deleteLen)}else{let startLine=this.state.cursorLine-(yankLines.length-1),startCol=(this.state.lines[startLine]||"").length-(yankLines[0]||"").length,afterCursor=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),beforeYank=(this.state.lines[startLine]||"").slice(0,startCol);this.state.lines.splice(startLine,yankLines.length,beforeYank+afterCursor),this.state.cursorLine=startLine,this.setCursorCol(startCol)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let snapshot=this.undoStack.pop();snapshot&&(Object.assign(this.state,snapshot.state),this.pastes=snapshot.pastes,this.pasteCounter=snapshot.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(char,direction){this.lastAction=null;let isForward=direction==="forward",lines=this.state.lines,end=isForward?lines.length:-1,step=isForward?1:-1;for(let lineIdx=this.state.cursorLine;lineIdx!==end;lineIdx+=step){let line=lines[lineIdx]||"",searchFrom=lineIdx===this.state.cursorLine?isForward?this.state.cursorCol+1:this.state.cursorCol-1:void 0,idx=isForward?line.indexOf(char,searchFrom):line.lastIndexOf(char,searchFrom);if(idx!==-1){this.state.cursorLine=lineIdx,this.setCursorCol(idx);return}}}moveWordForwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(findWordForward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return beforeCursor.trim()===""||beforeCursor.trim()==="/"}isInSlashCommandContext(textBeforeCursor){return this.isSlashMenuAllowed()&&textBeforeCursor.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(items,prefix){if(!prefix)return-1;let firstPrefixIndex=-1;for(let i=0;i<items.length;i++){let value=items[i].value;if(value===prefix)return i;firstPrefixIndex===-1&&value.startsWith(prefix)&&(firstPrefixIndex=i)}return firstPrefixIndex}createAutocompleteList(prefix,items){let layout=prefix.startsWith("/")?SLASH_COMMAND_SELECT_LIST_LAYOUT:void 0,list2=new SelectList(items,this.autocompleteMaxVisible,this.theme.selectList,layout);return list2.onSelect=selected=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText()),this.continueCompletionAfter(selected)},list2}continueCompletionAfter(item){"continueCompletion"in item&&item.continueCompletion===!0&&this.tryTriggerAutocomplete()}tryTriggerAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!1,explicitTab})}handleTabCompletion(){if(!this.autocompleteProvider)return;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(beforeCursor)&&!beforeCursor.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!0,explicitTab})}requestAutocomplete(options2){if(!this.autocompleteProvider||options2.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let startToken=++this.autocompleteStartToken,debounceMs=this.getAutocompleteDebounceMs(options2);if(debounceMs>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(startToken,options2)},debounceMs);return}this.startAutocompleteRequest(startToken,options2)}async startAutocompleteRequest(startToken,options2){let previousTask=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await previousTask,startToken!==this.autocompleteStartToken||!this.autocompleteProvider)return;let controller=new AbortController;this.autocompleteAbort=controller;let requestId=++this.autocompleteRequestId,snapshotText=this.getText(),snapshotLine=this.state.cursorLine,snapshotCol=this.state.cursorCol;await this.runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options2)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(triggerCharacters){let next=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];for(let character of triggerCharacters)character.length!==1||character==="/"||isWhitespaceChar(character)||next.includes(character)||next.push(character);this.autocompleteTriggerCharacters=next,this.autocompleteTriggerPattern=buildTriggerPattern(next),this.autocompleteDebouncePattern=buildDebouncePattern(next)}getAutocompleteDebounceMs(options2){if(options2.explicitTab||options2.force)return 0;let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(textBeforeCursor)?ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS:0}async runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options2){if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:controller.signal,force:options2.force});if(this.isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol)){if(this.autocompleteAbort=void 0,!suggestions||!Array.isArray(suggestions.items)||suggestions.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(options2.force&&options2.explicitTab&&suggestions.items.length===1){let item=suggestions.items[0];this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,item,suggestions.prefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(suggestions,options2.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol){return!controller.signal.aborted&&requestId===this.autocompleteRequestId&&this.getText()===snapshotText&&this.state.cursorLine===snapshotLine&&this.state.cursorCol===snapshotCol}applyAutocompleteSuggestions(suggestions,state){this.autocompletePrefix=suggestions.prefix,this.autocompleteList=this.createAutocompleteList(suggestions.prefix,suggestions.items);let bestMatchIndex=this.getBestAutocompleteMatchIndex(suggestions.items,suggestions.prefix);bestMatchIndex>=0&&this.autocompleteList.setSelectedIndex(bestMatchIndex),this.autocompleteState=state}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var LAYOUT_NODE=Symbol.for("@draht/tui/layout-node");function getLayoutNode(component){let candidate=component;return typeof candidate[LAYOUT_NODE]=="function"?candidate[LAYOUT_NODE]():void 0}function isStackEntry(child){return!("render"in child)}function normalizeSize(value,fallback){return value===void 0||!Number.isFinite(value)?fallback:Math.max(0,Math.floor(value))}var Stack=class extends Container{entries=[];gap;align;constructor(children=[],options2={}){super(),this.gap=normalizeSize(options2.gap,0),this.align=options2.align??"stretch";for(let child of children)isStackEntry(child)?this.addChild(child.component,child):this.addChild(child)}addChild(component,options2={}){super.addChild(component),this.entries.push({component,...options2.basis===void 0?{}:{basis:options2.basis},...options2.grow===void 0?{}:{grow:normalizeSize(options2.grow,0)},...options2.shrink===void 0?{}:{shrink:normalizeSize(options2.shrink,1)},...options2.minSize===void 0?{}:{minSize:normalizeSize(options2.minSize,0)},...options2.maxSize===void 0?{}:{maxSize:normalizeSize(options2.maxSize,Number.MAX_SAFE_INTEGER)},...options2.visible===void 0?{}:{visible:options2.visible}})}removeChild(component){super.removeChild(component);let index=this.entries.findIndex(entry=>entry.component===component);index!==-1&&this.entries.splice(index,1)}clear(){super.clear(),this.entries.length=0}[LAYOUT_NODE](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function visibleStackEntries(entries,viewport){return entries.filter(entry=>entry.visible?.(viewport)??!0)}function clampSize(size,entry){let min=Math.max(0,Math.floor(entry.minSize??0)),max=Math.max(min,Math.floor(entry.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(min,Math.min(max,Math.max(0,Math.floor(size))))}function distribute(sizes,entries,amount,mode){let remaining=amount;for(;remaining>0;){let candidates=entries.map((entry,index)=>({entry,index})).filter(({entry,index})=>mode==="grow"?(entry.grow??0)>0&&sizes[index]<(entry.maxSize??Number.MAX_SAFE_INTEGER):(entry.shrink??1)>0&&sizes[index]>(entry.minSize??0));if(candidates.length===0)return;let totalWeight=candidates.reduce((sum,{entry,index})=>sum+(mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index])),0),distributed=0;for(let{entry,index}of candidates){if(remaining<=0)break;let weight=mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index]),proposed=Math.max(1,Math.floor(remaining*weight/totalWeight)),capacity=mode==="grow"?(entry.maxSize??Number.MAX_SAFE_INTEGER)-sizes[index]:sizes[index]-(entry.minSize??0),delta=Math.min(remaining,proposed,capacity);delta<=0||(sizes[index]=sizes[index]+(mode==="grow"?delta:-delta),remaining-=delta,distributed+=delta)}if(distributed===0)return}}function allocateStackSizes(entries,intrinsicSizes,availableSize,gap){let sizes=entries.map((entry,index)=>clampSize(entry.basis===void 0||entry.basis==="auto"?intrinsicSizes[index]??0:entry.basis,entry));if(availableSize===void 0)return sizes;let contentSize=Math.max(0,Math.floor(availableSize)-Math.max(0,entries.length-1)*gap),total=sizes.reduce((sum,size)=>sum+size,0);return total<contentSize?distribute(sizes,entries,contentSize-total,"grow"):total>contentSize&&distribute(sizes,entries,total-contentSize,"shrink"),sizes}var HStack=class extends Stack{layoutType="hstack";constructor(children=[],options2={}){super(children,options2)}render(width){let safeWidth=Math.max(1,width),viewport={width:safeWidth,height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport);if(entries.length===0)return[];let intrinsicWidths=entries.map(entry=>entry.component.render(safeWidth).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,this.gap),rendered=entries.map((entry,index)=>widths[index]===0?[]:entry.component.render(widths[index])),height=rendered.reduce((max,lines)=>Math.max(max,lines.length),0),result=Array.from({length:height},()=>""),x=0;for(let index=0;index<rendered.length;index++){let lines=rendered[index],childWidth=widths[index],offset=0;this.align==="center"?offset=Math.floor((height-lines.length)/2):this.align==="end"&&(offset=height-lines.length);for(let row=0;row<lines.length;row++){let target=row+offset;target<0||target>=result.length||(result[target]=compositeTuiLine(result[target],lines[row],x,childWidth,safeWidth))}x+=childWidth+this.gap}return result}};var Image=class{base64Data;mimeType;dimensions;theme;options;imageId;cachedLines;cachedWidth;constructor(base64Data,mimeType,theme2,options2={},dimensions){this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme2,this.options=options2,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options2.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(width){if(this.cachedLines&&this.cachedWidth===width)return this.cachedLines;let maxWidth=Math.max(1,Math.min(width-2,this.options.maxWidthCells??60)),cellDimensions2=getCellDimensions(),defaultMaxHeight=Math.max(1,Math.ceil(maxWidth*cellDimensions2.widthPx/cellDimensions2.heightPx)),maxHeight=this.options.maxHeightCells??defaultMaxHeight,caps=getCapabilities(),lines;if(caps.images){caps.images==="kitty"&&this.imageId===void 0&&(this.imageId=allocateImageId());let result=renderImage(this.base64Data,this.dimensions,{maxWidthCells:maxWidth,maxHeightCells:maxHeight,imageId:this.imageId,moveCursor:!1});if(result)if(result.imageId&&(this.imageId=result.imageId),caps.images==="kitty"){lines=[result.sequence];for(let i=0;i<result.rows-1;i++)lines.push("")}else{lines=[];for(let i=0;i<result.rows-1;i++)lines.push("");let rowOffset=result.rows-1,moveUp=rowOffset>0?`\x1B[${rowOffset}A`:"";lines.push(moveUp+result.sequence)}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}return this.cachedLines=lines,this.cachedWidth=width,lines}};var segmenter=getGraphemeSegmenter(),Input=class{value="";cursor=0;prompt;placeholder;placeholderStyle;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new KillRing;lastAction=null;undoStack=new UndoStack;constructor(options2={}){this.prompt=options2.prompt??"> ",this.placeholder=options2.placeholder??"",this.placeholderStyle=options2.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,value.length)}handleInput(data){if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining&&this.handleInput(remaining)}return}let kb=getKeybindings();if(kb.matches(data,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(kb.matches(data,"tui.input.submit")||data===`
79
79
  `){this.onSubmit&&this.onSubmit(this.value);return}if(kb.matches(data,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(kb.matches(data,"tui.editor.deleteToLineEnd")){this.deleteToLineEnd();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.cursorLeft")){if(this.lastAction=null,this.cursor>0){let beforeCursor=this.value.slice(0,this.cursor),graphemes=[...segmenter.segment(beforeCursor)],lastGrapheme=graphemes[graphemes.length-1];this.cursor-=lastGrapheme?lastGrapheme.segment.length:1}return}if(kb.matches(data,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let afterCursor=this.value.slice(this.cursor),firstGrapheme=[...segmenter.segment(afterCursor)][0];this.cursor+=firstGrapheme?firstGrapheme.segment.length:1}return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let kittyPrintable=decodeKittyPrintable(data);if(kittyPrintable!==void 0){this.insertCharacter(kittyPrintable);return}[...data].some(ch=>{let code=ch.charCodeAt(0);return code<32||code===127||code>=128&&code<=159})||this.insertCharacter(data)}handleMouse(event){if(event.type!=="press"||event.button!=="left"||event.y!==0)return;let visibleColumn=Math.max(0,event.x-2),targetColumn=this.renderedStartColumn+visibleColumn,currentColumn=0;this.cursor=this.value.length;for(let grapheme of segmenter.segment(this.value)){let nextColumn=currentColumn+visibleWidth(grapheme.segment);if(targetColumn<nextColumn){this.cursor=grapheme.index;break}currentColumn=nextColumn}return this.lastAction=null,{handled:!0,focus:!0}}insertCharacter(char){(isWhitespaceChar(char)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+char+this.value.slice(this.cursor),this.cursor+=char.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let beforeCursor=this.value.slice(0,this.cursor),graphemes=[...segmenter.segment(beforeCursor)],lastGrapheme=graphemes[graphemes.length-1],graphemeLength=lastGrapheme?lastGrapheme.segment.length:1;this.value=this.value.slice(0,this.cursor-graphemeLength)+this.value.slice(this.cursor),this.cursor-=graphemeLength}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let afterCursor=this.value.slice(this.cursor),firstGrapheme=[...segmenter.segment(afterCursor)][0],graphemeLength=firstGrapheme?firstGrapheme.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+graphemeLength)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let deletedText=this.value.slice(0,this.cursor);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let deletedText=this.value.slice(this.cursor);this.killRing.push(deletedText,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let wasKill=this.lastAction==="kill";this.pushUndo();let oldCursor=this.cursor;this.moveWordBackwards();let deleteFrom=this.cursor;this.cursor=oldCursor;let deletedText=this.value.slice(deleteFrom,this.cursor);this.killRing.push(deletedText,{prepend:!0,accumulate:wasKill}),this.lastAction="kill",this.value=this.value.slice(0,deleteFrom)+this.value.slice(this.cursor),this.cursor=deleteFrom}deleteWordForward(){if(this.cursor>=this.value.length)return;let wasKill=this.lastAction==="kill";this.pushUndo();let oldCursor=this.cursor;this.moveWordForwards();let deleteTo=this.cursor;this.cursor=oldCursor;let deletedText=this.value.slice(this.cursor,deleteTo);this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(deleteTo)}yank(){let text=this.killRing.peek();text&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+text+this.value.slice(this.cursor),this.cursor+=text.length,this.lastAction="yank")}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let prevText=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-prevText.length)+this.value.slice(this.cursor),this.cursor-=prevText.length,this.killRing.rotate();let text=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+text+this.value.slice(this.cursor),this.cursor+=text.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let snapshot=this.undoStack.pop();snapshot&&(this.value=snapshot.value,this.cursor=snapshot.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=findWordBackward(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=findWordForward(this.value,this.cursor))}handlePaste(pastedText){this.lastAction=null,this.pushUndo();let cleanText=pastedText.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+cleanText+this.value.slice(this.cursor),this.cursor+=cleanText.length}invalidate(){}render(width){let availableWidth=width-visibleWidth(this.prompt);if(availableWidth<=0)return[truncateToWidth(this.prompt,width,"")];if(this.value.length===0&&this.placeholder){let placeholder=truncateToWidth(this.placeholder,availableWidth,""),atCursor2=[...segmenter.segment(placeholder)][0]?.segment??" ",afterCursor2=placeholder.slice(atCursor2.length),marker2=this.focused?CURSOR_MARKER:"",cursorChar2=`\x1B[7m${this.placeholderStyle(atCursor2)}\x1B[27m`,textWithCursor2=marker2+cursorChar2+this.placeholderStyle(afterCursor2),padding2=" ".repeat(Math.max(0,availableWidth-visibleWidth(textWithCursor2)));return[this.prompt+textWithCursor2+padding2]}let visibleText="",cursorDisplay=this.cursor;this.renderedStartColumn=0;let totalWidth=visibleWidth(this.value);if(totalWidth<availableWidth)visibleText=this.value;else{let scrollWidth=this.cursor===this.value.length?availableWidth-1:availableWidth,cursorCol=visibleWidth(this.value.slice(0,this.cursor));if(scrollWidth>0){let halfWidth=Math.floor(scrollWidth/2),startCol=0;cursorCol<halfWidth?startCol=0:cursorCol>totalWidth-halfWidth?startCol=Math.max(0,totalWidth-scrollWidth):startCol=Math.max(0,cursorCol-halfWidth),this.renderedStartColumn=startCol,visibleText=sliceByColumn(this.value,startCol,scrollWidth,!0),cursorDisplay=sliceByColumn(this.value,startCol,Math.max(0,cursorCol-startCol),!0).length}else visibleText="",cursorDisplay=0}let cursorGrapheme=[...segmenter.segment(visibleText.slice(cursorDisplay))][0],beforeCursor=visibleText.slice(0,cursorDisplay),atCursor=cursorGrapheme?.segment??" ",afterCursor=visibleText.slice(cursorDisplay+atCursor.length),marker=this.focused?CURSOR_MARKER:"",cursorChar=`\x1B[7m${atCursor}\x1B[27m`,textWithCursor=beforeCursor+marker+cursorChar+afterCursor,visualLength=visibleWidth(textWithCursor),padding=" ".repeat(Math.max(0,availableWidth-visualLength));return[this.prompt+textWithCursor+padding]}};var SYMBOLS={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",varkappa:"\u03F0",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9",pm:"\xB1",mp:"\u2213",times:"\xD7",div:"\xF7",cdot:"\xB7",ast:"\u2217",star:"\u22C6",circ:"\u2218",bullet:"\u2022",oplus:"\u2295",ominus:"\u2296",otimes:"\u2297",oslash:"\u2298",odot:"\u2299",bigcirc:"\u25CB",dagger:"\u2020",ddagger:"\u2021",amalg:"\u2A3F",uplus:"\u228E",sqcap:"\u2293",sqcup:"\u2294",bowtie:"\u22C8",Join:"\u22C8",ltimes:"\u22C9",rtimes:"\u22CA",leftouterjoin:"\u27D5",rightouterjoin:"\u27D6",fullouterjoin:"\u27D7",triangleleft:"\u25C1",triangleright:"\u25B7",wr:"\u2240",cap:"\u2229",cup:"\u222A",bigcap:"\u22C2",bigcup:"\u22C3",bigwedge:"\u22C0",bigvee:"\u22C1",bigsqcup:"\u2A06",biguplus:"\u2A04",bigoplus:"\u2A01",bigotimes:"\u2A02",bigodot:"\u2A00",setminus:"\u2216",in:"\u2208",notin:"\u2209",ni:"\u220B",subset:"\u2282",supset:"\u2283",subseteq:"\u2286",supseteq:"\u2287",sqsubset:"\u228F",sqsupset:"\u2290",sqsubseteq:"\u2291",sqsupseteq:"\u2292",prec:"\u227A",preceq:"\u227C",succ:"\u227B",succeq:"\u227D",ll:"\u226A",gg:"\u226B",le:"\u2264",leq:"\u2264",leqslant:"\u2264",ge:"\u2265",geq:"\u2265",geqslant:"\u2265",ne:"\u2260",neq:"\u2260",equiv:"\u2261",approx:"\u2248",sim:"\u223C",simeq:"\u2243",cong:"\u2245",asymp:"\u224D",doteq:"\u2250",propto:"\u221D",parallel:"\u2225",perp:"\u22A5",mid:"\u2223",vdash:"\u22A2",dashv:"\u22A3",models:"\u22A8",Vdash:"\u22A9",Vvdash:"\u22AA",nvdash:"\u22AC",nvDash:"\u22AD",forall:"\u2200",exists:"\u2203",nexists:"\u2204",neg:"\xAC",land:"\u2227",wedge:"\u2227",lor:"\u2228",vee:"\u2228",to:"\u2192",rightarrow:"\u2192",longrightarrow:"\u2192",leftarrow:"\u2190",longleftarrow:"\u2190",gets:"\u2190",leftrightarrow:"\u2194",longleftrightarrow:"\u2194",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",leftharpoonup:"\u21BC",leftharpoondown:"\u21BD",rightharpoonup:"\u21C0",rightharpoondown:"\u21C1",rightleftharpoons:"\u21CC",leftrightharpoons:"\u21CB",nearrow:"\u2197",searrow:"\u2198",swarrow:"\u2199",nwarrow:"\u2196",rightsquigarrow:"\u21DD",leadsto:"\u21DD",Rightarrow:"\u21D2",Longrightarrow:"\u21D2",Leftarrow:"\u21D0",Longleftarrow:"\u21D0",Leftrightarrow:"\u21D4",Longleftrightarrow:"\u21D4",implies:"\u21D2",iff:"\u21D4",mapsto:"\u21A6",longmapsto:"\u21A6",uparrow:"\u2191",downarrow:"\u2193",partial:"\u2202",nabla:"\u2207",int:"\u222B",iint:"\u222C",iiint:"\u222D",oint:"\u222E",sum:"\u2211",prod:"\u220F",coprod:"\u2210",infty:"\u221E",emptyset:"\u2205",varnothing:"\u2205",angle:"\u2220",therefore:"\u2234",because:"\u2235",aleph:"\u2135",beth:"\u2136",gimel:"\u2137",daleth:"\u2138",top:"\u22A4",bot:"\u22A5",triangle:"\u25B3",square:"\u25A1",lozenge:"\u25CA",checkmark:"\u2713",complement:"\u2201",wp:"\u2118",prime:"\u2032",ldots:"\u2026",dots:"\u2026",cdots:"\u22EF",vdots:"\u22EE",ddots:"\u22F1",ell:"\u2113",hbar:"\u210F",Im:"\u2111",Re:"\u211C",langle:"\u27E8",rangle:"\u27E9",vert:"|",lvert:"|",rvert:"|",Vert:"\u2016",lVert:"\u2016",rVert:"\u2016",lbrace:"{",rbrace:"}",backslash:"\\",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309",colon:":"},NAMED_OPERATORS=new Set(["arccos","arcsin","arctan","arg","cos","cosh","cot","coth","csc","deg","det","dim","exp","gcd","hom","inf","ker","lg","lim","liminf","limsup","ln","log","max","min","Pr","sec","sin","sinh","sup","tan","tanh"]),LIMIT_OPERATORS=new Set(["argmax","argmin","inf","injlim","lim","liminf","limsup","max","min","projlim","sup"]),DISPLAY_LIMIT_SYMBOLS=new Set(["bigcap","bigcup","bigodot","bigoplus","bigotimes","bigsqcup","biguplus","bigvee","bigwedge","coprod","int","iint","iiint","oint","prod","sum"]),RELATION_COMMANDS=new Set(["Leftarrow","Leftrightarrow","Longleftarrow","Longleftrightarrow","Longrightarrow","Rightarrow","Join","Vdash","Vvdash","approx","asymp","bowtie","cong","dashv","fullouterjoin","doteq","downarrow","equiv","ge","geq","geqslant","gets","gg","hookleftarrow","hookrightarrow","iff","implies","in","leadsto","le","leftarrow","leftharpoondown","leftharpoonup","leftrightarrow","leftrightharpoons","leftouterjoin","leq","leqslant","ll","longleftarrow","longleftrightarrow","longmapsto","longrightarrow","ltimes","mapsto","mid","models","ne","nearrow","neq","ni","notin","nvdash","nvDash","nwarrow","parallel","perp","prec","preceq","propto","rightharpoondown","rightharpoonup","rightleftharpoons","rightouterjoin","rightarrow","rightsquigarrow","rtimes","searrow","sim","simeq","sqsubset","sqsubseteq","sqsupset","sqsupseteq","subset","subseteq","succ","succeq","supset","supseteq","swarrow","to","triangleleft","triangleright","twoheadleftarrow","twoheadrightarrow","uparrow","vdash"]),NEGATED_SYMBOLS={"<":"\u226E",">":"\u226F","=":"\u2260","\u2208":"\u2209","\u220B":"\u220C","\u2223":"\u2224","\u2225":"\u2226","\u223C":"\u2241","\u2243":"\u2244","\u2245":"\u2247","\u2248":"\u2249","\u2261":"\u2262","\u2264":"\u2270","\u2265":"\u2271","\u227A":"\u2280","\u227B":"\u2281","\u2282":"\u2284","\u2283":"\u2285","\u2286":"\u2288","\u2287":"\u2289","\u22A2":"\u22AC","\u22A8":"\u22AD","\u2194":"\u21AE","\u2190":"\u219A","\u2192":"\u219B","\u21D2":"\u21CF","\u21D0":"\u21CD","\u21D4":"\u21CE","\u227C":"\u22E0","\u227D":"\u22E1"},BLACKBOARD={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},SUPERSCRIPTS={0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},SUBSCRIPTS={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"},SPACING_COMMANDS=new Set([",",":",";"," ",">","enspace","enskip","medspace","quad","qquad","thickspace","thinspace"]),NEGATIVE_SPACING_COMMANDS=new Set(["!","negmedspace","negthickspace","negthinspace"]),NEGATIVE_SPACE="\0",FONT_SWITCH_COMMANDS=new Set(["bf","cal","it","rm","sf","sl","tt"]),IGNORED_COMMANDS=new Set(["displaystyle","limits","nolimits","scriptstyle","scriptscriptstyle","textstyle"]),SIZE_COMMANDS=new Set(["big","Big","bigg","Bigg","bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr"]),PLAIN_WRAPPERS=new Set(["emph","mathcal","mathbf","mathfrak","mathit","mathrm","mathnormal","mathscr","mathsf","mathtt","mathup","mbox","overbrace","pmb","smash","substack","text","textbf","textit","textmd","textnormal","textrm","textsc","textsf","textsl","texttt","textup","underbrace","bm","boldsymbol"]),ACCENTS={acute:"\u0301",bar:"\u0305",breve:"\u0306",check:"\u030C",ddot:"\u0308",dot:"\u0307",grave:"\u0300",hat:"\u0302",mathring:"\u030A",overleftarrow:"\u20D6",overleftrightarrow:"\u20E1",overline:"\u0305",overrightarrow:"\u20D7",tilde:"\u0303",underline:"\u0332",vec:"\u20D7",widehat:"\u0302",widetilde:"\u0303"};function replaceCharacters(value,replacements){let result="";for(let character of value){let replacement=replacements[character];if(replacement===void 0)return;result+=replacement}return result}function normalizeScriptValue(value){return value.trim().replace(/\s*([=+-])\s*/g,"$1")}function formatUnicodeScript(value,kind){return replaceCharacters(normalizeScriptValue(value),kind==="sub"?SUBSCRIPTS:SUPERSCRIPTS)}function formatScript(value,kind){value=normalizeScriptValue(value);let unicode=formatUnicodeScript(value,kind);if(unicode!==void 0)return unicode;let prefix=kind==="sub"?"_":"^";return Array.from(value).length===1||kind==="sub"&&/^[A-Za-z]+$/.test(value)?`${prefix}${value}`:`${prefix}(${value})`}function formatFraction(numerator,denominator){numerator=numerator.trim(),denominator=denominator.trim();let simpleNumerator=/^[\p{L}\p{N}.]+$/u.test(numerator),simpleDenominator=/^[\p{N}.]+$/u.test(denominator)||Array.from(denominator).length===1;return`${simpleNumerator?numerator:`(${numerator})`}/${simpleDenominator?denominator:`(${denominator})`}`}function formatRoot(value,symbol="\u221A"){return value=value.trim(),/^[\p{L}\p{N}.]+$/u.test(value)?`${symbol}${value}`:`${symbol}(${value})`}var NAMED_OPERATOR_START="\u{F0004}",NAMED_OPERATOR_END="\u{F0005}",NAMED_OPERATOR_LEFT_SPACING_PATTERN=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,NAMED_OPERATOR_RIGHT_SPACING_PATTERN=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function normalizeOutput(value){return value.replace(NAMED_OPERATOR_LEFT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_START,"").replace(NAMED_OPERATOR_RIGHT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_END,"").split(`
80
80
  `).map(line=>line.replace(/[ \t]+/g," ").trim()).filter((line,index,lines)=>line.length>0||index>0&&index<lines.length-1).join(`
81
81
  `).trim()}var LAYOUT_MARKER_START="\u{F0000}",LAYOUT_MARKER_END="\u{F0001}",LAYOUT_MARKER_PATTERN=/\u{f0000}(\d+)\u{f0001}/gu,TRAILING_LAYOUT_MARKER_PATTERN=/\u{f0000}(\d+)\u{f0001}$/u,PROTECTED_SPACE="\u{F0002}";function padLayoutLine(line,width,centered=!1){let padding=Math.max(0,width-visibleWidth(line)),left=centered?Math.floor(padding/2):0;return`${" ".repeat(left)}${line}${" ".repeat(padding-left)}`}function joinLayouts(layouts){if(layouts.length===0)return{lines:[""],width:0,baseline:0};let baseline=Math.max(...layouts.map(layout=>layout.baseline)),below=Math.max(...layouts.map(layout=>layout.lines.length-layout.baseline-1)),lines=[];for(let row=0;row<=baseline+below;row++){let line="";for(let layout of layouts){let sourceRow=row-baseline+layout.baseline;line+=sourceRow>=0&&sourceRow<layout.lines.length?padLayoutLine(layout.lines[sourceRow]??"",layout.width):" ".repeat(layout.width)}lines.push(line.trimEnd())}return{lines,width:layouts.reduce((width,layout)=>width+layout.width,0),baseline}}function renderLayout(source,nodes){let renderedLines=[],firstBaseline=0;for(let sourceLine of source.split(`
@@ -120,7 +120,7 @@ Please report this to https://github.com/markedjs/marked.`,silent){let msg="<p>A
120
120
 
121
121
  Searched Git Bash in:
122
122
  ${paths.map(p=>` ${p}`).join(`
123
- `)}`)}if(existsSync("/bin/bash"))return getBashShellConfig("/bin/bash");let bashOnPath=findExecutableOnPath("bash");return bashOnPath?getBashShellConfig(bashOnPath):{shell:"sh",args:["-c"]}}var POWERSHELL_ARGS=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];function getPowerShellConfig(){if(process.platform!=="win32")throw new Error("The powershell tool is only available on Windows.");let shell=findExecutableOnPath("pwsh.exe")??findExecutableOnPath("powershell.exe");if(!shell)throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");return{shell,args:[...POWERSHELL_ARGS]}}function getShellEnv(){let binDir=getBinDir(),pathKey=Object.keys(process.env).find(key=>key.toLowerCase()==="path")??"PATH",currentPath=process.env[pathKey]??"",updatedPath=currentPath.split(delimiter).filter(Boolean).includes(binDir)?currentPath:[binDir,currentPath].filter(Boolean).join(delimiter),env2={...process.env,[pathKey]:updatedPath};return delete env2.DRAHT_POLYPHASE_DEPTH,delete env2.DRAHT_POLYPHASE_SCHEMA_FILE,env2}function sanitizeBinaryOutput(str2){return str2.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,"")}var trackedDetachedChildPids=new Set;function trackDetachedChildPid(pid){trackedDetachedChildPids.add(pid)}function untrackDetachedChildPid(pid){trackedDetachedChildPids.delete(pid)}function killTrackedDetachedChildren(){for(let pid of trackedDetachedChildPids)killProcessTree(pid);trackedDetachedChildPids.clear()}function killProcessTree(pid){if(process.platform==="win32")try{spawn2(join6(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(pid)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}else try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}import*as fs3 from"node:fs";import*as path4 from"node:path";import{watch}from"node:fs";var FS_WATCH_RETRY_DELAY_MS=5e3;function closeWatcher(watcher){if(watcher)try{watcher.close()}catch{}}function watchWithErrorHandler(path5,listener,onError){try{let watcher=watch(path5,listener);return watcher.on("error",onError),watcher}catch{return onError(),null}}var import_core=__toESM(require_core(),1),import_bash=__toESM(require_bash(),1),import_c=__toESM(require_c(),1),import_cpp=__toESM(require_cpp(),1),import_csharp=__toESM(require_csharp(),1),import_dart=__toESM(require_dart(),1),import_go=__toESM(require_go(),1),import_groovy=__toESM(require_groovy(),1),import_java=__toESM(require_java(),1),import_javascript=__toESM(require_javascript(),1),import_json=__toESM(require_json(),1),import_kotlin=__toESM(require_kotlin(),1),import_lua=__toESM(require_lua(),1),import_nix=__toESM(require_nix(),1),import_perl=__toESM(require_perl(),1),import_php=__toESM(require_php(),1),import_python=__toESM(require_python(),1),import_ruby=__toESM(require_ruby(),1),import_rust=__toESM(require_rust(),1),import_scala=__toESM(require_scala(),1),import_swift=__toESM(require_swift(),1),import_typescript=__toESM(require_typescript(),1);function decodeCodePoint(codePoint){if(!(!Number.isInteger(codePoint)||codePoint<0||codePoint>1114111))return String.fromCodePoint(codePoint)}function decodeHtmlEntity(entity){switch(entity){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'"}if(entity.startsWith("#x")||entity.startsWith("#X"))return decodeCodePoint(Number.parseInt(entity.slice(2),16));if(entity.startsWith("#"))return decodeCodePoint(Number.parseInt(entity.slice(1),10))}function decodeHtmlEntityAt(html2,index){let semicolonIndex=html2.indexOf(";",index+1);if(semicolonIndex===-1||semicolonIndex-index>16)return;let entity=html2.slice(index+1,semicolonIndex),decoded=decodeHtmlEntity(entity);if(decoded!==void 0)return{text:decoded,length:semicolonIndex-index+1}}var eagerLanguages={python:import_python.default,java:import_java.default,go:import_go.default,javascript:import_javascript.default,json:import_json.default,cpp:import_cpp.default,typescript:import_typescript.default,php:import_php.default,ruby:import_ruby.default,c:import_c.default,csharp:import_csharp.default,nix:import_nix.default,bash:import_bash.default,rust:import_rust.default,scala:import_scala.default,kotlin:import_kotlin.default,swift:import_swift.default,dart:import_dart.default,groovy:import_groovy.default,perl:import_perl.default,lua:import_lua.default};for(let[name,language]of Object.entries(eagerLanguages))import_core.default.registerLanguage(name,language);var allLanguagesPromise;function loadAllHighlightLanguages(){return allLanguagesPromise||(allLanguagesPromise=new Promise(resolve=>{setImmediate(()=>{import("./lib-XOG5PI3Y.js").then(()=>resolve(),()=>{resolve()})})})),allLanguagesPromise}var SPAN_CLOSE="</span>",HIGHLIGHT_CLASS_PREFIX="hljs-";function getScopeFromSpanTag(tag2){let match=/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag2),classValue=match?.[1]??match?.[2];if(classValue){for(let className of classValue.split(/\s+/))if(className.startsWith(HIGHLIGHT_CLASS_PREFIX))return className.slice(HIGHLIGHT_CLASS_PREFIX.length)}}function getScopeFormatter(scope,theme2){let exact=theme2[scope];if(exact)return exact;let dotIndex=scope.indexOf(".");if(dotIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dotIndex)];if(prefixFormatter)return prefixFormatter}let dashIndex=scope.indexOf("-");if(dashIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dashIndex)];if(prefixFormatter)return prefixFormatter}}function getActiveFormatter(scopes,theme2){for(let i=scopes.length-1;i>=0;i--){let scope=scopes[i];if(!scope)continue;let formatter=getScopeFormatter(scope,theme2);if(formatter)return formatter}return theme2.default}function isSpanOpenTagStart(html2,index){if(!html2.startsWith("<span",index))return!1;let nextChar=html2[index+5];return nextChar===">"||nextChar===" "||nextChar===" "||nextChar===`
123
+ `)}`)}if(existsSync("/bin/bash"))return getBashShellConfig("/bin/bash");let bashOnPath=findExecutableOnPath("bash");return bashOnPath?getBashShellConfig(bashOnPath):{shell:"sh",args:["-c"]}}var POWERSHELL_ARGS=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];function getPowerShellConfig(){if(process.platform!=="win32")throw new Error("The powershell tool is only available on Windows.");let shell=findExecutableOnPath("pwsh.exe")??findExecutableOnPath("powershell.exe");if(!shell)throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");return{shell,args:[...POWERSHELL_ARGS]}}function getShellEnv(){let binDir=getBinDir(),pathKey=Object.keys(process.env).find(key=>key.toLowerCase()==="path")??"PATH",currentPath=process.env[pathKey]??"",updatedPath=currentPath.split(delimiter).filter(Boolean).includes(binDir)?currentPath:[binDir,currentPath].filter(Boolean).join(delimiter),env2={...process.env,[pathKey]:updatedPath};return delete env2.DRAHT_POLYPHASE_DEPTH,delete env2.DRAHT_POLYPHASE_SCHEMA_FILE,delete env2.DRAHT_POLYPHASE_PERMISSION_BRIDGE,env2}function sanitizeBinaryOutput(str2){return str2.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,"")}var trackedDetachedChildPids=new Set;function trackDetachedChildPid(pid){trackedDetachedChildPids.add(pid)}function untrackDetachedChildPid(pid){trackedDetachedChildPids.delete(pid)}function killTrackedDetachedChildren(){for(let pid of trackedDetachedChildPids)killProcessTree(pid);trackedDetachedChildPids.clear()}function killProcessTree(pid){if(process.platform==="win32")try{spawn2(join6(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(pid)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}else try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}import*as fs3 from"node:fs";import*as path4 from"node:path";import{watch}from"node:fs";var FS_WATCH_RETRY_DELAY_MS=5e3;function closeWatcher(watcher){if(watcher)try{watcher.close()}catch{}}function watchWithErrorHandler(path5,listener,onError){try{let watcher=watch(path5,listener);return watcher.on("error",onError),watcher}catch{return onError(),null}}var import_core=__toESM(require_core(),1),import_bash=__toESM(require_bash(),1),import_c=__toESM(require_c(),1),import_cpp=__toESM(require_cpp(),1),import_csharp=__toESM(require_csharp(),1),import_dart=__toESM(require_dart(),1),import_go=__toESM(require_go(),1),import_groovy=__toESM(require_groovy(),1),import_java=__toESM(require_java(),1),import_javascript=__toESM(require_javascript(),1),import_json=__toESM(require_json(),1),import_kotlin=__toESM(require_kotlin(),1),import_lua=__toESM(require_lua(),1),import_nix=__toESM(require_nix(),1),import_perl=__toESM(require_perl(),1),import_php=__toESM(require_php(),1),import_python=__toESM(require_python(),1),import_ruby=__toESM(require_ruby(),1),import_rust=__toESM(require_rust(),1),import_scala=__toESM(require_scala(),1),import_swift=__toESM(require_swift(),1),import_typescript=__toESM(require_typescript(),1);function decodeCodePoint(codePoint){if(!(!Number.isInteger(codePoint)||codePoint<0||codePoint>1114111))return String.fromCodePoint(codePoint)}function decodeHtmlEntity(entity){switch(entity){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'"}if(entity.startsWith("#x")||entity.startsWith("#X"))return decodeCodePoint(Number.parseInt(entity.slice(2),16));if(entity.startsWith("#"))return decodeCodePoint(Number.parseInt(entity.slice(1),10))}function decodeHtmlEntityAt(html2,index){let semicolonIndex=html2.indexOf(";",index+1);if(semicolonIndex===-1||semicolonIndex-index>16)return;let entity=html2.slice(index+1,semicolonIndex),decoded=decodeHtmlEntity(entity);if(decoded!==void 0)return{text:decoded,length:semicolonIndex-index+1}}var eagerLanguages={python:import_python.default,java:import_java.default,go:import_go.default,javascript:import_javascript.default,json:import_json.default,cpp:import_cpp.default,typescript:import_typescript.default,php:import_php.default,ruby:import_ruby.default,c:import_c.default,csharp:import_csharp.default,nix:import_nix.default,bash:import_bash.default,rust:import_rust.default,scala:import_scala.default,kotlin:import_kotlin.default,swift:import_swift.default,dart:import_dart.default,groovy:import_groovy.default,perl:import_perl.default,lua:import_lua.default};for(let[name,language]of Object.entries(eagerLanguages))import_core.default.registerLanguage(name,language);var allLanguagesPromise;function loadAllHighlightLanguages(){return allLanguagesPromise||(allLanguagesPromise=new Promise(resolve=>{setImmediate(()=>{import("./lib-ULKZYRGD.js").then(()=>resolve(),()=>{resolve()})})})),allLanguagesPromise}var SPAN_CLOSE="</span>",HIGHLIGHT_CLASS_PREFIX="hljs-";function getScopeFromSpanTag(tag2){let match=/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag2),classValue=match?.[1]??match?.[2];if(classValue){for(let className of classValue.split(/\s+/))if(className.startsWith(HIGHLIGHT_CLASS_PREFIX))return className.slice(HIGHLIGHT_CLASS_PREFIX.length)}}function getScopeFormatter(scope,theme2){let exact=theme2[scope];if(exact)return exact;let dotIndex=scope.indexOf(".");if(dotIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dotIndex)];if(prefixFormatter)return prefixFormatter}let dashIndex=scope.indexOf("-");if(dashIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dashIndex)];if(prefixFormatter)return prefixFormatter}}function getActiveFormatter(scopes,theme2){for(let i=scopes.length-1;i>=0;i--){let scope=scopes[i];if(!scope)continue;let formatter=getScopeFormatter(scope,theme2);if(formatter)return formatter}return theme2.default}function isSpanOpenTagStart(html2,index){if(!html2.startsWith("<span",index))return!1;let nextChar=html2[index+5];return nextChar===">"||nextChar===" "||nextChar===" "||nextChar===`
124
124
  `||nextChar==="\r"}function renderHighlightedHtml(html2,theme2={}){let output="",textBuffer="",scopes=[],flushText=()=>{if(!textBuffer)return;let formatter=getActiveFormatter(scopes,theme2);output+=formatter?formatter(textBuffer):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}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(okhslOf):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(okhslOf(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 anchored(source,family,lightness,saturation){let anchor=saturationCurve(family,source.l),falloff=anchor>0?Math.min(1,saturationCurve(family,lightness)/anchor):1;return okhslColor(source.h,source.s*falloff*saturation,lightness)}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}}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 withThemeColorFallbacks(colors){return{...colors,scrollbarTrack:colors.scrollbarTrack??colors.muted,scrollbarThumb:colors.scrollbarThumb??colors.text,thinkingMax:colors.thinkingMax??colors.thinkingXhigh,searchMatchBg:colors.searchMatchBg??colors.selectedBg,searchMatchText:colors.searchMatchText??colors.text}}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 foregrounds={...fgColors,scrollbarTrack:fgColors.scrollbarTrack??fgColors.muted,scrollbarThumb:fgColors.scrollbarThumb??fgColors.text,thinkingMax:fgColors.thinkingMax??fgColors.thinkingXhigh,searchMatchText:fgColors.searchMatchText??fgColors.text},backgrounds={...bgColors,searchMatchBg:bgColors.searchMatchBg??bgColors.selectedBg},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)}var BACKGROUND_TOKENS=new Set(["selectedBg","searchMatchBg","userMessageBg","customMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg"]);function splitThemeColors(colors){let fgColors={},bgColors={};for(let[key,value]of Object.entries(colors))BACKGROUND_TOKENS.has(key)?bgColors[key]=value:fgColors[key]=value;return{fgColors,bgColors}}function createTheme(themeJson,mode,sourcePath){let colorMode=mode??getTerminalColorMode(),resolvedColors=resolveThemeColors(withThemeColorFallbacks(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(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(env2=process.env){let bg=env2.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,env2=process.env){let{background,foreground}=colors;return background?terminalAppearance(background,foreground):reportedScheme??detectColorFgBgTheme(env2)??"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 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),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(`
125
125
  `).map(line=>theme.fg("mdCodeBlock",line));let opts={language:validLang,ignoreIllegals:!0,theme:getCliHighlightTheme(theme)};try{return highlight(code,opts).split(`
126
126
  `)}catch{return code.split(`
@@ -134,4 +134,4 @@ ${imageIndicators}`:imageIndicators}return output}var COLLAPSED_ARGS_CHARS=100;f
134
134
  `).join(`
135
135
  `)}`});return`${header}
136
136
  ${theme2.fg("muted",lines.join(`
137
- `))}`}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 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","...")}export{Marked,fuzzyMatch,fuzzyFilter,visibleWidth,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,Key,matchesKey,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,hyperlink,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,Text,Loader,CancellableLoader,SelectList,Editor,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,source_default,getShellConfig,getPowerShellConfig,getShellEnv,sanitizeBinaryOutput,trackDetachedChildPid,untrackDetachedChildPid,killTrackedDetachedChildren,killProcessTree,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguages,SYSTEM_THEME_NAME,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,combinedKeyHint,keyDisplayText,keyHint,rawKeyHint,stripAnsi,shortenPath,str,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,invalidArgText,renderToolPath,truncateToVisualLines,VisualLinePreview};
137
+ `))}`}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 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","...")}export{Marked,fuzzyMatch,fuzzyFilter,visibleWidth,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,Key,isKeyRelease,isKeyRepeat,matchesKey,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,hyperlink,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,Text,Loader,CancellableLoader,SelectList,Editor,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,source_default,getShellConfig,getPowerShellConfig,getShellEnv,sanitizeBinaryOutput,trackDetachedChildPid,untrackDetachedChildPid,killTrackedDetachedChildren,killProcessTree,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguages,SYSTEM_THEME_NAME,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,combinedKeyHint,keyDisplayText,keyHint,rawKeyHint,stripAnsi,shortenPath,str,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,invalidArgText,renderToolPath,truncateToVisualLines,VisualLinePreview};