@humain/humain-code 0.4.5 → 0.4.7

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 (79) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/bun/sandbox-env-setup.js +8 -0
  3. package/dist/bun/sandbox-env-setup.js.map +1 -1
  4. package/dist/bundle/agent-monitor.js +1 -1
  5. package/dist/bundle/chunks/{anthropic-messages-OHNAMPAM.js → anthropic-messages-YMPB2HJ7.js} +14 -13
  6. package/dist/bundle/chunks/{azure-openai-responses-FREWTLSS.js → azure-openai-responses-PDHOT7UC.js} +2 -2
  7. package/dist/bundle/chunks/bedrock-converse-stream.js +62 -57
  8. package/dist/bundle/chunks/{chunk-UTMYL2YO.js → chunk-2W5PWUPO.js} +10 -10
  9. package/dist/bundle/chunks/{chunk-DUZY4PDA.js → chunk-3E4SMILM.js} +33 -29
  10. package/dist/bundle/chunks/{chunk-344UX7X3.js → chunk-3TYF6GG6.js} +305 -307
  11. package/dist/bundle/chunks/{chunk-DECZQGMF.js → chunk-DAJJK7AP.js} +499 -480
  12. package/dist/bundle/chunks/{chunk-JQZ7BIAI.js → chunk-F7UMX5BV.js} +25 -22
  13. package/dist/bundle/chunks/{chunk-E7WGCXWK.js → chunk-GUUAEK6G.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-4X774RBJ.js → chunk-GVVRXZHN.js} +4 -4
  15. package/dist/bundle/chunks/{chunk-H5CZL7M5.js → chunk-KRMTBTWU.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-ICLZNV4V.js → chunk-LQ4S7CRR.js} +79 -67
  17. package/dist/bundle/chunks/{chunk-KLIRQQH5.js → chunk-OTXURGIO.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-OXJXKCLB.js → chunk-PMISFIBM.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-LFXFQLII.js → chunk-ROSZII6E.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-E22S6D55.js → chunk-SWRU4BOC.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-VQTXF23B.js → chunk-TIAXGIMN.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-3ZI2TEVB.js → chunk-UZ5FVVCP.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-5NOJN3CK.js → chunk-XRMWWXLF.js} +3 -3
  24. package/dist/bundle/chunks/{chunk-2NX3BVH6.js → chunk-Z5LYSSTY.js} +2 -2
  25. package/dist/bundle/chunks/{cli-5YRA5PFB.js → cli-ZKT34WPW.js} +2 -2
  26. package/dist/bundle/chunks/{compat-BFDCEZSB.js → compat-VPRCBNVL.js} +8 -8
  27. package/dist/bundle/chunks/{dist-NO7WH7BY.js → dist-4KCNJLEA.js} +262 -245
  28. package/dist/bundle/chunks/{dist-QHFJK4TH.js → dist-N7XDUAAO.js} +4 -4
  29. package/dist/bundle/chunks/{easter-egg-3d-ARXMB2RN.js → easter-egg-3d-5KKDWEIA.js} +1 -1
  30. package/dist/bundle/chunks/{execute-MFIDTEMB.js → execute-OSBDNQU5.js} +1 -1
  31. package/dist/bundle/chunks/{extract-EWN2GRAC.js → extract-56PXVZVW.js} +2 -2
  32. package/dist/bundle/chunks/{host-3OGMFGBY.js → host-2ARI7PQ5.js} +1 -1
  33. package/dist/bundle/chunks/mistral-conversations-XA2ZGSAH.js +43 -0
  34. package/dist/bundle/chunks/{openai-codex-responses-5AJAJHTK.js → openai-codex-responses-Y6NRWMOI.js} +2 -2
  35. package/dist/bundle/chunks/{openai-completions-65RRYKEQ.js → openai-completions-FY77MIZH.js} +6 -6
  36. package/dist/bundle/chunks/{openai-responses-72W3PGZ7.js → openai-responses-LNSCERKH.js} +2 -2
  37. package/dist/bundle/chunks/{pi-messages-RLLYRBDT.js → pi-messages-LYJZPRST.js} +7 -6
  38. package/dist/bundle/chunks/{runtime-HBWXEJT3.js → runtime-JFLZUNYP.js} +1 -1
  39. package/dist/bundle/chunks/{virtual-modules-LSFLJEDU.js → virtual-modules-F76HZAGG.js} +2 -2
  40. package/dist/bundle/cli-runtime.js +2 -2
  41. package/dist/bundle/flow/assets/profiles/anthropic.json +3 -3
  42. package/dist/bundle/flow/assets/profiles/openai.json +3 -3
  43. package/dist/bundle/flow/assets/profiles/oss-first.json +3 -3
  44. package/dist/bundle/flow/assets/profiles/premium.json +3 -3
  45. package/dist/bundle/flow/package.json +1 -1
  46. package/dist/bundle/index.js +5 -5
  47. package/dist/bundle/rpc-entry.js +2 -2
  48. package/dist/core/tools/renderers/write.d.ts +2 -2
  49. package/dist/core/tools/renderers/write.d.ts.map +1 -1
  50. package/dist/core/tools/renderers/write.js +120 -15
  51. package/dist/core/tools/renderers/write.js.map +1 -1
  52. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +27 -28
  53. package/dist/humain/flow-loader.d.ts.map +1 -1
  54. package/dist/humain/flow-loader.js +30 -2
  55. package/dist/humain/flow-loader.js.map +1 -1
  56. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  57. package/dist/modes/interactive/components/assistant-message.js +2 -0
  58. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  59. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  60. package/dist/modes/interactive/components/mermaid.js +4 -0
  61. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  62. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  63. package/dist/modes/interactive/components/tool-execution.js +4 -0
  64. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  65. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  66. package/dist/modes/interactive/interactive-mode.js +5 -0
  67. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  68. package/dist/utils/child-process.d.ts +8 -0
  69. package/dist/utils/child-process.d.ts.map +1 -1
  70. package/dist/utils/child-process.js +65 -4
  71. package/dist/utils/child-process.js.map +1 -1
  72. package/dist/utils/windows-path.d.ts +9 -0
  73. package/dist/utils/windows-path.d.ts.map +1 -0
  74. package/dist/utils/windows-path.js +31 -0
  75. package/dist/utils/windows-path.js.map +1 -0
  76. package/docs/tui.md +1 -1
  77. package/npm-shrinkwrap.json +6 -6
  78. package/package.json +2 -2
  79. package/dist/bundle/chunks/mistral-conversations-5HCMHK6E.js +0 -43
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{require_core}from"./chunk-SCIGZFN5.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-DUZY4PDA.js";import{__export,__toESM}from"./chunk-JXWJOIH4.js";var ambiguousRanges=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,
2
+ import{require_core}from"./chunk-SCIGZFN5.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-3E4SMILM.js";import{__export,__toESM}from"./chunk-JXWJOIH4.js";var ambiguousRanges=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,
3
3
  1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,
4
4
  8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,
5
5
  9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],fullwidthMinimalCodePoint=12288,fullwidthMaximumCodePoint=65510,fullwidthRanges=[12288,12288,65281,65376,65504,65510];var wideMinimalCodePoint=4352,wideMaximumCodePoint=262141,wideRanges=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,
@@ -130,9 +130,9 @@ keybindings]}))}setUserBindings(userBindings){this.userBindings=userBindings,thi
130
130
  TUI_KEYBINDINGS)),globalKeybindings}var dist_exports={};__export(dist_exports,{Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,Image:()=>Image,Input:()=>Input,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,Markdown:()=>Markdown,Marked:()=>F,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,
131
131
  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,
132
132
  decodeKittyPrintable:()=>decodeKittyPrintable,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,foregroundAnsi:()=>foregroundAnsi,formatProgramStatus:()=>formatProgramStatus,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getImageDimensions:()=>getImageDimensions,
133
- getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,indexedColor:()=>indexedColor,isAppleTerminalSession:()=>isAppleTerminalSession,isFocusable:()=>isFocusable,isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,
134
- 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,
135
- setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function I(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var P=I();function W(l3){P=l3}var A={exec:()=>null};function C(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l3(n),e[n]=s),s}}function h(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(s,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(x.caret,"$1"),t=t.replace(s,o),n},getRegex:()=>new RegExp(t,e)};return n}
133
+ getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,indexedColor:()=>indexedColor,invalidateRenderedMarkdown:()=>invalidateRenderedMarkdown,isAppleTerminalSession:()=>isAppleTerminalSession,isFocusable:()=>isFocusable,
134
+ 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,
135
+ rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function I(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var P=I();function W(l3){P=l3}var A={exec:()=>null};function C(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l3(n),e[n]=s),s}}function h(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(s,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(x.caret,"$1"),t=t.replace(s,o),n},getRegex:()=>new RegExp(t,e)};return n}
136
136
  var _e=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),x={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,
137
137
  blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,
138
138
  endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,
@@ -302,7 +302,7 @@ return!this.fdPath||signal.aborted?[]:await walkDirectoryWithFd(baseDir,this.fdP
302
302
  signal),seenPaths=new Set(baseDirEntries.map(entry=>entry.path)),entries=[...baseDirEntries,...recursiveEntries.filter(entry=>seenPaths.has(entry.path)?!1:(seenPaths.add(entry.path),!0))];if(options.signal.aborted)return[];let scoredEntries=entries.map(entry=>({...entry,score:fdQuery?this.scoreEntry(entry.path,fdQuery,entry.isDirectory):1})).filter(entry=>entry.score>0);scoredEntries.sort((a,b)=>{let scoreDiff=b.score-a.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(a.path).split(
303
303
  "/").filter(Boolean).length,bDepth=toDisplayPath(b.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a.path.length-b.path.length;return lengthDiff!==0?lengthDiff:a.path.localeCompare(b.path)});let topEntries=scoredEntries.slice(0,20),suggestions=[];for(let{path:entryPath,isDirectory}of topEntries){let pathWithoutSlash=isDirectory?entryPath.slice(0,-1):entryPath,displayPath=scopedQuery?this.scopedPathForDisplay(scopedQuery.displayBase,
304
304
  pathWithoutSlash):pathWithoutSlash,entryName=basename(pathWithoutSlash),completionPath=isDirectory?`${displayPath}/`:displayPath,value=buildCompletionValue(completionPath,{isDirectory,isAtPrefix:!0,isQuotedPrefix:options.isQuotedPrefix});suggestions.push({value,label:entryName+(isDirectory?"/":""),description:displayPath})}return suggestions}catch{return[]}}shouldTriggerFileCompletion(lines,cursorLine,cursorCol){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol);return!(textBeforeCursor.
305
- trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};import{performance as performance2}from"node:perf_hooks";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)+$/;
305
+ trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};import{performance as performance2}from"node:perf_hooks";var generation=0;function renderedMarkdownGeneration(){return generation}function invalidateRenderedMarkdown(){generation++}function hexToRgb(hex){let normalized=hex.startsWith("#")?hex.slice(1):hex,r=parseInt(normalized.slice(0,2),16),g=parseInt(normalized.slice(2,4),16),b=parseInt(normalized.slice(4,6),16);return{r,g,b}}function parseOscHexChannel(channel){if(!/^[0-9a-f]+$/i.test(channel))return;let max=16**channel.length-1;if(!(max<=0))return Math.round(parseInt(channel,16)/max*255)}var OSC_COLOR_RESPONSE_PATTERN=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,COLOR_SCHEME_REPORT_PATTERN=/^(?:\x1b\[\?997;(1|2)n)+$/;
306
306
  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.
307
307
  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)
308
308
  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",
@@ -357,14 +357,14 @@ fallbackTarget)}this.requestRender()}},isFocused:()=>this.focusedComponent===com
357
357
  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.
358
358
  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,
359
359
  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||
360
- 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(),
361
- 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,
362
- this.stopped||this.terminal.write(enabled?"\x1B[?2031h":"\x1B[?2031l"))}queryCellSize(){getCapabilities().images&&this.terminal.write("\x1B[16t")}stop(options={}){this.stopped=!0,this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(options),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(options)}renderNow(force=!1){force&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.
363
- 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.
364
- 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.
365
- 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+ct\
366
- rl+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.
367
- 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){
360
+ overlay.focusOrder>topmost.focusOrder)&&(topmost=overlay);return topmost}invalidate(){invalidateRenderedMarkdown();for(let root of this.getMountedRoots())root.invalidate();for(let overlay of this.overlayStack)overlay.component.invalidate()}start(){this.stopped=!1,this.beforeTerminalStart(),this.terminal.start(data=>this.handleTerminalInput(data),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?203\
361
+ 1h"),this.queryCellSize(),this.requestRender()}addInputListener(listener){return this.inputListeners.add(listener),()=>{this.inputListeners.delete(listener)}}removeInputListener(listener){this.inputListeners.delete(listener)}onTerminalColorSchemeChange(listener){return this.terminalColorSchemeListeners.add(listener),()=>{this.terminalColorSchemeListeners.delete(listener)}}setTerminalColorSchemeNotifications(enabled){this.terminalColorSchemeNotificationsEnabled!==enabled&&(this.terminalColorSchemeNotificationsEnabled=
362
+ enabled,this.stopped||this.terminal.write(enabled?"\x1B[?2031h":"\x1B[?2031l"))}queryCellSize(){getCapabilities().images&&this.terminal.write("\x1B[16t")}stop(options={}){this.stopped=!0,this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(options),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(options)}renderNow(force=!1){force&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),
363
+ 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(),
364
+ 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=
365
+ 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,
366
+ "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();
367
+ 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){
368
368
  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.
369
369
  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(
370
370
  data);if(!scheme)return!1;for(let listener of this.terminalColorSchemeListeners)listener(scheme);return!0}consumeCellSizeResponse(data){let match=data.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!match)return!1;let heightPx=parseInt(match[1],10),widthPx=parseInt(match[2],10);return heightPx<=0||widthPx<=0||(setCellDimensions({widthPx,heightPx}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(options,overlayHeight,termWidth,termHeight){let opt=options??{},margin=typeof opt.margin=="number"?
@@ -607,14 +607,21 @@ exec(source2);if(pendingBracket)return{type:"latexBlock",raw:pendingBracket[0],t
607
607
  `
608
608
  `)?1:0):void 0},tokenizer:tokenizeBlockLatex},{name:"latex",level:"inline",start(source2){let indices=[source2.indexOf("$"),source2.indexOf("\\("),source2.indexOf("\\[")].filter(index=>index>=0);return indices.length>0?Math.min(...indices):void 0},tokenizer:tokenizeInlineLatex}];function trimPartialClosingFences(tokens){let token=tokens[tokens.length-1];if(token?.type==="list"){trimPartialClosingFences(token.items[token.items.length-1]?.tokens??[]);return}if(token?.type==="blockquote"){trimPartialClosingFences(
609
609
  token.tokens??[]);return}if(token?.type!=="code")return;let marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1],lastLine=token.raw.split(`
610
- `).pop();!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)||(token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,""))}var markdownParser=new F;markdownParser.setOptions({tokenizer:new StrictStrikethroughTokenizer});markdownParser.use({extensions:[...LATEX_MARKDOWN_EXTENSIONS]});var Markdown=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;cachedTokens;constructor(text,paddingX,paddingY,theme2,defaultTextStyle,options){
611
- this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.theme=theme2,this.defaultTextStyle=defaultTextStyle,this.options=options?{...options}:{}}setText(text){this.text=text,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;let contentWidth=Math.max(1,width-this.paddingX*2),text=this.options.transform?.(this.text,contentWidth)??
612
- this.text;if(!text||text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=text.replace(/\t/g," "),cached=this.cachedTokens?.deref(),tokens=cached?.source===normalizedText?cached.tokens:void 0;tokens||(tokens=markdownParser.lexer(normalizedText),trimPartialClosingFences(tokens),this.cachedTokens=new WeakRef({source:normalizedText,tokens}));let renderedLines=[];for(let i=0;i<tokens.length;i++){let token=tokens[i],
613
- nextToken=tokens[i+1],tokenLines=this.renderToken(token,contentWidth,nextToken?.type);for(let tokenLine of tokenLines)renderedLines.push(tokenLine)}let wrappedLines=[];for(let line of renderedLines)if(isImageLine(line))wrappedLines.push(line);else for(let wrappedLine of wrapTextWithAnsi(line,contentWidth))wrappedLines.push(wrappedLine);let leftMargin=" ".repeat(this.paddingX),rightMargin=" ".repeat(this.paddingX),bgFn=this.defaultTextStyle?.bgColor,contentLines=[];for(let line of wrappedLines){if(isImageLine(
614
- line)){contentLines.push(line);continue}let lineWithMargins=leftMargin+line+rightMargin;if(bgFn)contentLines.push(applyBackgroundToLine(lineWithMargins,width,bgFn));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=bgFn?applyBackgroundToLine(emptyLine,width,bgFn):emptyLine;emptyLines.push(line)}let result=emptyLines.
615
- concat(contentLines,emptyLines);return flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}applyDefaultStyle(text){if(!this.defaultTextStyle)return text;let styled=text;return this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.
616
- strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled)),styled}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let sentinel="\0",styled=sentinel;this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=
617
- this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled));let sentinelIndex=styled.indexOf(sentinel);return this.defaultStylePrefix=sentinelIndex>=0?styled.slice(0,sentinelIndex):"",this.defaultStylePrefix}getStylePrefix(styleFn){let styled=styleFn("\0"),sentinelIndex=styled.indexOf("\0");return sentinelIndex>=0?styled.slice(0,sentinelIndex):""}getDefaultInlineStyleContext(){return{applyText:text=>this.applyDefaultStyle(text),stylePrefix:this.getDefaultStylePrefix()}}renderToken(token,width,nextTokenType,styleContext){
610
+ `).pop();!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)||(token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,""))}var markdownParser=new F;markdownParser.setOptions({tokenizer:new StrictStrikethroughTokenizer});markdownParser.use({extensions:[...LATEX_MARKDOWN_EXTENSIONS]});var lexedMarkdown=[],LEXED_MARKDOWN_KEPT=8;function hasLinkDefinitions(tokens){let links=tokens.links;return links!==void 0&&Object.keys(links).length>0}function lexAddedMarkdown(previous,source2){
611
+ let last=previous.tokens.length;for(let blocks=0;blocks<2;blocks++)for(last--;last>=0&&previous.tokens[last].type==="space";)last--;if(last<=0)return;let offset=0;for(let i=0;i<last;i++)offset+=previous.tokens[i].raw.length;let added=markdownParser.lexer(JSON.parse(JSON.stringify(source2.slice(offset))));if(hasLinkDefinitions(added))return;let tokens=previous.tokens.slice(0,last),length=offset;for(let token of added)tokens.push(token),length+=token.raw.length;return length===source2.length?tokens:
612
+ void 0}function lexMarkdown(source2,complete=!0){if(!markdownCaching){let tokens2=markdownParser.lexer(source2);return trimPartialClosingFences(tokens2),tokens2}let previous=-1;for(let i=lexedMarkdown.length-1;i>=0;i--){let entry=lexedMarkdown[i];if(entry.source===source2){if(lexedMarkdown.splice(i,1),complete&&entry.pieced)break;return lexedMarkdown.push(entry),entry.tokens}!complete&&entry.resumable&&source2.length>entry.source.length&&(previous<0||entry.source.length>lexedMarkdown[previous].source.
613
+ length)&&source2.startsWith(entry.source)&&(previous=i)}let tokens=previous>=0?lexAddedMarkdown(lexedMarkdown[previous],source2):void 0,pieced=tokens!==void 0,resumable=pieced;if(!tokens){tokens=markdownParser.lexer(source2);let length=0;for(let token of tokens)length+=token.raw.length;resumable=!hasLinkDefinitions(tokens)&&length===source2.length}return trimPartialClosingFences(tokens),previous>=0&&lexedMarkdown.splice(previous,1),lexedMarkdown.push({source:source2,tokens,resumable,pieced}),lexedMarkdown.
614
+ length>LEXED_MARKDOWN_KEPT&&lexedMarkdown.shift(),tokens}var textsWithoutTabs=[],TEXTS_WITHOUT_TABS_KEPT=4;function replaceTabs(text){if(!text.includes(" "))return text;if(!markdownCaching)return text.replace(/\t/g," ");let replaced;for(let i=textsWithoutTabs.length-1;i>=0&&replaced===void 0;i--){let entry=textsWithoutTabs[i];text.length>=entry.text.length&&text.startsWith(entry.text)&&(replaced=text.length===entry.text.length?entry.replaced:entry.replaced+text.slice(entry.text.length).replace(
615
+ /\t/g," "),textsWithoutTabs.splice(i,1))}return replaced??=text.replace(/\t/g," "),textsWithoutTabs.push({text,replaced}),textsWithoutTabs.length>TEXTS_WITHOUT_TABS_KEPT&&textsWithoutTabs.shift(),replaced}var renderedBlocks=new WeakMap,markdownCaching=!0;var Markdown=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;cachedTokens;constructor(text,paddingX,paddingY,theme2,defaultTextStyle,options){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.theme=theme2,this.defaultTextStyle=defaultTextStyle,this.options=options?{...options}:{}}setText(text){this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedText=void 0,this.
616
+ cachedWidth=void 0,this.cachedLines=void 0,invalidateRenderedMarkdown()}renderBlock(token,nextTokenType,width,contentWidth){let style=this.defaultTextStyle,capabilities=getCapabilities(),known=markdownCaching?renderedBlocks.get(token):void 0;if(known&&known.generation===renderedMarkdownGeneration()&&known.width===width&&known.paddingX===this.paddingX&&known.nextTokenType===nextTokenType&&known.theme===this.theme&&known.color===style?.color&&known.bgColor===style?.bgColor&&known.bold===style?.bold&&
617
+ known.italic===style?.italic&&known.strikethrough===style?.strikethrough&&known.underline===style?.underline&&known.preserveOrderedListMarkers===this.options.preserveOrderedListMarkers&&known.preserveBackslashEscapes===this.options.preserveBackslashEscapes&&known.renderLatex===this.options.renderLatex&&known.capabilities===capabilities)return known.lines;let leftMargin=" ".repeat(this.paddingX),rightMargin=" ".repeat(this.paddingX),bgFn=style?.bgColor,lines=[],add=line=>{if(isImageLine(line)){lines.
618
+ push(line);return}let lineWithMargins=leftMargin+line+rightMargin;if(bgFn)lines.push(applyBackgroundToLine(lineWithMargins,width,bgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);lines.push(lineWithMargins+" ".repeat(paddingNeeded))}};for(let line of this.renderToken(token,contentWidth,nextTokenType))if(isImageLine(line))add(line);else for(let wrappedLine of wrapTextWithAnsi(line,contentWidth))add(wrappedLine);return flattenLines(lines),markdownCaching&&
619
+ renderedBlocks.set(token,{generation:renderedMarkdownGeneration(),width,paddingX:this.paddingX,nextTokenType,theme:this.theme,color:style?.color,bgColor:style?.bgColor,bold:style?.bold,italic:style?.italic,strikethrough:style?.strikethrough,underline:style?.underline,preserveOrderedListMarkers:this.options.preserveOrderedListMarkers,preserveBackslashEscapes:this.options.preserveBackslashEscapes,renderLatex:this.options.renderLatex,capabilities,lines}),lines}render(width){if(this.cachedLines&&this.
620
+ cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;let contentWidth=Math.max(1,width-this.paddingX*2),text=this.options.transform?.(this.text,contentWidth)??this.text;if(!text||!/\S/.test(text)){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=replaceTabs(text),cached=this.cachedTokens?.deref(),tokens=cached?.source===normalizedText?cached.tokens:void 0;tokens||(tokens=lexMarkdown(normalizedText,this.
621
+ options.complete),this.cachedTokens=new WeakRef({source:normalizedText,tokens}));let bgFn=this.defaultTextStyle?.bgColor,contentLines=[];for(let i=0;i<tokens.length;i++)for(let line of this.renderBlock(tokens[i],tokens[i+1]?.type,width,contentWidth))contentLines.push(line);let emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=bgFn?applyBackgroundToLine(emptyLine,width,bgFn):emptyLine;emptyLines.push(line)}flattenLines(emptyLines);let result=emptyLines.concat(contentLines,
622
+ emptyLines);return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}applyDefaultStyle(text){if(!this.defaultTextStyle)return text;let styled=text;return this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.
623
+ underline&&(styled=this.theme.underline(styled)),styled}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let sentinel="\0",styled=sentinel;this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.
624
+ defaultTextStyle.underline&&(styled=this.theme.underline(styled));let sentinelIndex=styled.indexOf(sentinel);return this.defaultStylePrefix=sentinelIndex>=0?styled.slice(0,sentinelIndex):"",this.defaultStylePrefix}getStylePrefix(styleFn){let styled=styleFn("\0"),sentinelIndex=styled.indexOf("\0");return sentinelIndex>=0?styled.slice(0,sentinelIndex):""}getDefaultInlineStyleContext(){return{applyText:text=>this.applyDefaultStyle(text),stylePrefix:this.getDefaultStylePrefix()}}renderToken(token,width,nextTokenType,styleContext){
618
625
  let lines=[];switch(token.type){case"heading":{let headingLevel=token.depth,headingPrefix=`${"#".repeat(headingLevel)} `,headingStyleFn;headingLevel===1?headingStyleFn=text=>this.theme.heading(this.theme.bold(this.theme.underline(text))):headingStyleFn=text=>this.theme.heading(this.theme.bold(text));let headingStyleContext={applyText:headingStyleFn,stylePrefix:this.getStylePrefix(headingStyleFn)},headingText=this.renderInlineTokens(token.tokens||[],headingStyleContext),styledHeading=headingLevel>=
619
626
  3?headingStyleFn(headingPrefix)+headingText:headingText;lines.push(styledHeading),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"paragraph":{let paragraphText=this.renderInlineTokens(token.tokens||[],styleContext);lines.push(paragraphText),nextTokenType&&nextTokenType!=="list"&&nextTokenType!=="space"&&lines.push("");break}case"text":lines.push(this.renderInlineTokens([token],styleContext));break;case"latexBlock":{let latexToken=token,rendered=!latexToken.pending&&this.options.
620
627
  renderLatex!==!1?renderLatex(latexToken.text,{display:!0})??latexToken.raw.trim():latexToken.raw.trim();for(let line of rendered.split(`
@@ -734,8 +741,8 @@ rootBox=layoutComponent(context,root,0,0,safeWidth,safeHeight,{x:0,y:0,width:saf
734
741
  if(containsPoint(box.clip,x2,y2)){result.push({box,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b)=>b.box.layer-a.box.layer||b.depth-a.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y2){let result=[],visit=(box,depth)=>{
735
742
  if(containsPoint(box.clip,x2,y2)){box.scrollView&&containsPoint(box.rect,x2,y2)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b)=>b.depth-a.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env2=process.env;return process.platform==="darwin"&&env2.SSH_CONNECTION===void 0&&env2.SSH_CLIENT===void 0&&env2.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.
736
743
  isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let gap=now-this.lastTime,sameGesture=direction===this.lastDirection&&gap<=200;if(this.lastTime=now,this.lastDirection=direction,!sameGesture)return this.averageGap=void 0,this.carry=0,1;if(gap<5)return 1;this.averageGap=this.averageGap===void 0?gap:(this.averageGap+gap)/2;let lines=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,whole=Math.floor(lines);return this.carry=lines-whole,whole}reset(){this.lastTime=
737
- Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var ENTER_ALT_SCREEN="\x1B[?1049h",EXIT_ALT_SCREEN="\x1B[?1049l",DISABLE_AUTOWRAP="\x1B[?7l",ENABLE_AUTOWRAP="\x1B[?7h",ENABLE_BUTTON_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",ENABLE_ALL_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",DISABLE_MOUSE="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",FOCUS_IN="\x1B[I",FOCUS_OUT="\x1B[O",BEGIN_SYNCHRONIZED_OUTPUT="\x1B[?2026h",END_SYNCHRONIZED_OUTPUT="\x1B[?2026l",OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,
738
- OSC133_PROMPT_START=/^\x1b\]133;A(?:\x07|\x1b\\)/,PAGE_SCROLL_OVERLAP=4,ALT_WHEEL_SCROLL_MULTIPLIER=5,MAX_CACHED_OFFSCREEN_KITTY_IMAGES=16,MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES=32*1024*1024,MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES=64*1024*1024,DOUBLE_CLICK_INTERVAL_MS=500,COPY_ERROR_FLASH_DURATION_MS=5e3,TERMINAL_WORD_SELECTION_JOINERS=new Set(["/","-"]),wordSegmenter4=getWordSegmenter(),TuiAltScreen=class extends TuiBase{mode="fullscreen";[VIEWPORT_TUI]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="\
744
+ Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var ENTER_ALT_SCREEN="\x1B[?1049h",EXIT_ALT_SCREEN="\x1B[?1049l",DISABLE_AUTOWRAP="\x1B[?7l",ENABLE_AUTOWRAP="\x1B[?7h",ENABLE_BUTTON_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",ENABLE_ALL_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",DISABLE_MOUSE="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",FOCUS_IN="\x1B[I",FOCUS_OUT="\x1B[O",BEGIN_SYNCHRONIZED_OUTPUT="\x1B[?2026h",END_SYNCHRONIZED_OUTPUT="\x1B[?2026l",MIN_ROWS_SAVED_BY_SCROLLING=3,OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,
745
+ OSC133_PROMPT_START=/^\x1b\]133;A(?:\x07|\x1b\\)/,PAGE_SCROLL_OVERLAP=4,ALT_WHEEL_SCROLL_MULTIPLIER=5,MAX_CACHED_OFFSCREEN_KITTY_IMAGES=16,MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES=32*1024*1024,MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES=64*1024*1024,DOUBLE_CLICK_INTERVAL_MS=500,COPY_ERROR_FLASH_DURATION_MS=5e3,TERMINAL_WORD_SELECTION_JOINERS=new Set(["/","-"]),wordSegmenter4=getWordSegmenter(),TuiAltScreen=class extends TuiBase{mode="fullscreen";[VIEWPORT_TUI]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;finishedRows=new Map;finishedRowsWidth=0;imageRows=new Set;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="\
739
746
  character";selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScroll;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(terminal,showHardwareCursor,logDirectory,options={}){
740
747
  super(terminal,showHardwareCursor,logDirectory),this.implicitDocument={render:width=>super.render(width),handleMouse:event=>super.handleMouse(event),invalidate:()=>{for(let child of this.children)child.invalidate()}},this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(options.wheelScrollLines??1),this.mouseEnabled=options.mouse??!0,this.searchMatchStyle=
741
748
  options.searchMatchStyle??(text=>`\x1B[4m${text}\x1B[24m`),this.searchCurrentMatchStyle=options.searchCurrentMatchStyle??(text=>`\x1B[1;7m${text}\x1B[22;27m`),this.searchNavigationButtonStyle=options.searchNavigationButtonStyle??(text=>text),this.scrollToEndIndicator=options.scrollToEndIndicator,this.openUrl=options.openUrl,this.onRightClickPaste=options.onRightClickPaste,this.copyOnSelect=options.copyOnSelect??!0,this.copySelection=options.copySelection,this.addInputListener(data=>this.handleViewportInput(
@@ -750,43 +757,43 @@ for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
750
757
  \x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}deleteKittyImages(){return this.imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={
751
758
  transmissionGeneration:placement.transmissionGeneration,transmissionBytes:placement.transmissionBytes,estimatedDecodedBytes:placement.estimatedDecodedBytes};return cachedImage&&this.uploadedKittyImages.delete(placement.imageId),this.uploadedKittyImages.set(placement.imageId,nextCachedImage),cachedImage?.transmissionGeneration===placement.transmissionGeneration?placement.replacementLine:line}),cachedOffscreenImageCount=0,cachedOffscreenTransmissionBytes=0,cachedOffscreenDecodedBytes=0;for(let[imageId,
752
759
  cachedImage]of this.uploadedKittyImages)visibleImageIds.has(imageId)||(cachedOffscreenImageCount+=1,cachedOffscreenTransmissionBytes+=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes+=cachedImage.estimatedDecodedBytes);let evictedImageDeletion="";for(let[imageId,cachedImage]of this.uploadedKittyImages){if(cachedOffscreenImageCount<=MAX_CACHED_OFFSCREEN_KITTY_IMAGES&&cachedOffscreenTransmissionBytes<=MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES&&cachedOffscreenDecodedBytes<=MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES)
753
- break;visibleImageIds.has(imageId)||(evictedImageDeletion+=deleteKittyImage(imageId),this.uploadedKittyImages.delete(imageId),cachedOffscreenImageCount-=1,cachedOffscreenTransmissionBytes-=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes-=cachedImage.estimatedDecodedBytes)}return{lines,evictedImageDeletion}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(lines){this.getPrimaryScrollView().scrollBy(lines),
754
- this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(direction){if(!this.currentLayout)return;let scrollView=this.getPrimaryScrollView(),lines=getScrollViewBox(this.currentLayout,scrollView)?.scrollContentLines;if(lines){for(let row=scrollView.scrollTop+direction;row>=0&&row<lines.length;row+=direction)if(OSC133_PROMPT_START.test(lines[row]??"")){scrollView.
755
- scrollTo(row),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let component=new AltScreenSearchComponent(query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={component,index:new AltScreenSearchIndex,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=search,search.overlay=this.showOverlay(component,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){
756
- let search=this.activeSearch;search&&(this.activeSearch=void 0,search.overlay?.hide(),this.requestRender())}updateSearchQuery(query){let search=this.activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){let search=this.activeSearch;search?.
757
- query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x2,y2){let search=this.activeSearch,bounds=search?.overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y2<bounds.row||y2>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y2-bounds.row,x2-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.getSearchNavigationDirectionAt(
758
- event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==0||(event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.matches=[],search.selectedIndex=
759
- -1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",result=search.index.search(lines,search.query),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;if(matches.length>0)if(search.
760
- selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.row??0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=0?exactIndex:Math.
761
- min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;let selected=matches[selectedIndex],
762
- firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==before}flash(message,durationMs){this.
763
- flashes.flash(message,durationMs)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.
764
- stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),this.lastClick=void 0,{
765
- consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let lines=this.wheelScroll.next(wheelEvent.direction,performance.now()),wheelDelta=wheelEvent.direction*((wheelEvent.button&8)!==0?lines*ALT_WHEEL_SCROLL_MULTIPLIER:lines),event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));return result?
766
- (this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):this.shouldDeferViewportInputToOverlay()?void 0:(this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.toggleSearch(),{consume:!0};
767
- if(this.activeSearch?.overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(keybindings.matches(data,"tui.altScreen.pageUp"))return isRelease||this.scrollBy(
768
- -Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageDown"))return isRelease||
769
- this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.nextPrompt"))return isRelease||this.scrollToPrompt(
770
- 1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){switch(button&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(type,button,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.
771
- max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||getLayoutNode(box.component)&&box.component.
772
- handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result){let focusTarget=this.resolveMouseFocusTarget(result.focusTarget??result.target.component),focusChanged=result.focus===!0&&this.getFocusedComponent()!==focusTarget;return result.focus&&this.setFocus(focusTarget),
773
- result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x2&&previous.
774
- y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y:y2},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"release":isMotion?this.decodeMouseButton(raw.button)===
775
- "none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(event,targetResult)),raw.release){if(!this.mousePressMoved&&
776
- this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),clickResult=this.dispatchMouseToTarget(clickEvent,target);clickResult&&(render=this.applyMouseDispatchResult(clickEvent,clickResult)||render)}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.
777
- hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=result.target,this.mousePressPoint={x:raw.x,y:raw.y},
778
- this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(raw)}parseWheelEvent(data){let sgr=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(data);if(sgr){let button=Number.parseInt(sgr[1],10);if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:Number.parseInt(sgr[2],10)-1,y:Number.parseInt(sgr[3],10)-1,button}}if(data.length===6&&data.startsWith("\x1B[M")){let button=data.
779
- charCodeAt(3)-32;if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:data.charCodeAt(4)-33,y:data.charCodeAt(5)-33,button}}}routeWheel(event,delta){let remaining=delta,seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll==="contain")break;let primary=this.getPrimaryScrollView();
780
- remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){let match=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);if(match)return{button:Number.parseInt(match[1],10),x:Number.parseInt(match[2],10)-1,y:Number.parseInt(match[3],10)-1,release:match[4]==="m"}}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||
781
- event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;return!rect||event.release||(event.button&32)!==0||(event.button&3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x2,y2)){let box=getScrollViewBox(
782
- this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){
783
- this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?
784
- getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=
785
- void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(target.scrollView);let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,target.geometry,event.y,grabOffset),this.scrollbarDrag=
786
- {scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x2,y2){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)return;let pointerRow=Math.max(visibleTop,Math.
787
- min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.max(0,Math.min(this.terminal.columns-1,event.
788
- x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.scrollContentLines;if(lines)return lines[point.row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of wordSegmenter4.segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.has(segment.segment);
789
- segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.col>=segment.start&&point.col<segment.end);if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)
760
+ break;visibleImageIds.has(imageId)||(evictedImageDeletion+=deleteKittyImage(imageId),this.uploadedKittyImages.delete(imageId),cachedOffscreenImageCount-=1,cachedOffscreenTransmissionBytes-=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes-=cachedImage.estimatedDecodedBytes)}return{lines,evictedImageDeletion}}resetRenderState(){this.previousScreen=[],this.finishedRows=new Map,this.imageRows=new Set,this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(lines){
761
+ this.getPrimaryScrollView().scrollBy(lines),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(direction){if(!this.currentLayout)return;let scrollView=this.getPrimaryScrollView(),lines=getScrollViewBox(this.currentLayout,scrollView)?.scrollContentLines;if(lines){for(let row=scrollView.scrollTop+direction;row>=0&&row<lines.length;row+=direction)if(OSC133_PROMPT_START.
762
+ test(lines[row]??"")){scrollView.scrollTo(row),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let component=new AltScreenSearchComponent(query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={component,index:new AltScreenSearchIndex,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=search,search.overlay=this.showOverlay(component,{anchor:"top-right",width:"\
763
+ 40%",minWidth:32,margin:1})}closeSearch(){let search=this.activeSearch;search&&(this.activeSearch=void 0,search.overlay?.hide(),this.requestRender())}updateSearchQuery(query){let search=this.activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){
764
+ let search=this.activeSearch;search?.query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x2,y2){let search=this.activeSearch,bounds=search?.overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y2<bounds.row||y2>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y2-bounds.row,x2-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.
765
+ getSearchNavigationDirectionAt(event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==0||(event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.
766
+ matches=[],search.selectedIndex=-1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",result=search.index.search(lines,search.query),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;
767
+ if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.row??0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=
768
+ 0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;
769
+ let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==
770
+ before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.
771
+ selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),
772
+ this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let lines=this.wheelScroll.next(wheelEvent.direction,performance.now()),wheelDelta=wheelEvent.direction*((wheelEvent.button&8)!==0?lines*ALT_WHEEL_SCROLL_MULTIPLIER:lines),event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(
773
+ event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):this.shouldDeferViewportInputToOverlay()?void 0:(this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.
774
+ toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(keybindings.matches(data,"tui.altScreen.pageUp"))
775
+ return isRelease||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tu\
776
+ i.altScreen.halfPageDown"))return isRelease||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScre\
777
+ en.nextPrompt"))return isRelease||this.scrollToPrompt(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){switch(button&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(type,button,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(
778
+ button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||
779
+ getLayoutNode(box.component)&&box.component.handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result){let focusTarget=this.resolveMouseFocusTarget(result.focusTarget??result.target.component),focusChanged=result.focus===!0&&this.getFocusedComponent()!==focusTarget;
780
+ return result.focus&&this.setFocus(focusTarget),result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===
781
+ target.component&&previous.x===x2&&previous.y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y:y2},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"rel\
782
+ ease":isMotion?this.decodeMouseButton(raw.button)==="none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(
783
+ event,targetResult)),raw.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),clickResult=this.dispatchMouseToTarget(clickEvent,target);clickResult&&(render=this.applyMouseDispatchResult(clickEvent,clickResult)||render)}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))
784
+ return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=
785
+ result.target,this.mousePressPoint={x:raw.x,y:raw.y},this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(raw)}parseWheelEvent(data){let sgr=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(data);if(sgr){let button=Number.parseInt(sgr[1],10);if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:Number.parseInt(sgr[2],10)-1,y:Number.parseInt(sgr[3],10)-1,button}}if(data.
786
+ length===6&&data.startsWith("\x1B[M")){let button=data.charCodeAt(3)-32;if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:data.charCodeAt(4)-33,y:data.charCodeAt(5)-33,button}}}routeWheel(event,delta){let remaining=delta,seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll===
787
+ "contain")break;let primary=this.getPrimaryScrollView();remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){let match=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);if(match)return{button:Number.parseInt(match[1],10),x:Number.parseInt(match[2],10)-1,y:Number.parseInt(match[3],10)-1,release:match[4]==="m"}}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.
788
+ TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;return!rect||event.release||(event.button&32)!==0||(event.button&3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(
789
+ this.currentLayout,x2,y2)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(
790
+ this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.
791
+ release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=
792
+ !1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(target.scrollView);let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,
793
+ target.geometry,event.y,grabOffset),this.scrollbarDrag={scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x2,y2){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)
794
+ return;let pointerRow=Math.max(visibleTop,Math.min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.
795
+ max(0,Math.min(this.terminal.columns-1,event.x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.scrollContentLines;if(lines)return lines[point.row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of wordSegmenter4.segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.
796
+ has(segment.segment);segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.col>=segment.start&&point.col<segment.end);if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)
790
797
  selectionStart=segments[index-1].start;for(let index=clickedSegmentIndex;index<segments.length-1&&canJoin(segments[index],segments[index+1]);index++)selectionEnd=segments[index+1].end;return{start:{...point,col:selectionStart},end:{...point,col:selectionEnd,boundary:!0}}}getLineSelection(point){return{start:{...point,col:0},end:{...point,col:visibleWidth(this.getSelectionSourceLine(point)),boundary:!0}}}updateSelectionFocus(point){if(this.selectionGranularity==="character"||!this.selectionInitialRange){
791
798
  this.selectionFocus=point;return}let range=this.selectionGranularity==="word"?this.getWordSelection(point):this.getLineSelection(point);if(!range)return;let initial=this.selectionInitialRange;range.start.row<initial.start.row||range.start.row===initial.start.row&&range.start.col<initial.start.col?(this.selectionAnchor=initial.end,this.selectionFocus=range.start):(this.selectionAnchor=initial.start,this.selectionFocus=range.end)}getClickCount(point,word){let now=Date.now(),previous=this.lastClick,
792
799
  count=word&&previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.row===point.row&&previous.scrollView===point.scrollView&&previous.wordStart===word.start.col&&previous.wordEnd===word.end.col?previous.count%3+1:1;return this.lastClick=word?{timestamp:now,count,row:point.row,scrollView:point.scrollView,wordStart:word.start.col,wordEnd:word.end.col}:void 0,count}updateSelectionAutoScroll(event){let scrollView=this.selectionAnchor?.scrollView;if(!scrollView||!this.currentLayout){this.
@@ -813,14 +820,19 @@ rect.x+selection.start.col},end:{...selection.end,row:box.rect.y+selection.end.r
813
820
  !0),selected=sliceByColumn(line,columns.start,columns.end-columns.start,!0),after=sliceByColumn(line,columns.end,Math.max(0,lineWidth-columns.end),!0);return`${before}${this.applySelectionHighlight(selected)}${after}`})}isMouseSequence(data){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(data)||data.length===6&&data.startsWith("\x1B[M")}compositeScrollToEndIndicator(screen,layout,width){this.scrollToEndIndicatorRect=void 0;let scrollView=layout.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||
814
821
  !scrollView.followEnd||scrollView.isFollowingEnd)return screen;let box=getScrollViewBox(layout,scrollView),clip=box?.clip;if(!clip||clip.width<=0||clip.height<=0)return screen;let row=clip.y+clip.height-1;if(row>=screen.length||isImageLine(screen[row]??""))return screen;let scrollbarColumn=box?getScrollbarGeometry(box)?.column:void 0,label=truncateToWidth(this.scrollToEndIndicator(),clip.width,""),labelWidth=visibleWidth(label),column=clip.x+Math.floor((clip.width-labelWidth)/2),rightEdge=scrollbarColumn??
815
822
  clip.x+clip.width,availableWidth=Math.max(0,rightEdge-column),text=truncateToWidth(label,availableWidth,""),textWidth=visibleWidth(text);if(textWidth===0)return screen;let result=[...screen];return result[row]=compositeTuiLine(result[row]??"",text,column,textWidth,width),this.scrollToEndIndicatorRect={row,column,width:textWidth},result}compositeFlashes(screen,width,height){let flashLines=this.flashes.render(width).slice(-height);if(flashLines.length===0)return screen;let result=[...screen];for(;result.
816
- length<height;)result.push("");for(let row=0;row<flashLines.length;row++){let line=flashLines[row],flashWidth=visibleWidth(line);flashWidth!==0&&(result[row]=compositeTuiLine(result[row]??"",line,width-flashWidth,flashWidth,width))}return result}doRender(){if(this.stopped||!this.altScreenActive)return;let width=Math.max(1,this.terminal.columns),height=Math.max(1,this.terminal.rows),root=this.layoutRoot??this.implicitScrollView,nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender());
817
- this.refreshSearch(nextLayout)&&(nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender()));let screen=nextLayout.lines.map(line=>line.replace(OSC133_ZONE_PREFIX2,""));screen=this.applySearchHighlights(screen,nextLayout),screen=this.compositeScrollToEndIndicator(screen,nextLayout,width),screen=this.compositeOverlays(screen,width,height),screen.length>height&&(screen=screen.slice(screen.length-height)),screen=this.applySelection(screen,nextLayout),screen=this.compositeFlashes(screen,
818
- width,height);let cursorPos=this.extractCursorPosition(screen,height);screen=this.applyLineResets(screen).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,changedRows=screen.map((line,row)=>line!==this.previousScreen[row]),imageAnchorsNeedRedraw=screen.some((line,row)=>changedRows[row]&&(isImageLine(line)||isImageLine(this.previousScreen[row]??
819
- ""))),isWezTerm=!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()==="wezterm",imageCellsNeedRedraw=!imageAnchorsNeedRedraw&&isWezTerm&&this.imageProtocol==="kitty"&&changedRows.some(Boolean)&&screen.some((line,row)=>{let placementRows=getKittyImagePlacementRows(line);if(placementRows===void 0)return!1;for(let coveredRow=row;coveredRow<row+placementRows;coveredRow++)if(changedRows[coveredRow])return!0;return!1}),imagesNeedRedraw=imageAnchorsNeedRedraw||imageCellsNeedRedraw,redrawImages=fullRedraw||
823
+ length<height;)result.push("");for(let row=0;row<flashLines.length;row++){let line=flashLines[row],flashWidth=visibleWidth(line);flashWidth!==0&&(result[row]=compositeTuiLine(result[row]??"",line,width-flashWidth,flashWidth,width))}return result}findMovedRows(screen,height){let previous=this.previousScreen,top=0;for(;top<height&&screen[top]===previous[top];)top++;let bottom=height-1;for(;bottom>top&&screen[bottom]===previous[bottom];)bottom--;let span=bottom-top+1;if(span<=MIN_ROWS_SAVED_BY_SCROLLING)
824
+ return;let changed=0;for(let row=top;row<=bottom;row++){let line=screen[row];if(line!==previous[row]&&(changed++,isImageLine(line)||isImageLine(previous[row]??"")))return}if(changed<=MIN_ROWS_SAVED_BY_SCROLLING)return;let best=0,up=0;for(let distance=1;span-distance>best;distance++){let sameUp=0,sameDown=0;for(let row=top;row+distance<=bottom;row++)screen[row]===previous[row+distance]&&sameUp++,screen[row+distance]===previous[row]&&sameDown++;sameUp>best&&(best=sameUp,up=distance),sameDown>best&&
825
+ (best=sameDown,up=-distance)}if(!(changed-(span-best)<MIN_ROWS_SAVED_BY_SCROLLING)){for(let row=top;row<=bottom;row++)if(isImageLine(previous[row]??""))return;return{top,bottom,up}}}doRender(){if(this.stopped||!this.altScreenActive)return;let width=Math.max(1,this.terminal.columns),height=Math.max(1,this.terminal.rows),root=this.layoutRoot??this.implicitScrollView,nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender());this.refreshSearch(nextLayout)&&(nextLayout=renderLayoutFrame(
826
+ root,width,height,()=>this.requestRender()));let screen=nextLayout.lines.map(line=>line.startsWith("\x1B]133;")?line.replace(OSC133_ZONE_PREFIX2,""):line);screen=this.applySearchHighlights(screen,nextLayout),screen=this.compositeScrollToEndIndicator(screen,nextLayout,width),screen=this.compositeOverlays(screen,width,height),screen.length>height&&(screen=screen.slice(screen.length-height)),screen=this.applySelection(screen,nextLayout),screen=this.compositeFlashes(screen,width,height);let cursorPos=this.
827
+ extractCursorPosition(screen,height),knownRows=this.finishedRowsWidth===width?this.finishedRows:void 0,previousImageRows=this.imageRows,finishedRows=new Map,imageRows=new Set;screen=screen.map(line=>{let finished=knownRows?.get(line);return finished===void 0?(finished=this.applyLineResets([line])[0],isImageLine(finished)?imageRows.add(finished):visibleWidth(finished)>width&&(finished=sliceByColumn(finished,0,width,!0))):previousImageRows.has(finished)&&imageRows.add(finished),finishedRows.set(line,
828
+ finished),finished}),this.finishedRows=finishedRows,this.finishedRowsWidth=width,this.imageRows=imageRows;let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,imageAnchorsNeedRedraw=(imageRows.size>0||previousImageRows.size>0)&&screen.some((line,row)=>line!==this.previousScreen[row]&&(imageRows.has(line)||previousImageRows.has(this.previousScreen[row]??""))),isWezTerm=!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()===
829
+ "wezterm",imageCellsNeedRedraw=!imageAnchorsNeedRedraw&&isWezTerm&&this.imageProtocol==="kitty"&&imageRows.size>0&&screen.some((line,row)=>{if(!imageRows.has(line))return!1;let placementRows=getKittyImagePlacementRows(line);if(placementRows===void 0)return!1;for(let coveredRow=row;coveredRow<row+placementRows;coveredRow++)if(coveredRow<screen.length&&screen[coveredRow]!==this.previousScreen[coveredRow])return!0;return!1}),imagesNeedRedraw=imageAnchorsNeedRedraw||imageCellsNeedRedraw,redrawImages=fullRedraw||
820
830
  imagesNeedRedraw,hadUploadedKittyImages=this.uploadedKittyImages.size>0,preparedKittyScreen=redrawImages&&this.imageProtocol==="kitty"?this.prepareKittyScreen(screen):{lines:screen,evictedImageDeletion:""},buffer=BEGIN_SYNCHRONIZED_OUTPUT;if(fullRedraw){this.fullRedrawCount+=1;let clearImages=this.imageProtocol==="kitty"&&hadUploadedKittyImages?deleteAllKittyPlacements():this.deleteKittyImages();buffer+=`${clearImages}\x1B[2J`}else imagesNeedRedraw&&(this.imageProtocol==="iterm2"?buffer+="\x1B[2J":
821
- this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements()));if(buffer+=preparedKittyScreen.evictedImageDeletion,redrawImages&&this.imageProtocol==="kitty"&&screen.some(isImageLine)&&isWezTerm){for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")||(buffer+=
822
- `\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")&&(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`)}else for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K${preparedKittyScreen.lines[row]??""}`);cursorPos?(buffer+=`\x1B[${cursorPos.row+1};${Math.
823
- min(width,cursorPos.col)+1}H`,buffer+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):buffer+="\x1B[?25l",buffer+=END_SYNCHRONIZED_OUTPUT,this.terminal.write(buffer),this.previousScreen=screen,this.previousScreenWidth=width,this.previousScreenHeight=height,this.currentLayout=nextLayout}};import*as fs2 from"node:fs";import*as os from"node:os";import*as path3 from"node:path";var KITTY_SEQUENCE_PREFIX="\x1B_G",MAX_RENDER_WRITE_CHARS=1024*1024,BoundedTerminalWriter=class{buffer="";writtenChars=0;write;constructor(write){this.write=write}append(value){let offset=0;for(;offset<value.length;){let capacity=MAX_RENDER_WRITE_CHARS-this.buffer.length;if(capacity===0){this.flush();continue}let end=Math.min(value.length,offset+capacity);if(end<value.length&&value.charCodeAt(end-1)>=55296&&value.charCodeAt(end-1)<=56319&&value.charCodeAt(end)>=56320&&value.charCodeAt(end)<=57343&&
831
+ this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements()));if(buffer+=preparedKittyScreen.evictedImageDeletion,redrawImages&&this.imageProtocol==="kitty"&&imageRows.size>0&&isWezTerm){for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")||(buffer+=`\x1B[${row+
832
+ 1};1H${preparedKittyScreen.lines[row]??""}`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")&&(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`)}else{let moved=fullRedraw||redrawImages||(process.env.HUMAIN_TERMINAL_TUI_SCROLL_ROWS||process.env.PI_TUI_SCROLL_ROWS)==="0"?void 0:this.findMovedRows(screen,height);moved&&(buffer+=`\x1B[${moved.top+1};${moved.bottom+1}r`,buffer+=moved.
833
+ up>0?`\x1B[${moved.bottom+1};1H${`
834
+ `.repeat(moved.up)}`:`\x1B[${moved.top+1};1H${"\x1BM".repeat(-moved.up)}`,buffer+="\x1B[r");for(let row=0;row<height;row++){if(!fullRedraw&&!imagesNeedRedraw){let shown=this.previousScreen[row];if(moved&&row>=moved.top&&row<=moved.bottom){let from=row+moved.up;shown=from>=moved.top&&from<=moved.bottom?this.previousScreen[from]:void 0}if(screen[row]===shown)continue}buffer+=`\x1B[${row+1};1H\x1B[2K${preparedKittyScreen.lines[row]??""}`}}cursorPos?(buffer+=`\x1B[${cursorPos.row+1};${Math.min(width,
835
+ cursorPos.col)+1}H`,buffer+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):buffer+="\x1B[?25l",buffer+=END_SYNCHRONIZED_OUTPUT,this.terminal.write(buffer),this.previousScreen=screen,this.previousScreenWidth=width,this.previousScreenHeight=height,this.currentLayout=nextLayout}};import*as fs2 from"node:fs";import*as os from"node:os";import*as path3 from"node:path";var KITTY_SEQUENCE_PREFIX="\x1B_G",MAX_RENDER_WRITE_CHARS=1024*1024,BoundedTerminalWriter=class{buffer="";writtenChars=0;write;constructor(write){this.write=write}append(value){let offset=0;for(;offset<value.length;){let capacity=MAX_RENDER_WRITE_CHARS-this.buffer.length;if(capacity===0){this.flush();continue}let end=Math.min(value.length,offset+capacity);if(end<value.length&&value.charCodeAt(end-1)>=55296&&value.charCodeAt(end-1)<=56319&&value.charCodeAt(end)>=56320&&value.charCodeAt(end)<=57343&&
824
836
  end--,end===offset){this.flush();continue}this.buffer+=value.slice(offset,end),offset=end,this.buffer.length===MAX_RENDER_WRITE_CHARS&&this.flush()}}flush(){this.buffer&&(this.write(this.buffer),this.writtenChars+=this.buffer.length,this.buffer="")}get length(){return this.writtenChars+this.buffer.length}};function parseKittyImageHeader(line){let sequenceStart=line.indexOf(KITTY_SEQUENCE_PREFIX);if(sequenceStart===-1)return;let paramsStart=sequenceStart+KITTY_SEQUENCE_PREFIX.length,paramsEnd=line.
825
837
  indexOf(";",paramsStart);if(paramsEnd===-1)return;let ids=[],rows=1;for(let param of line.slice(paramsStart,paramsEnd).split(",")){let[key,value]=param.split("=",2);if(value===void 0)continue;let numberValue=Number(value);!Number.isInteger(numberValue)||numberValue<=0||numberValue>4294967295||(key==="i"?ids.push(numberValue):key==="r"&&(rows=numberValue))}return{ids,rows}}function extractKittyImageIds(line){return parseKittyImageHeader(line)?.ids??[]}function extractKittyImageRows(line){return parseKittyImageHeader(
826
838
  line)?.rows??1}function isTermuxSession(){return!!process.env.TERMUX_VERSION}var TuiMainScreen=class extends TuiBase{mode="regular";previousLines=[];previousKittyImageIds=new Set;previousWidth=0;previousHeight=0;cursorRow=0;hardwareCursorRow=0;maxLinesRendered=0;previousViewportTop=0;captureRenderState(){return{previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{parseStreamingJson}from"./chunk-4X774RBJ.js";import{createProvider,getSystemMessageText}from"./chunk-WPLW452J.js";import{createAssistantMessageEventStream}from"./chunk-YURQPD6Y.js";import{Compile,value_exports}from"./chunk-QMUIATLD.js";import{typebox_exports}from"./chunk-BHM75BJJ.js";function envApiKeyAuth(name,envVars){return{name,login:async interaction=>{interaction.signal.throwIfAborted();let key=await interaction.prompt({type:"secret",message:`Enter ${name}`});return interaction.signal.throwIfAborted(),{type:"api_key",key}},resolve:async({ctx,credential,signal})=>{if(signal.throwIfAborted(),credential?.key)return{auth:{apiKey:credential.key},env:credential.env,source:"stored credential"};for(let envVar of envVars){let value=await ctx.env(envVar);if(signal.throwIfAborted(),
2
+ import{parseStreamingJson}from"./chunk-GVVRXZHN.js";import{createProvider,getSystemMessageText}from"./chunk-WPLW452J.js";import{createAssistantMessageEventStream}from"./chunk-YURQPD6Y.js";import{Compile,value_exports}from"./chunk-QMUIATLD.js";import{typebox_exports}from"./chunk-BHM75BJJ.js";function envApiKeyAuth(name,envVars){return{name,login:async interaction=>{interaction.signal.throwIfAborted();let key=await interaction.prompt({type:"secret",message:`Enter ${name}`});return interaction.signal.throwIfAborted(),{type:"api_key",key}},resolve:async({ctx,credential,signal})=>{if(signal.throwIfAborted(),credential?.key)return{auth:{apiKey:credential.key},env:credential.env,source:"stored credential"};for(let envVar of envVars){let value=await ctx.env(envVar);if(signal.throwIfAborted(),
3
3
  value)return{auth:{apiKey:value},source:envVar}}}}}function lazyOAuth(input){let promise,loaded=()=>(promise??=input.load(),promise);return{name:input.name,isSubscription:input.isSubscription,loginLabel:input.loginLabel,login:async(interaction,options)=>(await loaded()).login(interaction,options),refresh:async(credential,signal)=>(await loaded()).refresh(credential,signal),toAuth:async credential=>(await loaded()).toAuth(credential)}}var DEFAULT_API="faux",DEFAULT_PROVIDER="faux",DEFAULT_MODEL_ID="faux-1",DEFAULT_MODEL_NAME="Faux Model",DEFAULT_BASE_URL="http://localhost:0",DEFAULT_MIN_TOKEN_SIZE=3,DEFAULT_MAX_TOKEN_SIZE=5,DEFAULT_USAGE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function fauxText(text){return{type:"text",text}}function fauxThinking(thinking){return{type:"thinking",thinking}}function fauxToolCall(name,arguments_,options={}){return{type:"t\
4
4
  oolCall",id:options.id??randomId("tool"),name,arguments:arguments_}}function normalizeFauxAssistantContent(content){return typeof content=="string"?[fauxText(content)]:Array.isArray(content)?content:[content]}function fauxAssistantMessage(content,options={}){return{role:"assistant",content:normalizeFauxAssistantContent(content),api:DEFAULT_API,provider:DEFAULT_PROVIDER,model:DEFAULT_MODEL_ID,usage:DEFAULT_USAGE,stopReason:options.stopReason??"stop",...options.deferred===void 0?{}:{deferred:options.
5
5
  deferred},...options.errorMessage===void 0?{}:{errorMessage:options.errorMessage},...options.responseId===void 0?{}:{responseId:options.responseId},timestamp:options.timestamp??Date.now()}}function estimateTokens(text){return Math.ceil(text.length/4)}function randomId(prefix){return`${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function contentToText(content){return typeof content=="string"?content:content.map(block=>block.type==="text"?block.text:`[image:${block.mimeType}:${block.
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{Text,getCapabilities,getImageDimensions,hyperlink,imageFallback,truncateToWidth}from"./chunk-ICLZNV4V.js";import{getBinDir,resolvePath}from"./chunk-DUZY4PDA.js";import{existsSync}from"node:fs";import{delimiter,join}from"node:path";import{spawn,spawnSync}from"child_process";function isLegacyWslBashPath(path){let normalized=path.replace(/\//g,"\\").toLowerCase();return/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)}function getBashShellConfig(shell){return isLegacyWslBashPath(shell)?{shell,args:["-s"],commandTransport:"stdin"}:{shell,args:["-c"]}}function findExecutableOnPath(executable){if(process.platform==="win32"){try{let result=spawnSync("where",[executable],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(result.status===0&&result.stdout){
2
+ import{Text,getCapabilities,getImageDimensions,hyperlink,imageFallback,truncateToWidth}from"./chunk-LQ4S7CRR.js";import{getBinDir,resolvePath}from"./chunk-3E4SMILM.js";import{existsSync}from"node:fs";import{delimiter,join}from"node:path";import{spawn,spawnSync}from"child_process";function isLegacyWslBashPath(path){let normalized=path.replace(/\//g,"\\").toLowerCase();return/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)}function getBashShellConfig(shell){return isLegacyWslBashPath(shell)?{shell,args:["-s"],commandTransport:"stdin"}:{shell,args:["-c"]}}function findExecutableOnPath(executable){if(process.platform==="win32"){try{let result=spawnSync("where",[executable],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(result.status===0&&result.stdout){
3
3
  let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch&&existsSync(firstMatch))return firstMatch}}catch{}return null}try{let result=spawnSync("which",[executable],{encoding:"utf-8",timeout:5e3});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch)return firstMatch}}catch{}return null}function getShellConfig(customShellPath){if(customShellPath){if(existsSync(customShellPath))return getBashShellConfig(customShellPath);throw new Error(
4
4
  `Custom shell path not found: ${customShellPath}`)}if(process.platform==="win32"){let paths=[],programFiles=process.env.ProgramFiles;programFiles&&paths.push(`${programFiles}\\Git\\bin\\bash.exe`);let programFilesX86=process.env["ProgramFiles(x86)"];programFilesX86&&paths.push(`${programFilesX86}\\Git\\bin\\bash.exe`);for(let path of paths)if(existsSync(path))return getBashShellConfig(path);let bashOnPath2=findExecutableOnPath("bash.exe");if(bashOnPath2)return getBashShellConfig(bashOnPath2);throw new Error(
5
5
  `No bash shell found. Options:
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{APP_TITLE,getAgentDir,getSessionsDir,normalizePath,resolvePath}from"./chunk-DUZY4PDA.js";import{getCurrentSystemMessage}from"./chunk-WPLW452J.js";import{uuidv7}from"./chunk-AKA7HNO3.js";import{randomUUID}from"crypto";import{appendFileSync,closeSync,createReadStream,existsSync,fsyncSync,mkdirSync,openSync,readdirSync,readSync,renameSync,statSync,writeFileSync}from"fs";import{readdir,stat}from"fs/promises";import{basename,join,resolve}from"path";import{createInterface}from"readline";import{StringDecoder}from"string_decoder";var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
2
+ import{APP_TITLE,getAgentDir,getSessionsDir,normalizePath,resolvePath}from"./chunk-3E4SMILM.js";import{getCurrentSystemMessage}from"./chunk-WPLW452J.js";import{uuidv7}from"./chunk-AKA7HNO3.js";import{randomUUID}from"crypto";import{appendFileSync,closeSync,createReadStream,existsSync,fsyncSync,mkdirSync,openSync,readdirSync,readSync,renameSync,statSync,writeFileSync}from"fs";import{readdir,stat}from"fs/promises";import{basename,join,resolve}from"path";import{createInterface}from"readline";import{StringDecoder}from"string_decoder";var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
3
3
 
4
4
  <summary>
5
5
  `,COMPACTION_SUMMARY_SUFFIX=`
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isMcpAppResource,isObject,mcpNamespace,require_proper_lockfile,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-JQZ7BIAI.js";import{APP_TITLE,ENV_MCP_CLIENT_METADATA_URL,VERSION,getAgentDir}from"./chunk-DUZY4PDA.js";import{__toESM}from"./chunk-JXWJOIH4.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{pathToFileURL}from"node:url";import{createServer}from"node:http";var ALLOWED_ERROR_CODES=new Set(["invalid_request","invalid_client","invalid_grant","unauthorized_client","unsupported_grant_type","invalid_scope","access_denied","unsupported_response_type","server_error","temporarily_unavailable","invalid_token","insufficient_scope","authorization_pending","slow_down","expired_token","invalid_redirect_uri","invalid_client_metadata","invalid_software_statement","unapproved_software_statement"]);function isAllowedOAuthErrorCode(value){return ALLOWED_ERROR_CODES.
2
+ import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isMcpAppResource,isObject,mcpNamespace,require_proper_lockfile,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-F7UMX5BV.js";import{APP_TITLE,ENV_MCP_CLIENT_METADATA_URL,VERSION,getAgentDir}from"./chunk-3E4SMILM.js";import{__toESM}from"./chunk-JXWJOIH4.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{pathToFileURL}from"node:url";import{createServer}from"node:http";var ALLOWED_ERROR_CODES=new Set(["invalid_request","invalid_client","invalid_grant","unauthorized_client","unsupported_grant_type","invalid_scope","access_denied","unsupported_response_type","server_error","temporarily_unavailable","invalid_token","insufficient_scope","authorization_pending","slow_down","expired_token","invalid_redirect_uri","invalid_client_metadata","invalid_software_statement","unapproved_software_statement"]);function isAllowedOAuthErrorCode(value){return ALLOWED_ERROR_CODES.
3
3
  has(value)}function sanitizeOAuthErrorCode(value,fallback="server_error"){return value&&ALLOWED_ERROR_CODES.has(value)?value:fallback}var OAuthError=class extends Error{code;errorUri;constructor(code,message,errorUri){super(message||code),this.name="OAuthError",this.code=code,this.errorUri=errorUri}},OAuthIssuerMismatchError=class extends Error{expected;received;constructor(expected,received){super(`OAuth issuer mismatch: expected ${JSON.stringify(expected)}, received ${received===void 0?"none":
4
4
  JSON.stringify(received)}`),this.name="OAuthIssuerMismatchError",this.expected=expected,this.received=received}},OAuthInsecureEndpointError=class extends Error{endpoint;constructor(endpoint){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`),this.name="OAuthInsecureEndpointError",this.endpoint=endpoint}},OAuthRedirectError=class extends Error{constructor(){super("OAuth endpoint redirected; refusing to follow the redirect"),this.name="OAuthRedirectError"}},OAuthRegistrationError=class extends Error{status;code;constructor(status,code){
5
5
  super(`OAuth dynamic client registration failed with status ${status}${code?`: ${code}`:""}`),this.name="OAuthRegistrationError",this.status=status,this.code=code}},McpOAuthAuthorizationRequiredError=class extends Error{constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}};function plainText(page){return page.ok?"Authorization complete. You may close this window.":page.details?`${page.message}
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{ENV_PREFIX,getAgentDir,getPackageDir,isBunBinary,isBunRuntime,isBundledNode}from"./chunk-DUZY4PDA.js";import{Compile}from"./chunk-QMUIATLD.js";import{typebox_exports}from"./chunk-BHM75BJJ.js";var FLOW_ID_PATTERN="^[a-z0-9][a-z0-9_.:-]{0,127}$",FLOW_MODEL_ID_PATTERN="^(?=.{1,128}$)[a-z0-9][a-z0-9_.:-]*(?:/[a-z0-9][a-z0-9_.:-]*)?$",FLOW_DIGEST_PATTERN="^[a-f0-9]{64}$",FLOW_TS_PATTERN="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,9})?(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)$",FLOW_CONTRACT_ERROR_CODES={profile_invalid:"Invalid flow profile",admission_invalid:"Invalid flow run admission",event_invalid:"Invalid flow event",command_invalid:"\
2
+ import{ENV_PREFIX,getAgentDir,getPackageDir,isBunBinary,isBunRuntime,isBundledNode}from"./chunk-3E4SMILM.js";import{Compile}from"./chunk-QMUIATLD.js";import{typebox_exports}from"./chunk-BHM75BJJ.js";var FLOW_ID_PATTERN="^[a-z0-9][a-z0-9_.:-]{0,127}$",FLOW_MODEL_ID_PATTERN="^(?=.{1,128}$)[a-z0-9][a-z0-9_.:-]*(?:/[a-z0-9][a-z0-9_.:-]*)?$",FLOW_DIGEST_PATTERN="^[a-f0-9]{64}$",FLOW_TS_PATTERN="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,9})?(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)$",FLOW_CONTRACT_ERROR_CODES={profile_invalid:"Invalid flow profile",admission_invalid:"Invalid flow run admission",event_invalid:"Invalid flow event",command_invalid:"\
3
3
  Invalid flow control command",receipt_invalid:"Invalid flow control receipt",status_invalid:"Invalid flow status",digest_mismatch:"Flow digest mismatch",digest_unverifiable:"Flow digest cannot be verified",canonical_invalid:"Flow data cannot be canonicalized",receipt_conflict:"Flow receipt conflicts with the first receipt"},FlowContractError=class extends Error{code;constructor(code){super(FLOW_CONTRACT_ERROR_CODES[code]),this.name="FlowContractError",this.code=code}},lit=(...values)=>typebox_exports.
4
4
  Union(values.map(value=>typebox_exports.Literal(value))),StrictObject=properties=>typebox_exports.Object(properties,{additionalProperties:!1}),FlowIdSchema=typebox_exports.String({pattern:FLOW_ID_PATTERN}),FlowDigestSchema=typebox_exports.String({pattern:FLOW_DIGEST_PATTERN}),DAYS_IN_MONTH=[31,28,31,30,31,30,31,31,30,31,30,31];function isRealCalendarDate(timestamp){let year=Number(timestamp.slice(0,4)),month=Number(timestamp.slice(5,7)),day=Number(timestamp.slice(8,10)),leap=year%4===0&&year%100!==
5
5
  0||year%400===0;return day<=(month===2&&leap?29:DAYS_IN_MONTH[month-1]??0)}var FlowTimestampSchema=typebox_exports.Refine(typebox_exports.String({pattern:FLOW_TS_PATTERN}),isRealCalendarDate),FlowMicrousdSchema=typebox_exports.Integer({minimum:0,maximum:Number.MAX_SAFE_INTEGER}),FlowCountSchema=typebox_exports.Integer({minimum:0,maximum:Number.MAX_SAFE_INTEGER}),FlowPositiveIntSchema=typebox_exports.Integer({minimum:1,maximum:Number.MAX_SAFE_INTEGER}),FlowModelRefSchema=StrictObject({provider:FlowIdSchema,
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{getAgentDir}from"./chunk-DUZY4PDA.js";import{AsyncLocalStorage}from"node:async_hooks";import{spawn}from"node:child_process";import{existsSync,readFileSync}from"node:fs";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{isIP}from"node:net";import{hostname,tmpdir}from"node:os";import{join}from"node:path";function getWebSearchConfigDir(){return getAgentDir()}function getWebSearchConfigPath(){return join(getWebSearchConfigDir(),"web-search.json")}function isLoopbackHostname(hostnameValue){let normalized=hostnameValue.replace(/^\[|\]$/g,"").replace(/\.$/,"").toLowerCase();return normalized==="localhost"||normalized==="::1"||isIP(normalized)===4&&normalized.split(".",1)[0]==="127"}function resolveApiBaseUrl(options){let fromEnvironment=options.environmentValue!==void 0,value=fromEnvironment?options.
2
+ import{getAgentDir}from"./chunk-3E4SMILM.js";import{AsyncLocalStorage}from"node:async_hooks";import{spawn}from"node:child_process";import{existsSync,readFileSync}from"node:fs";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{isIP}from"node:net";import{hostname,tmpdir}from"node:os";import{join}from"node:path";function getWebSearchConfigDir(){return getAgentDir()}function getWebSearchConfigPath(){return join(getWebSearchConfigDir(),"web-search.json")}function isLoopbackHostname(hostnameValue){let normalized=hostnameValue.replace(/^\[|\]$/g,"").replace(/\.$/,"").toLowerCase();return normalized==="localhost"||normalized==="::1"||isIP(normalized)===4&&normalized.split(".",1)[0]==="127"}function resolveApiBaseUrl(options){let fromEnvironment=options.environmentValue!==void 0,value=fromEnvironment?options.
3
3
  environmentValue:options.configuredValue;if(value===void 0)return options.defaultValue;let source=fromEnvironment?options.environmentKey:`${options.configKey} in ${getWebSearchConfigPath()}`;if(typeof value!="string"||value.trim().length===0)throw new Error(`${source} must be an absolute HTTP(S) URL`);let url;try{url=new URL(value.trim())}catch{throw new Error(`${source} must be an absolute HTTP(S) URL`)}if(url.protocol!=="https:"&&(url.protocol!=="http:"||!isLoopbackHostname(url.hostname)))throw new Error(
4
4
  `${source} must be an absolute HTTPS URL`);if(url.username||url.password)throw new Error(`${source} must not include credentials`);if(url.search||url.hash)throw new Error(`${source} must not include query parameters or fragments`);return url.search="",url.hash="",url.pathname=url.pathname.replace(/\/+$/,""),url.toString().replace(/\/+$/,"")}var API_REDIRECT_STATUSES=new Set([301,302,303,307,308]),API_REQUEST_BODY_HEADERS=["Content-Encoding","Content-Language","Content-Location","Content-Type"],MAX_API_REDIRECTS=5;
5
5
  async function fetchWithCredentialRedirects(url,init,credentialHeaders){let current=new URL(url),requestInit=init;for(let redirects=0;;redirects++){let response=await fetch(current,{...requestInit,redirect:"manual"});if(!API_REDIRECT_STATUSES.has(response.status))return response;let location=response.headers.get("location");if(!location)return response;if(redirects===MAX_API_REDIRECTS)throw new Error(`Too many API redirects from ${url}`);let next=new URL(location,current);if(next.protocol!=="htt\
@@ -4,9 +4,9 @@ InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorCom
4
4
  createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPiAgentExecutionHost,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,
5
5
  createReadTool,createReadToolDefinition,createSubagentTool,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAgents,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,findTurnStartIndex,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getFlowChildLaunchHost,getFlowControlHost,getFlowTraceProducer,
6
6
  getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,parseArgs,parseFrontmatter,parseSkillBlock,prepareBranchEntries,prepareChildLaunch,renderDiff,renderTaskWithContext,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,shouldCompact,stripFrontmatter,
7
- withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunk-DECZQGMF.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-H5CZL7M5.js";import{CURRENT_SESSION_VERSION,SessionManager,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,formatDimensionNote,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,resizeImage,sessionEntryToContextMessages}from"./chunk-LFXFQLII.js";import{readStoredCredential}from"./chunk-JQZ7BIAI.js";
8
- import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getPowerShellConfig,getShellConfig,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunk-OXJXKCLB.js";import{ArminComponent}from"./chunk-E7WGCXWK.js";import{Container,SelectList,Theme,getAvailableThemes,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunk-ICLZNV4V.js";import{HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,
9
- HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse}from"./chunk-VQTXF23B.js";import{CONFIG_DIR_NAME,UPSTREAM_PI_VERSION,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunk-DUZY4PDA.js";import{
7
+ withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunk-DAJJK7AP.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-KRMTBTWU.js";import{CURRENT_SESSION_VERSION,SessionManager,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,formatDimensionNote,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,resizeImage,sessionEntryToContextMessages}from"./chunk-ROSZII6E.js";import{readStoredCredential}from"./chunk-F7UMX5BV.js";
8
+ import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getPowerShellConfig,getShellConfig,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunk-PMISFIBM.js";import{ArminComponent}from"./chunk-GUUAEK6G.js";import{Container,SelectList,Theme,getAvailableThemes,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunk-LQ4S7CRR.js";import{HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,
9
+ HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse}from"./chunk-TIAXGIMN.js";import{CONFIG_DIR_NAME,UPSTREAM_PI_VERSION,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunk-3E4SMILM.js";import{
10
10
  __export}from"./chunk-JXWJOIH4.js";var dist_exports={};__export(dist_exports,{ACCOUNT_RETURN_COOLDOWN_MS:()=>ACCOUNT_RETURN_COOLDOWN_MS,ACCOUNT_RETURN_MAX_COOLDOWN_MS:()=>ACCOUNT_RETURN_MAX_COOLDOWN_MS,AgentExecInputError:()=>AgentExecInputError,AgentSession:()=>AgentSession,AgentSessionRuntime:()=>AgentSessionRuntime,ArminComponent:()=>ArminComponent,AssistantMessageComponent:()=>AssistantMessageComponent,BashExecutionComponent:()=>BashExecutionComponent,BorderedLoader:()=>BorderedLoader,BranchSummaryMessageComponent:()=>BranchSummaryMessageComponent,
11
11
  CONFIG_DIR_NAME:()=>CONFIG_DIR_NAME,CURRENT_SESSION_VERSION:()=>CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent:()=>CompactionSummaryMessageComponent,CredentialSynchronizationError:()=>CredentialSynchronizationError,CustomEditor:()=>CustomEditor,CustomMessageComponent:()=>CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS:()=>DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES:()=>DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES:()=>DEFAULT_MAX_LINES,DefaultPackageManager:()=>DefaultPackageManager,DefaultResourceLoader:()=>DefaultResourceLoader,
12
12
  DynamicBorder:()=>DynamicBorder,ExtensionEditorComponent:()=>ExtensionEditorComponent,ExtensionInputComponent:()=>ExtensionInputComponent,ExtensionRunner:()=>ExtensionRunner,ExtensionSelectorComponent:()=>ExtensionSelectorComponent,FooterComponent:()=>FooterComponent,HUMAIN_AGENT_EXECUTION_FAILURE_CODES:()=>HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION:()=>HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema:()=>HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema:()=>HumainAgentExecutionClaimSchema,
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{VisualLinePreview,getTextOutput,replaceTabs,str}from"./chunk-OXJXKCLB.js";import{Container,Spacer,Text,highlightCode,keyHint}from"./chunk-ICLZNV4V.js";import{getDocsPath}from"./chunk-DUZY4PDA.js";import{typebox_exports}from"./chunk-BHM75BJJ.js";function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){usage.usageIncomplete&&(totals.usageIncomplete=!0),totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{...first.usageIncomplete||second.usageIncomplete?{usageIncomplete:!0}:{},input:first.input+second.input,output:first.output+second.
2
+ import{VisualLinePreview,getTextOutput,replaceTabs,str}from"./chunk-PMISFIBM.js";import{Container,Spacer,Text,highlightCode,keyHint}from"./chunk-LQ4S7CRR.js";import{getDocsPath}from"./chunk-3E4SMILM.js";import{typebox_exports}from"./chunk-BHM75BJJ.js";function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){usage.usageIncomplete&&(totals.usageIncomplete=!0),totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{...first.usageIncomplete||second.usageIncomplete?{usageIncomplete:!0}:{},input:first.input+second.input,output:first.output+second.
3
3
  output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+
4
4
  second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total}}}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let entry of entries){let key,usage;if(entry.type==="message"&&entry.message.role==="assistant"?(key=`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage=entry.message.usage):entry.type==="usage"?(key=`${entry.provider}/${entry.model}`,usage=entry.usage):entry.type==="message"&&
5
5
  entry.message.role==="toolResult"&&entry.message.usage?(key="Tools/summaries",usage=entry.message.usage):(entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage&&(key="Tools/summaries",usage=entry.usage),!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,...totals.usageIncomplete?{usageIncomplete:!0}:{},cost:totals.cost,tokens:totals.
@@ -120,7 +120,7 @@ Searches over deferred tool metadata with BM25 and exposes matching tools for th
120
120
  Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;function createToolSearchToolDefinition(options={}){return{name:TOOL_SEARCH_TOOL_NAME,label:TOOL_SEARCH_TOOL_NAME,description:TOOL_SEARCH_DESCRIPTION,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:toolSearchSchema,
121
121
  exposure:"model-only",async execute(_toolCallId,{query,limit}){if(query.trim()==="")throw new Error("query must not be empty");let max=limit??DEFAULT_TOOL_SEARCH_LIMIT;if(!Number.isInteger(max)||max<=0)throw new Error("limit must be a positive integer");let tools=options.tools?searchAndLoad(options.tools,query,max):[];return{content:[{type:"text",text:tools.length===0?"No matching tools found.":`Loaded ${tools.length} tool${tools.length===1?"":"s"}. They are available from your next call:
122
122
  ${tools.map(tool=>`- ${tool.name}: ${tool.description.trim().split(/\r?\n/)[0]}`).join(`
123
- `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join}from"node:path";function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-MFIDTEMB.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme,hidden,noun){return`${theme.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(
123
+ `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join}from"node:path";function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-OSBDNQU5.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme,hidden,noun){return`${theme.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(
124
124
  2):cost.toPrecision(2)}`}function statusIcon(call,theme){switch(call.status){case"running":return theme.fg("warning","\u2026");case"ok":return theme.fg("success","\u2713");case"error":return theme.fg("error","\u2717");case"cancelled":return theme.fg("muted","\u2298")}}function formatCall(call,theme,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS?`${call.args.slice(0,COLLAPSED_ARGS_CHARS-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme)}\
125
125
  ${theme.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme.fg("muted",args)}`),duration&&(line+=` ${theme.fg("dim",duration)}`),call.cost&&(line+=` ${theme.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
126
126
  ${theme.fg("error",call.error.split(`
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-E22S6D55.js";import{ProjectTrustStore,addMcpServerConfig,loadMcpConfig,openBrowser,removeMcpServerConfig}from"./chunk-H5CZL7M5.js";import{getMcpToolExposure,validateMcpServerConfig}from"./chunk-JQZ7BIAI.js";import"./chunk-OXJXKCLB.js";import{source_default}from"./chunk-ICLZNV4V.js";import"./chunk-SCIGZFN5.js";import{APP_COMMAND,
3
- CONFIG_DIR_NAME}from"./chunk-DUZY4PDA.js";import"./chunk-JXWJOIH4.js";import{existsSync}from"node:fs";import{join}from"node:path";import{createInterface}from"node:readline/promises";var HELP=`${source_default.bold("Usage:")}
2
+ import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-SWRU4BOC.js";import{ProjectTrustStore,addMcpServerConfig,loadMcpConfig,openBrowser,removeMcpServerConfig}from"./chunk-KRMTBTWU.js";import{getMcpToolExposure,validateMcpServerConfig}from"./chunk-F7UMX5BV.js";import"./chunk-PMISFIBM.js";import{source_default}from"./chunk-LQ4S7CRR.js";import"./chunk-SCIGZFN5.js";import{APP_COMMAND,
3
+ CONFIG_DIR_NAME}from"./chunk-3E4SMILM.js";import"./chunk-JXWJOIH4.js";import{existsSync}from"node:fs";import{join}from"node:path";import{createInterface}from"node:readline/promises";var HELP=`${source_default.bold("Usage:")}
4
4
  ${APP_COMMAND} mcp add <server> [options] -- <command> [args...]
5
5
  ${APP_COMMAND} mcp add <server> [options] --url <url>
6
6
  ${APP_COMMAND} mcp remove <server> [-l]