mu-agent 0.1.10 → 0.1.14
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.
- package/CHANGELOG.md +122 -0
- package/README.md +7 -7
- package/dist/bundle/chunks/{chunk-DNNHZBQR.js → chunk-6Z2347ML.js} +1 -1
- package/dist/bundle/chunks/{chunk-FN6OEZYR.js → chunk-AN7MSYCK.js} +1 -1
- package/dist/bundle/chunks/{chunk-O7IPTASE.js → chunk-BK7M6BDT.js} +22 -21
- package/dist/bundle/chunks/{chunk-X234222Q.js → chunk-DYTENXHX.js} +2 -2
- package/dist/bundle/chunks/{chunk-RAQ6TU76.js → chunk-FLHKNMLQ.js} +1 -1
- package/dist/bundle/chunks/chunk-LHRPMXVI.js +2 -0
- package/dist/bundle/chunks/{chunk-HZNN636Z.js → chunk-LT2C56HV.js} +1 -1
- package/dist/bundle/chunks/{chunk-SGOTYFMT.js → chunk-MF3VB62R.js} +1 -1
- package/dist/bundle/chunks/{chunk-QOEEJKS4.js → chunk-URBBMV3M.js} +1 -1
- package/dist/bundle/chunks/{chunk-VJLOQZKR.js → chunk-WCJNJQO5.js} +1 -1
- package/dist/bundle/chunks/{cli-722OL3K5.js → cli-M4YBZZ6Q.js} +1 -1
- package/dist/bundle/chunks/{easter-egg-3d-6H34EDGX.js → easter-egg-3d-VFY3YRQR.js} +1 -1
- package/dist/bundle/chunks/{execute-KVSEIDWL.js → execute-FKI7Y4XR.js} +1 -1
- package/dist/bundle/chunks/{runtime-O3ELDOM7.js → runtime-IKE5OQIW.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-IKEARUOZ.js → virtual-modules-U6MRV5BC.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/docs/settings.md +1 -1
- package/judge/dist/auth.js +54 -26
- package/judge/dist/chrome.js +2 -2
- package/judge/dist/import.js +833 -161
- package/judge/dist/setup.js +142 -48
- package/judge/manifest.json +2048 -394
- package/judge/mu/chunk-3NQ5BIBI.js +4773 -0
- package/judge/mu/chunk-6XRUK3PM.js +51 -0
- package/judge/mu/chunk-WQM4MV6L.js +58 -0
- package/judge/mu/cloud-code-XR7SZMJC.js +22802 -0
- package/judge/mu/dist-75PS4OC4.js +1283 -0
- package/judge/mu/index.js +4949 -32969
- package/judge/mu/multipart-parser-ZDXVIOOP.js +372 -0
- package/judge/mu/src-TVVA5ZK2.js +1409 -0
- package/kyrn/bin/kyrn-doctor +67 -14
- package/kyrn/bin/kyrn-judge-local +42 -13
- package/kyrn/bin/kyrn-ledger +16 -1
- package/kyrn/bin/mu.mjs +101 -29
- package/kyrn/local-judge/server.py +26 -14
- package/package.json +6 -3
- package/dist/bundle/chunks/chunk-BSS6T6KQ.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{source_default}from"./chunk-6QGV3IWD.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-BSS6T6KQ.js";import{require_bash,require_c,require_core,require_cpp,require_csharp,require_dart,require_go,require_groovy,require_java,require_javascript,require_json,require_kotlin,require_lua,require_nix,require_perl,require_php,require_python,require_ruby,require_rust,require_scala,require_swift,require_typescript}from"./chunk-5AGIVGSV.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,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,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,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,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var isInRange=(ranges,codePoint)=>{let low=0,high=Math.floor(ranges.length/2)-1;for(;low<=high;){let mid=Math.floor((low+high)/2),i=mid*2;if(codePoint<ranges[i])high=mid-1;else if(codePoint>ranges[i+1])low=mid+1;else return!0}return!1};var commonCjkCodePoint=19968,[wideFastPathStart,wideFastPathEnd]=findWideFastPathRange(wideRanges);function findWideFastPathRange(ranges){let fastPathStart=ranges[0],fastPathEnd=ranges[1];for(let index=0;index<ranges.length;index+=2){let start=ranges[index],end=ranges[index+1];if(commonCjkCodePoint>=start&&commonCjkCodePoint<=end)return[start,end];end-start>fastPathEnd-fastPathStart&&(fastPathStart=start,fastPathEnd=end)}return[fastPathStart,fastPathEnd]}var isAmbiguous=codePoint=>codePoint<161||codePoint>1114109?!1:isInRange(ambiguousRanges,codePoint),isFullWidth=codePoint=>codePoint<fullwidthMinimalCodePoint||codePoint>fullwidthMaximumCodePoint?!1:isInRange(fullwidthRanges,codePoint);var isWide=codePoint=>codePoint>=wideFastPathStart&&codePoint<=wideFastPathEnd?!0:codePoint<wideMinimalCodePoint||codePoint>wideMaximumCodePoint?!1:isInRange(wideRanges,codePoint);function validate(codePoint){if(!Number.isSafeInteger(codePoint))throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`)}function eastAsianWidth(codePoint,{ambiguousAsWide=!1}={}){return validate(codePoint),isFullWidth(codePoint)||isWide(codePoint)||ambiguousAsWide&&isAmbiguous(codePoint)?2:1}var graphemeSegmenter=new Intl.Segmenter(void 0,{granularity:"grapheme"}),wordSegmenter=new Intl.Segmenter(void 0,{granularity:"word"});function getGraphemeSegmenter(){return graphemeSegmenter}function getWordSegmenter(){return wordSegmenter}function couldBeEmoji(segment){let cp=segment.codePointAt(0);return cp>=126976&&cp<=130047||cp>=8960&&cp<=9215||cp>=9728&&cp<=10175||cp>=11088&&cp<=11093||segment.includes("\uFE0F")||segment.length>2}var zeroWidthRegex=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),leadingNonPrintingRegex=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),nonPrintingCharRegex=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$","v"),markCharRegex=new RegExp("^\\p{Mark}$","v"),terminalSpacingMarkRegex=new RegExp("^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$","v"),rgiEmojiRegex=new RegExp("^\\p{RGI_Emoji}$","v"),WIDTH_CACHE_SIZE=512,widthCache=new Map,cjkBreakRegex=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,cjkPunctuationRegex=new RegExp(`(?:(?=\\p{Punctuation})${cjkBreakRegex.source}|[\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\uFF3B\uFF3D\uFF5B\uFF5D\u201C\u201D\u2018\u2019\u2026\u2014])`,"u"),autocompleteSeparatorRegex=new RegExp(`(?:\\s|${cjkPunctuationRegex.source})`,"u"),autocompleteBoundaryRegex=new RegExp(`(?:^|${autocompleteSeparatorRegex.source})`,"u");function isPrintableAscii(str){for(let i=0;i<str.length;i++){let code=str.charCodeAt(i);if(code<32||code>126)return!1}return!0}function truncateFragmentToWidth(text,maxWidth){if(maxWidth<=0||text.length===0)return{text:"",width:0};if(isPrintableAscii(text)){let clipped=text.slice(0,maxWidth);return{text:clipped,width:clipped.length}}let hasAnsi=text.includes("\x1B"),hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){let result2="",width2=0;for(let{segment}of graphemeSegmenter.segment(text)){let w=graphemeWidth(segment);if(width2+w>maxWidth)break;result2+=segment,width2+=w}return{text:result2,width:width2}}let result="",width=0,i=0,pendingAnsi="";for(;i<text.length;){let ansi=extractAnsiCode(text,i);if(ansi){pendingAnsi+=ansi.code,i+=ansi.length;continue}if(text[i]===" "){if(width+3>maxWidth)break;pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=" ",width+=3,i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&!extractAnsiCode(text,end);)end++;for(let{segment}of graphemeSegmenter.segment(text.slice(i,end))){let w=graphemeWidth(segment);if(width+w>maxWidth)return{text:result,width};pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,width+=w}i=end}return{text:result,width}}function finalizeTruncatedResult(prefix,prefixWidth,ellipsis,ellipsisWidth,maxWidth,pad){let reset="\x1B[0m",hyperlinkClose=getActiveOsc8Close(prefix),visibleWidth2=prefixWidth+ellipsisWidth,result;return ellipsis.length>0?result=`${prefix}${hyperlinkClose}${reset}${ellipsis}${reset}`:result=`${prefix}${hyperlinkClose}${reset}`,pad?result+" ".repeat(Math.max(0,maxWidth-visibleWidth2)):result}function graphemeWidth(segment){if(segment.length===1){let code=segment.charCodeAt(0);if(code>=32&&code<=126)return 1;if(code===9)return 3}if(terminalSpacingMarkRegex.test(segment))return[...segment].length;if(zeroWidthRegex.test(segment))return 0;if(couldBeEmoji(segment)&&rgiEmojiRegex.test(segment))return 2;let base=segment.replace(leadingNonPrintingRegex,""),cp=base.codePointAt(0);if(cp===void 0)return 0;if(cp>=127462&&cp<=127487)return 2;let width=eastAsianWidth(cp),followsMark=!1,chars=[...base];for(let char of chars.slice(1))if(terminalSpacingMarkRegex.test(char))width+=1,followsMark=!1;else if(markCharRegex.test(char))followsMark=!0;else if(!nonPrintingCharRegex.test(char)){let c2=char.codePointAt(0);followsMark||c2>=65280&&c2<=65519?width+=eastAsianWidth(c2):(c2===3635||c2===3763)&&(width+=1),followsMark=!1}return width}function visibleWidth(str){if(str.length===0)return 0;let asciiWidth=asciiVisibleWidth(str);if(asciiWidth!==-1)return asciiWidth;let cached=widthCache.get(str);if(cached!==void 0)return cached;let clean=str;str.includes(" ")&&(clean=clean.replace(/\t/g," "));let escapeIndex=clean.indexOf("\x1B");if(escapeIndex!==-1){let stripped="",copyFrom=0;for(;escapeIndex!==-1;){let length=ansiCodeLength(clean,escapeIndex);length>0?(stripped+=clean.slice(copyFrom,escapeIndex),escapeIndex+=length,copyFrom=escapeIndex):escapeIndex++,escapeIndex=clean.indexOf("\x1B",escapeIndex)}clean=stripped+clean.slice(copyFrom)}let width=0;for(let{segment}of graphemeSegmenter.segment(clean))width+=graphemeWidth(segment);if(widthCache.size>=WIDTH_CACHE_SIZE){let firstKey=widthCache.keys().next().value;firstKey!==void 0&&widthCache.delete(firstKey)}return widthCache.set(str,width),width}function stripTerminalSequences(str){if(!str.includes("\x1B"))return str;let result="",i=0;for(;i<str.length;){let ansi=extractAnsiCode(str,i);if(ansi){i+=ansi.length;continue}result+=str[i],i++}return result}function getGraphemeCellRange(line,column){let currentCol=0,i=0;for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let width=graphemeWidth(segment);if(width>0&&column>=currentCol&&column<currentCol+width)return{start:currentCol,end:currentCol+width};currentCol+=width}i=textEnd}}function getOsc8LinkAtColumn(line,column){let activeUrl,currentCol=0,i=0;for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){let hyperlink2=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(ansi.code);hyperlink2&&(activeUrl=hyperlink2[1]||void 0),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let width=segment===" "?3:graphemeWidth(segment);if(column>=currentCol&&column<currentCol+width)return activeUrl;currentCol+=width}i=textEnd}}var THAI_LAO_AM_REGEX=/[\u0e33\u0eb3]/,THAI_LAO_AM_GLOBAL_REGEX=/[\u0e33\u0eb3]/g;function normalizeTerminalOutput(str){let normalized=str;if(THAI_LAO_AM_REGEX.test(normalized)&&(normalized=normalized.replace(THAI_LAO_AM_GLOBAL_REGEX,char=>char==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2")),!normalized.includes(" "))return normalized;let result="",i=0;for(;i<normalized.length;){let ansi=extractAnsiCode(normalized,i);if(ansi){result+=ansi.code,i+=ansi.length;continue}result+=normalized[i]===" "?" ":normalized[i],i++}return result}function extractAnsiCode(str,pos){let length=ansiCodeLength(str,pos);return length>0?{code:str.substring(pos,pos+length),length}:null}function asciiVisibleWidth(str){let width=0,i=0;for(;i<str.length;){let code=str.charCodeAt(i);if(code>=32&&code<=126)width++,i++;else if(code===9)width+=3,i++;else if(code===27){let length=ansiCodeLength(str,i);if(length===0)return-1;i+=length}else return-1}return width}function ansiCodeLength(str,pos){if(pos>=str.length||str.charCodeAt(pos)!==27)return 0;let next=str[pos+1];if(next==="["){for(let j2=pos+2;j2<str.length;j2++){let c2=str.charCodeAt(j2);if(c2===109||c2===71||c2===75||c2===72||c2===74)return j2+1-pos}return 0}if(next==="]"||next==="_"){for(let j2=pos+2;j2<str.length;j2++){let c2=str.charCodeAt(j2);if(c2===7)return j2+1-pos;if(c2===27&&str[j2+1]==="\\")return j2+2-pos}return 0}return 0}function parseOsc8Hyperlink(ansiCode){if(!ansiCode.startsWith("\x1B]8;"))return;let terminator=ansiCode.endsWith("\x07")?"\x07":"\x1B\\",body=ansiCode.slice(4,terminator==="\x07"?-1:-2),separatorIndex=body.indexOf(";");if(separatorIndex===-1)return;let params=body.slice(0,separatorIndex),url=body.slice(separatorIndex+1);return url?{params,url,terminator}:null}function formatOsc8Hyperlink(hyperlink2){return`\x1B]8;${hyperlink2.params};${hyperlink2.url}${hyperlink2.terminator}`}function formatOsc8Close(terminator){return`\x1B]8;;${terminator}`}function getActiveOsc8Close(prefix){if(!prefix.includes("\x1B]8;"))return"";let activeHyperlink=null,i=0;for(;i<prefix.length;){let ansi=extractAnsiCode(prefix,i);if(ansi){let hyperlink2=parseOsc8Hyperlink(ansi.code);hyperlink2!==void 0&&(activeHyperlink=hyperlink2),i+=ansi.length}else i++}return activeHyperlink?formatOsc8Close(activeHyperlink.terminator):""}var AnsiCodeTracker=class{bold=!1;dim=!1;italic=!1;underline=!1;blink=!1;inverse=!1;hidden=!1;strikethrough=!1;fgColor=null;bgColor=null;activeHyperlink=null;process(ansiCode){let hyperlink2=parseOsc8Hyperlink(ansiCode);if(hyperlink2!==void 0){this.activeHyperlink=hyperlink2;return}if(!ansiCode.endsWith("m"))return;let match=ansiCode.match(/\x1b\[([\d;]*)m/);if(!match)return;let params=match[1];if(params===""||params==="0"){this.reset();return}let parts=params.split(";"),i=0;for(;i<parts.length;){let code=Number.parseInt(parts[i],10);if(code===38||code===48){if(parts[i+1]==="5"&&parts[i+2]!==void 0){let colorCode=`${parts[i]};${parts[i+1]};${parts[i+2]}`;code===38?this.fgColor=colorCode:this.bgColor=colorCode,i+=3;continue}else if(parts[i+1]==="2"&&parts[i+4]!==void 0){let colorCode=`${parts[i]};${parts[i+1]};${parts[i+2]};${parts[i+3]};${parts[i+4]}`;code===38?this.fgColor=colorCode:this.bgColor=colorCode,i+=5;continue}}switch(code){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:code>=30&&code<=37||code>=90&&code<=97?this.fgColor=String(code):(code>=40&&code<=47||code>=100&&code<=107)&&(this.bgColor=String(code));break}i++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let codes=[];this.bold&&codes.push("1"),this.dim&&codes.push("2"),this.italic&&codes.push("3"),this.underline&&codes.push("4"),this.blink&&codes.push("5"),this.inverse&&codes.push("7"),this.hidden&&codes.push("8"),this.strikethrough&&codes.push("9"),this.fgColor&&codes.push(this.fgColor),this.bgColor&&codes.push(this.bgColor);let result=codes.length>0?`\x1B[${codes.join(";")}m`:"";return this.activeHyperlink&&(result+=formatOsc8Hyperlink(this.activeHyperlink)),result}getActiveBackgroundCode(){return this.bgColor?`\x1B[${this.bgColor}m`:""}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let result="";return this.underline&&(result+="\x1B[24m"),this.activeHyperlink&&(result+=formatOsc8Close(this.activeHyperlink.terminator)),result}};function updateTrackerFromText(text,tracker){let i=text.indexOf("\x1B");for(;i!==-1;){let length=ansiCodeLength(text,i);length>0?(tracker.process(text.substring(i,i+length)),i+=length):i++,i=text.indexOf("\x1B",i)}}function getActiveBackgroundAnsi(text){let tracker=new AnsiCodeTracker;return updateTrackerFromText(text,tracker),tracker.getActiveBackgroundCode()}function*graphemeSegments(text){for(let{segment}of graphemeSegmenter.segment(text))yield segment}function splitIntoTokensWithAnsi(text){let tokens=[],current="",pendingAnsi="",currentKind=null,i=0,flushCurrent=()=>{current&&(tokens.push(current),current="",currentKind=null)};for(;i<text.length;){let ansiResult=extractAnsiCode(text,i);if(ansiResult){pendingAnsi+=ansiResult.code,i+=ansiResult.length;continue}let end=text.indexOf("\x1B",i+1);for(;end!==-1&&ansiCodeLength(text,end)===0;)end=text.indexOf("\x1B",end+1);end===-1&&(end=text.length);let chunk=text.slice(i,end),ascii=isPrintableAscii(chunk);for(let segment of ascii?chunk:graphemeSegments(chunk)){let segmentIsSpace=segment===" ";if(!ascii&&!segmentIsSpace&&cjkBreakRegex.test(segment)){flushCurrent();let token=pendingAnsi+segment;pendingAnsi="",tokens.push(token);continue}let segmentKind=segmentIsSpace?"space":"word";current&¤tKind!==segmentKind&&flushCurrent(),pendingAnsi&&(current+=pendingAnsi,pendingAnsi=""),currentKind=segmentKind,current+=segment}i=end}return pendingAnsi&&(current?current+=pendingAnsi:tokens.length>0?tokens[tokens.length-1]+=pendingAnsi:current=pendingAnsi),current&&tokens.push(current),tokens}function flattenLines(lines){for(let line of lines)Number(line)}function wrapTextWithAnsi(text,width){if(!text)return[""];let inputLines=text.split(/\r\n|\r|\n/),result=[],tracker=new AnsiCodeTracker;for(let inputLine of inputLines){let prefix=result.length>0?tracker.getActiveCodes():"",wrappedLines=wrapSingleLine(prefix+inputLine,width);for(let wrappedLine of wrappedLines)result.push(wrappedLine);updateTrackerFromText(inputLine,tracker)}return result.length>0?result:[""]}function wrapSingleLine(line,width){if(!line)return[""];if(visibleWidth(line)<=width)return[line];let wrapped=[],tracker=new AnsiCodeTracker,tokens=splitIntoTokensWithAnsi(line),currentLine="",currentVisibleLength=0;for(let token of tokens){let tokenVisibleLength=visibleWidth(token),isWhitespace=token.trim()==="";if(tokenVisibleLength>width&&!isWhitespace){if(currentLine){let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),wrapped.push(currentLine),currentLine="",currentVisibleLength=0}let broken=breakLongWord(token,width,tracker);for(let i=0;i<broken.length-1;i++)wrapped.push(broken[i]);currentLine=broken[broken.length-1],currentVisibleLength=visibleWidth(currentLine);continue}if(currentVisibleLength+tokenVisibleLength>width&¤tVisibleLength>0){let lineToWrap=currentLine.trimEnd(),lineEndReset=tracker.getLineEndReset();lineEndReset&&(lineToWrap+=lineEndReset),wrapped.push(lineToWrap),isWhitespace?(currentLine=tracker.getActiveCodes(),currentVisibleLength=0):(currentLine=tracker.getActiveCodes()+token,currentVisibleLength=tokenVisibleLength)}else currentLine+=token,currentVisibleLength+=tokenVisibleLength;updateTrackerFromText(token,tracker)}return currentLine&&wrapped.push(currentLine),wrapped.length>0?wrapped.map(line2=>line2.trimEnd()):[""]}var PUNCTUATION_REGEX=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function isWhitespaceChar(char){return/\s/.test(char)}function breakLongWord(word,width,tracker){let lines=[],currentLine=tracker.getActiveCodes(),currentWidth=0,i=0,segments=[];for(;i<word.length;){let ansiResult=extractAnsiCode(word,i);if(ansiResult)segments.push({type:"ansi",value:ansiResult.code}),i+=ansiResult.length;else{let end=i;for(;end<word.length&&!extractAnsiCode(word,end);)end++;let textPortion=word.slice(i,end);for(let seg of graphemeSegmenter.segment(textPortion))segments.push({type:"grapheme",value:seg.segment});i=end}}for(let seg of segments){if(seg.type==="ansi"){currentLine+=seg.value,tracker.process(seg.value);continue}let grapheme=seg.value;if(!grapheme)continue;let graphemeWidth2=visibleWidth(grapheme);if(currentWidth+graphemeWidth2>width){let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),lines.push(currentLine),currentLine=tracker.getActiveCodes(),currentWidth=0}currentLine+=grapheme,currentWidth+=graphemeWidth2}return currentLine&&lines.push(currentLine),lines.length>0?lines:[""]}function applyBackgroundToLine(line,width,bgFn){let visibleLen=visibleWidth(line),paddingNeeded=Math.max(0,width-visibleLen),padding=" ".repeat(paddingNeeded),withPadding=line+padding;return bgFn(withPadding)}function truncateToWidth(text,maxWidth,ellipsis="...",pad=!1){if(maxWidth<=0)return"";if(text.length===0)return pad?" ".repeat(maxWidth):"";let ellipsisWidth=visibleWidth(ellipsis);if(ellipsisWidth>=maxWidth){let textWidth=visibleWidth(text);if(textWidth<=maxWidth)return pad?text+" ".repeat(maxWidth-textWidth):text;let clippedEllipsis=truncateFragmentToWidth(ellipsis,maxWidth);return clippedEllipsis.width===0?pad?" ".repeat(maxWidth):"":finalizeTruncatedResult("",0,clippedEllipsis.text,clippedEllipsis.width,maxWidth,pad)}if(isPrintableAscii(text)){if(text.length<=maxWidth)return pad?text+" ".repeat(maxWidth-text.length):text;let targetWidth2=maxWidth-ellipsisWidth;return finalizeTruncatedResult(text.slice(0,targetWidth2),targetWidth2,ellipsis,ellipsisWidth,maxWidth,pad)}let targetWidth=maxWidth-ellipsisWidth,result="",pendingAnsi="",visibleSoFar=0,keptWidth=0,keepContiguousPrefix=!0,overflowed=!1,exhaustedInput=!1,hasAnsi=text.includes("\x1B"),hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){for(let{segment}of graphemeSegmenter.segment(text)){let width=graphemeWidth(segment);if(keepContiguousPrefix&&keptWidth+width<=targetWidth?(result+=segment,keptWidth+=width):keepContiguousPrefix=!1,visibleSoFar+=width,visibleSoFar>maxWidth){overflowed=!0;break}}exhaustedInput=!overflowed}else{let i=0;for(;i<text.length;){let ansi=extractAnsiCode(text,i);if(ansi){pendingAnsi+=ansi.code,i+=ansi.length;continue}if(text[i]===" "){if(keepContiguousPrefix&&keptWidth+3<=targetWidth?(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=" ",keptWidth+=3):(keepContiguousPrefix=!1,pendingAnsi=""),visibleSoFar+=3,visibleSoFar>maxWidth){overflowed=!0;break}i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&!extractAnsiCode(text,end);)end++;for(let{segment}of graphemeSegmenter.segment(text.slice(i,end))){let width=graphemeWidth(segment);if(keepContiguousPrefix&&keptWidth+width<=targetWidth?(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,keptWidth+=width):(keepContiguousPrefix=!1,pendingAnsi=""),visibleSoFar+=width,visibleSoFar>maxWidth){overflowed=!0;break}}if(overflowed)break;i=end}exhaustedInput=i>=text.length}return!overflowed&&exhaustedInput?pad?text+" ".repeat(Math.max(0,maxWidth-visibleSoFar)):text:finalizeTruncatedResult(result,keptWidth,ellipsis,ellipsisWidth,maxWidth,pad)}function sliceByColumn(line,startCol,length,strict=!1){return sliceWithWidth(line,startCol,length,strict).text}function sliceWithWidth(line,startCol,length,strict=!1){if(length<=0)return{text:"",width:0};let endCol=startCol+length,result="",resultWidth=0,currentCol=0,i=0,pendingAnsi="";for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){currentCol>=startCol&¤tCol<endCol?(result+=pendingAnsi+ansi.code,pendingAnsi=""):currentCol<startCol&&(pendingAnsi+=ansi.code),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let w=graphemeWidth(segment),inRange=currentCol>=startCol&¤tCol<endCol,fits=!strict||currentCol+w<=endCol;if(inRange&&fits&&(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,resultWidth+=w),currentCol+=w,currentCol>=endCol)break}if(i=textEnd,currentCol>=endCol)break}return{text:result,width:resultWidth}}var pooledStyleTracker=new AnsiCodeTracker;function extractSegments(line,beforeEnd,afterStart,afterLen,strictAfter=!1){let before="",beforeWidth=0,after="",afterWidth=0,currentCol=0,i=0,pendingAnsiBefore="",afterStarted=!1,afterEnd=afterStart+afterLen;for(pooledStyleTracker.clear();i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){pooledStyleTracker.process(ansi.code),currentCol<beforeEnd?pendingAnsiBefore+=ansi.code:currentCol>=afterStart&¤tCol<afterEnd&&(afterStarted||ansi.code.startsWith("\x1B_"))&&(after+=ansi.code),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let w=graphemeWidth(segment);if(currentCol<beforeEnd&¤tCol+w<=beforeEnd?(pendingAnsiBefore&&(before+=pendingAnsiBefore,pendingAnsiBefore=""),before+=segment,beforeWidth+=w):currentCol>=afterStart&¤tCol<afterEnd&&(!strictAfter||currentCol+w<=afterEnd)&&(afterStarted||(after+=pooledStyleTracker.getActiveCodes(),afterStarted=!0),after+=segment,afterWidth+=w),currentCol+=w,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}if(i=textEnd,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}return{before,beforeWidth,after,afterWidth}}var multiply=(m2,[x2,y2,z2])=>m2.map(row=>row[0]*x2+row[1]*y2+row[2]*z2),LINEAR_SRGB_TO_LMS=[[.4122214694707629,.5363325372617349,.0514459932675022],[.2119034958178251,.6806995506452344,.1073969535369405],[.0883024591900564,.2817188391361215,.6299787016738222]],LMS_TO_LAB=[[.210454268309314,.793617774702305,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],LAB_TO_LMS=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],LMS_TO_LINEAR_SRGB=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-.341319376002657],[-.0041960761386756,-.7034186179359362,1.7076146940746117]],SATURATION_FIT=[[[-1.8817031,-.80936501],[1.19086277,1.76576728,.59662641,.75515197,.56771245]],[[1.8144408,-1.19445267],[.73956515,-.45954404,.08285427,.12541073,-.14503204]],[[.13110758,1.81333971],[1.35733652,-.00915799,-1.1513021,-.50559606,.00692167]]],K1=.206,K2=.03,K3=(1+K1)/(1+K2),oklabToOkhslLightness=x2=>.5*(K3*x2-K1+Math.sqrt((K3*x2-K1)**2+4*K2*K3*x2)),okhslToOklabLightness=x2=>(x2*x2+K1*x2)/(K3*(x2+K2)),linearToSrgb=value=>value>.0031308?1.055*value**(1/2.4)-.055:12.92*value,srgbToLinear=value=>value<=.04045?value/12.92:((value+.055)/1.055)**2.4;function oklabToLinearSrgb(lab){return multiply(LMS_TO_LINEAR_SRGB,multiply(LAB_TO_LMS,lab).map(value=>value**3))}function linearSrgbToOklab(rgb){return multiply(LMS_TO_LAB,multiply(LINEAR_SRGB_TO_LMS,rgb).map(Math.cbrt))}function rgbToOklab({r,g,b:b2}){return linearSrgbToOklab([r/255,g/255,b2/255].map(srgbToLinear))}function linearSrgbToRgb(linear){let[r,g,b2]=linear.map(value=>Math.round(Math.min(1,Math.max(0,linearToSrgb(value)))*255));return{r,g,b:b2}}function lmsSlopes(a,b2){return[LAB_TO_LMS[0],LAB_TO_LMS[1],LAB_TO_LMS[2]].map(row=>row[1]*a+row[2]*b2)}function maxSaturation(a,b2){let channel=SATURATION_FIT.findIndex(([[x2,y2]],index)=>index===2||x2*a+y2*b2>1),[k0,k1,k2,k3,k4]=SATURATION_FIT[channel][1],weights=LMS_TO_LINEAR_SRGB[channel],saturation=k0+k1*a+k2*b2+k3*a*a+k4*a*b2,slopes=lmsSlopes(a,b2),base=slopes.map(k5=>1+saturation*k5),dot=values=>values.reduce((sum,value,index)=>sum+weights[index]*value,0),f2=dot(base.map(value=>value**3)),f1=dot(base.map((value,index)=>3*slopes[index]*value**2)),f22=dot(base.map((value,index)=>6*slopes[index]**2*value));return saturation-f2*f1/(f1*f1-.5*f2*f22)}function cusp(a,b2){let saturation=maxSaturation(a,b2),lightness=Math.cbrt(1/Math.max(...oklabToLinearSrgb([1,saturation*a,saturation*b2])));return[lightness,lightness*saturation]}function maxChroma(a,b2,lightness,[cuspL,cuspC]){if(lightness<=cuspL)return cuspC*lightness/cuspL;let t=cuspC*(lightness-1)/(cuspL-1),slopes=lmsSlopes(a,b2),lms=slopes.map(k2=>lightness+t*k2),cubes=lms.map(value=>value**3),first=lms.map((value,index)=>3*slopes[index]*value**2),second=lms.map((value,index)=>6*slopes[index]**2*value),dot=(row,values)=>row[0]*values[0]+row[1]*values[1]+row[2]*values[2],steps=LMS_TO_LINEAR_SRGB.map(row=>{let f2=dot(row,cubes)-1,f1=dot(row,first),f22=dot(row,second),u=f1/(f1*f1-.5*f2*f22);return u>=0?-f2*u:Number.MAX_VALUE});return t+Math.min(...steps)}function chromaStops(L2,a,b2){let peak=cusp(a,b2),cMax=maxChroma(a,b2,L2,peak),k2=cMax/Math.min(L2*(peak[1]/peak[0]),(1-L2)*(peak[1]/(1-peak[0]))),midS=.11516993+1/(7.4477897+4.1590124*b2+a*(-2.19557347+1.75198401*b2+a*(-2.13704948-10.02301043*b2+a*(-4.24894561+5.38770819*b2+4.69891013*a)))),midT=.11239642+1/(1.6132032-.68124379*b2+a*(.40370612+.90148123*b2+a*(-.27087943+.6122399*b2+a*(.00299215-.45399568*b2-.14661872*a)))),cMid=.9*k2*Math.sqrt(Math.sqrt(1/(1/(L2*midS)**4+1/((1-L2)*midT)**4)));return[Math.sqrt(1/(1/(L2*.4)**2+1/((1-L2)*.8)**2)),cMid,cMax]}function okhslToRgb(hue,saturation,lightness){let L2=okhslToOklabLightness(lightness),lab=[L2,0,0];if(L2>0&&L2<1&&saturation>0){let angle=2*Math.PI*((hue%360+360)%360)/360,a=Math.cos(angle),b2=Math.sin(angle),[c0,cMid,cMax]=chromaStops(L2,a,b2),chroma;if(saturation<.8){let t=1.25*saturation,k1=.8*c0;chroma=t*k1/(1-(1-k1/cMid)*t)}else{let t=5*(saturation-.8),k1=.2*cMid**2*1.25**2/c0;chroma=cMid+t*k1/(1-(1-k1/(cMax-cMid))*t)}lab=[L2,chroma*a,chroma*b2]}return linearSrgbToRgb(oklabToLinearSrgb(lab))}function rgbToOkhsl(rgb){let[L2,labA,labB]=rgbToOklab(rgb),chroma=Math.hypot(labA,labB),lightness=oklabToOkhslLightness(L2);if(chroma<1e-9||lightness<=0||lightness>=1)return{h:0,s:0,l:lightness};let hue=(Math.atan2(labB,labA)*180/Math.PI+360)%360,[c0,cMid,cMax]=chromaStops(L2,labA/chroma,labB/chroma),saturation;if(chroma<cMid){let k1=.8*c0;saturation=.8*(chroma/(k1+(1-k1/cMid)*chroma))}else{let k1=.2*cMid**2*1.5625/c0,offset=chroma-cMid;saturation=.8+.2*(offset/(k1+(1-k1/(cMax-cMid))*offset))}return{h:hue,s:Math.min(1,Math.max(0,saturation)),l:lightness}}function requireFinite(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function indexedColor(index){if(!Number.isInteger(index)||index<0||index>255)throw new Error(`ANSI color index must be an integer from 0 to 255: ${index}`);return Object.freeze({kind:"indexed",index})}function rgbColor(r,g,b2){for(let[name,value]of[["r",r],["g",g],["b",b2]])if(requireFinite(value,name),value<0||value>255)throw new Error(`${name} must be between 0 and 255: ${value}`);return Object.freeze({kind:"rgb",r,g,b:b2})}function oklchColor(l3,c2,h){if(requireFinite(l3,"l"),requireFinite(c2,"c"),requireFinite(h,"h"),l3<0||l3>1)throw new Error(`l must be between 0 and 1: ${l3}`);if(c2<0)throw new Error(`c must not be negative: ${c2}`);return Object.freeze({kind:"oklch",l:l3,c:c2,h:(h%360+360)%360})}var NUMBER_PATTERN=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,OKLCH_PATTERN=new RegExp(`^oklch\\(\\s*(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})\\s+(${NUMBER_PATTERN})(?:deg)?\\s*\\)$`,"i"),OKHSL_PATTERN=new RegExp(`^okhsl\\(\\s*(${NUMBER_PATTERN})(?:deg)?\\s+(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})(%)?\\s*\\)$`,"i");function okhslColor(h,s,l3){if(requireFinite(h,"h"),requireFinite(s,"s"),requireFinite(l3,"l"),s<0||s>1)throw new Error(`s must be between 0 and 1: ${s}`);if(l3<0||l3>1)throw new Error(`l must be between 0 and 1: ${l3}`);let{r,g,b:b2}=okhslToRgb(h,s,l3);return rgbColor(r,g,b2)}function colorToOkhsl(color){return rgbToOkhsl(colorToRgb(color))}function parseColor(value){if(typeof value=="number")return indexedColor(value);let hex=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(value);if(hex){let digits=hex[1].length===3?[...hex[1]].map(digit=>digit+digit).join(""):hex[1];return rgbColor(Number.parseInt(digits.slice(0,2),16),Number.parseInt(digits.slice(2,4),16),Number.parseInt(digits.slice(4,6),16))}let oklch=OKLCH_PATTERN.exec(value);if(oklch){let lightness=Number.parseFloat(oklch[1])/(oklch[2]?100:1);return oklchColor(lightness,Number.parseFloat(oklch[3]),Number.parseFloat(oklch[4]))}let okhsl=OKHSL_PATTERN.exec(value);if(okhsl){let saturation=Number.parseFloat(okhsl[2])/(okhsl[3]?100:1),lightness=Number.parseFloat(okhsl[4])/(okhsl[5]?100:1);return okhslColor(Number.parseFloat(okhsl[1]),saturation,lightness)}throw new Error(`Invalid color value: ${value}`)}var BASIC_COLORS=[{r:0,g:0,b:0},{r:128,g:0,b:0},{r:0,g:128,b:0},{r:128,g:128,b:0},{r:0,g:0,b:128},{r:128,g:0,b:128},{r:0,g:128,b:128},{r:192,g:192,b:192},{r:128,g:128,b:128},{r:255,g:0,b:0},{r:0,g:255,b:0},{r:255,g:255,b:0},{r:0,g:0,b:255},{r:255,g:0,b:255},{r:0,g:255,b:255},{r:255,g:255,b:255}],CUBE_VALUES=[0,95,135,175,215,255],GRAY_VALUES=Array.from({length:24},(_2,index)=>8+index*10);function indexedToRgb(index){if(index<16)return{...BASIC_COLORS[index]};if(index<232){let cubeIndex=index-16;return{r:CUBE_VALUES[Math.floor(cubeIndex/36)],g:CUBE_VALUES[Math.floor(cubeIndex%36/6)],b:CUBE_VALUES[cubeIndex%6]}}let gray=8+(index-232)*10;return{r:gray,g:gray,b:gray}}function isInSrgbGamut(linear){return linear.every(channel=>channel>=-1e-7&&channel<=1+1e-7)}function oklchToRgb({l:l3,c:c2,h}){let radians=h*Math.PI/180,cos=Math.cos(radians),sin=Math.sin(radians),atChroma=chroma=>oklabToLinearSrgb([l3,chroma*cos,chroma*sin]),direct=atChroma(c2);if(isInSrgbGamut(direct))return linearSrgbToRgb(direct);let linear=atChroma(0),low=0,high=c2;for(let index=0;index<20;index++){let chroma=(low+high)/2,candidate=atChroma(chroma);isInSrgbGamut(candidate)?(low=chroma,linear=candidate):high=chroma}return linearSrgbToRgb(linear)}function colorToRgb(color){switch(color.kind){case"indexed":return indexedToRgb(color.index);case"rgb":return{r:color.r,g:color.g,b:color.b};case"oklch":return oklchToRgb(color)}}function colorToOklch(color){if(color.kind==="oklch")return{l:color.l,c:color.c,h:color.h};let[l3,a,b2]=rgbToOklab(colorToRgb(color));return{l:l3,c:Math.hypot(a,b2),h:(Math.atan2(b2,a)*180/Math.PI+360)%360}}function colorToHex(color){let{r,g,b:b2}=colorToRgb(color),channel=value=>Math.round(value).toString(16).padStart(2,"0");return`#${channel(r)}${channel(g)}${channel(b2)}`}function mixColors(first,second,amount,space="oklch"){if(requireFinite(amount,"amount"),amount<0||amount>1)throw new Error(`amount must be between 0 and 1: ${amount}`);if(space==="srgb"){let a2=colorToRgb(first),b3=colorToRgb(second);return rgbColor(a2.r+(b3.r-a2.r)*amount,a2.g+(b3.g-a2.g)*amount,a2.b+(b3.b-a2.b)*amount)}let a=colorToOklch(first),b2=colorToOklch(second),firstHue=a.c<1e-7?b2.h:a.h,hueDelta=((b2.c<1e-7?firstHue:b2.h)-firstHue+540)%360-180;return oklchColor(a.l+(b2.l-a.l)*amount,a.c+(b2.c-a.c)*amount,firstHue+hueDelta*amount)}function findClosest(values,target){let closestIndex=0,closestDistance=1/0;for(let index=0;index<values.length;index++){let distance=Math.abs(target-values[index]);distance<closestDistance&&(closestIndex=index,closestDistance=distance)}return closestIndex}function colorDistance(first,second){let dr=first.r-second.r,dg=first.g-second.g,db=first.b-second.b;return dr*dr*.299+dg*dg*.587+db*db*.114}function rgbToAnsi256(color){let rIndex=findClosest(CUBE_VALUES,color.r),gIndex=findClosest(CUBE_VALUES,color.g),bIndex=findClosest(CUBE_VALUES,color.b),cubeColor={r:CUBE_VALUES[rIndex],g:CUBE_VALUES[gIndex],b:CUBE_VALUES[bIndex]},cubeIndex=16+36*rIndex+6*gIndex+bIndex,gray=Math.round(.299*color.r+.587*color.g+.114*color.b),grayOffset=findClosest(GRAY_VALUES,gray),grayValue=GRAY_VALUES[grayOffset];return Math.max(color.r,color.g,color.b)-Math.min(color.r,color.g,color.b)<10&&colorDistance(color,{r:grayValue,g:grayValue,b:grayValue})<colorDistance(color,cubeColor)?232+grayOffset:cubeIndex}function colorAnsi(color,mode,background){if(color.kind==="indexed")return`\x1B[${background?48:38};5;${color.index}m`;let rgb=colorToRgb(color);return mode==="truecolor"?`\x1B[${background?48:38};2;${Math.round(rgb.r)};${Math.round(rgb.g)};${Math.round(rgb.b)}m`:`\x1B[${background?48:38};5;${rgbToAnsi256(rgb)}m`}function foregroundAnsi(color,mode){return colorAnsi(color,mode,!1)}function backgroundAnsi(color,mode){return colorAnsi(color,mode,!0)}function styleText(text,options,mode){return styleTextWithAnsi(text,options.fg&&foregroundAnsi(options.fg,mode),options.bg&&backgroundAnsi(options.bg,mode),options)}function styleTextWithAnsi(text,fgAnsi,bgAnsi,options){let prefix="",suffix="";return fgAnsi&&(prefix+=fgAnsi,suffix="\x1B[39m"),bgAnsi&&(prefix+=bgAnsi,suffix=`\x1B[49m${suffix}`),options.bold&&(prefix+="\x1B[1m"),options.dim&&(prefix+="\x1B[2m"),(options.bold||options.dim)&&(suffix=`\x1B[22m${suffix}`),options.italic&&(prefix+="\x1B[3m",suffix=`\x1B[23m${suffix}`),options.underline&&(prefix+="\x1B[4m",suffix=`\x1B[24m${suffix}`),options.inverse&&(prefix+="\x1B[7m",suffix=`\x1B[27m${suffix}`),options.strikethrough&&(prefix+="\x1B[9m",suffix=`\x1B[29m${suffix}`),`${prefix}${text}${suffix}`}var _kittyProtocolActive=!1;function setKittyProtocolActive(active){_kittyProtocolActive=active}function isKittyProtocolActive(){return _kittyProtocolActive}var Key={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:key=>`ctrl+${key}`,shift:key=>`shift+${key}`,alt:key=>`alt+${key}`,super:key=>`super+${key}`,ctrlShift:key=>`ctrl+shift+${key}`,shiftCtrl:key=>`shift+ctrl+${key}`,ctrlAlt:key=>`ctrl+alt+${key}`,altCtrl:key=>`alt+ctrl+${key}`,shiftAlt:key=>`shift+alt+${key}`,altShift:key=>`alt+shift+${key}`,ctrlSuper:key=>`ctrl+super+${key}`,superCtrl:key=>`super+ctrl+${key}`,shiftSuper:key=>`shift+super+${key}`,superShift:key=>`super+shift+${key}`,altSuper:key=>`alt+super+${key}`,superAlt:key=>`super+alt+${key}`,ctrlShiftAlt:key=>`ctrl+shift+alt+${key}`,ctrlShiftSuper:key=>`ctrl+shift+super+${key}`},SYMBOL_KEYS=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),SHIFTED_SYMBOL_KEYS=new Set("~!@#$%^&*()_+|{}:<>?"),MODIFIER_NAMES=["shift","alt","ctrl","super"],MODIFIERS={shift:1,alt:2,ctrl:4,super:8},LOCK_MASK=192,CODEPOINTS={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},ARROW_CODEPOINTS={up:-1,down:-2,right:-3,left:-4},FUNCTIONAL_CODEPOINTS={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},KITTY_FUNCTIONAL_KEY_EQUIVALENTS=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,ARROW_CODEPOINTS.left],[57418,ARROW_CODEPOINTS.right],[57419,ARROW_CODEPOINTS.up],[57420,ARROW_CODEPOINTS.down],[57421,FUNCTIONAL_CODEPOINTS.pageUp],[57422,FUNCTIONAL_CODEPOINTS.pageDown],[57423,FUNCTIONAL_CODEPOINTS.home],[57424,FUNCTIONAL_CODEPOINTS.end],[57425,FUNCTIONAL_CODEPOINTS.insert],[57426,FUNCTIONAL_CODEPOINTS.delete]]);function normalizeKittyFunctionalCodepoint(codepoint){return KITTY_FUNCTIONAL_KEY_EQUIVALENTS.get(codepoint)??codepoint}function normalizeShiftedLetterIdentityCodepoint(codepoint,modifier){return(modifier&~LOCK_MASK&MODIFIERS.shift)!==0&&codepoint>=65&&codepoint<=90?codepoint+32:codepoint}function getLogicalShiftedSymbolCandidate(codepoint,modifier,allowedSymbols){if(codepoint===void 0||(modifier&MODIFIERS.shift)===0)return;let normalizedCodepoint=normalizeKittyFunctionalCodepoint(codepoint);if(allowedSymbols.has(String.fromCharCode(normalizedCodepoint)))return{codepoint:normalizedCodepoint,modifier:modifier&~MODIFIERS.shift}}var LEGACY_KEY_SEQUENCES={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},LEGACY_SHIFT_SEQUENCES={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},LEGACY_CTRL_SEQUENCES={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]},LEGACY_SEQUENCE_KEY_IDS={"\x1BOA":"up","\x1BOB":"down","\x1BOC":"right","\x1BOD":"left","\x1BOH":"home","\x1BOF":"end","\x1B[E":"clear","\x1BOE":"clear","\x1BOe":"ctrl+clear","\x1B[e":"shift+clear","\x1B[2~":"insert","\x1B[2$":"shift+insert","\x1B[2^":"ctrl+insert","\x1B[3$":"shift+delete","\x1B[3^":"ctrl+delete","\x1B[[5~":"pageUp","\x1B[[6~":"pageDown","\x1B[a":"shift+up","\x1B[b":"shift+down","\x1B[c":"shift+right","\x1B[d":"shift+left","\x1BOa":"ctrl+up","\x1BOb":"ctrl+down","\x1BOc":"ctrl+right","\x1BOd":"ctrl+left","\x1B[5$":"shift+pageUp","\x1B[6$":"shift+pageDown","\x1B[7$":"shift+home","\x1B[8$":"shift+end","\x1B[5^":"ctrl+pageUp","\x1B[6^":"ctrl+pageDown","\x1B[7^":"ctrl+home","\x1B[8^":"ctrl+end","\x1BOP":"f1","\x1BOQ":"f2","\x1BOR":"f3","\x1BOS":"f4","\x1B[11~":"f1","\x1B[12~":"f2","\x1B[13~":"f3","\x1B[14~":"f4","\x1B[[A":"f1","\x1B[[B":"f2","\x1B[[C":"f3","\x1B[[D":"f4","\x1B[[E":"f5","\x1B[15~":"f5","\x1B[17~":"f6","\x1B[18~":"f7","\x1B[19~":"f8","\x1B[20~":"f9","\x1B[21~":"f10","\x1B[23~":"f11","\x1B[24~":"f12","\x1Bb":"alt+left","\x1Bf":"alt+right","\x1Bp":"alt+up","\x1Bn":"alt+down"},matchesLegacySequence=(data,sequences)=>sequences.includes(data),matchesLegacyModifierSequence=(data,key,modifier)=>modifier===MODIFIERS.shift?matchesLegacySequence(data,LEGACY_SHIFT_SEQUENCES[key]):modifier===MODIFIERS.ctrl?matchesLegacySequence(data,LEGACY_CTRL_SEQUENCES[key]):!1,_lastEventType="press";function isKeyRelease(data){return data.includes("\x1B[200~")?!1:!!(data.includes(":3u")||data.includes(":3~")||data.includes(":3A")||data.includes(":3B")||data.includes(":3C")||data.includes(":3D")||data.includes(":3H")||data.includes(":3F"))}function isKeyRepeat(data){return data.includes("\x1B[200~")?!1:!!(data.includes(":2u")||data.includes(":2~")||data.includes(":2A")||data.includes(":2B")||data.includes(":2C")||data.includes(":2D")||data.includes(":2H")||data.includes(":2F"))}function parseEventType(eventTypeStr){if(!eventTypeStr)return"press";let eventType=parseInt(eventTypeStr,10);return eventType===2?"repeat":eventType===3?"release":"press"}function parseKittySequence(data){let csiUMatch=data.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(csiUMatch){let codepoint=parseInt(csiUMatch[1],10),shiftedKey=csiUMatch[2]&&csiUMatch[2].length>0?parseInt(csiUMatch[2],10):void 0,baseLayoutKey=csiUMatch[3]?parseInt(csiUMatch[3],10):void 0,modValue=csiUMatch[4]?parseInt(csiUMatch[4],10):1,eventType=parseEventType(csiUMatch[5]);return _lastEventType=eventType,{codepoint,shiftedKey,baseLayoutKey,modifier:modValue-1,eventType}}let arrowMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(arrowMatch){let modValue=parseInt(arrowMatch[1],10),eventType=parseEventType(arrowMatch[2]),arrowCodes={A:-1,B:-2,C:-3,D:-4};return _lastEventType=eventType,{codepoint:arrowCodes[arrowMatch[3]],modifier:modValue-1,eventType}}let funcMatch=data.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(funcMatch){let keyNum=parseInt(funcMatch[1],10),modValue=funcMatch[2]?parseInt(funcMatch[2],10):1,eventType=parseEventType(funcMatch[3]),codepoint={2:FUNCTIONAL_CODEPOINTS.insert,3:FUNCTIONAL_CODEPOINTS.delete,5:FUNCTIONAL_CODEPOINTS.pageUp,6:FUNCTIONAL_CODEPOINTS.pageDown,7:FUNCTIONAL_CODEPOINTS.home,8:FUNCTIONAL_CODEPOINTS.end}[keyNum];if(codepoint!==void 0)return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}let homeEndMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(homeEndMatch){let modValue=parseInt(homeEndMatch[1],10),eventType=parseEventType(homeEndMatch[2]),codepoint=homeEndMatch[3]==="H"?FUNCTIONAL_CODEPOINTS.home:FUNCTIONAL_CODEPOINTS.end;return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}return null}function matchesKittySequence(data,expectedCodepoint,expectedModifier){let parsed=parseKittySequence(data);if(!parsed)return!1;let actualMod=parsed.modifier&~LOCK_MASK,expectedMod=expectedModifier&~LOCK_MASK,normalizedCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(parsed.codepoint),parsed.modifier),normalizedExpectedCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(expectedCodepoint),expectedModifier);if(actualMod===expectedMod&&normalizedCodepoint===normalizedExpectedCodepoint)return!0;let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(parsed.shiftedKey,actualMod,SYMBOL_KEYS);if(logicalShiftedSymbol&&(logicalShiftedSymbol.modifier&~LOCK_MASK)===expectedMod&&logicalShiftedSymbol.codepoint===normalizeKittyFunctionalCodepoint(expectedCodepoint))return!0;if(actualMod!==expectedMod)return!1;if(parsed.baseLayoutKey!==void 0&&parsed.baseLayoutKey===expectedCodepoint){let cp=normalizedCodepoint,isLatinLetter=cp>=97&&cp<=122,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(cp));if(!isLatinLetter&&!isKnownSymbol)return!0}return!1}function parseModifyOtherKeysSequence(data){let match=data.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!match)return null;let modValue=parseInt(match[1],10);return{codepoint:parseInt(match[2],10),modifier:modValue-1}}function matchesModifyOtherKeys(data,expectedKeycode,expectedModifier){let parsed=parseModifyOtherKeysSequence(data);return parsed?parsed.codepoint===expectedKeycode&&parsed.modifier===expectedModifier:!1}function isWindowsTerminalSession(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function matchesRawBackspace(data,expectedModifier){return data==="\x7F"?expectedModifier===0:data!=="\b"?!1:isWindowsTerminalSession()?expectedModifier===MODIFIERS.ctrl:expectedModifier===0}function rawCtrlChar(key){let char=key.toLowerCase(),code=char.charCodeAt(0);return code>=97&&code<=122||char==="["||char==="\\"||char==="]"||char==="_"?String.fromCharCode(code&31):char==="-"?"":null}function isDigitKey(key){return key>="0"&&key<="9"}function matchesPrintableModifyOtherKeys(data,expectedKeycode,expectedModifier){let parsed=parseModifyOtherKeysSequence(data);if(!parsed)return!1;if(parsed.modifier===expectedModifier&&normalizeShiftedLetterIdentityCodepoint(parsed.codepoint,parsed.modifier)===normalizeShiftedLetterIdentityCodepoint(expectedKeycode,expectedModifier))return!0;let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(parsed.codepoint,parsed.modifier,SHIFTED_SYMBOL_KEYS);return logicalShiftedSymbol?.modifier===expectedModifier&&logicalShiftedSymbol.codepoint===expectedKeycode}function formatKeyNameWithModifiers(keyName,modifier){let mods=[],effectiveMod=modifier&~LOCK_MASK,supportedModifierMask=MODIFIERS.shift|MODIFIERS.ctrl|MODIFIERS.alt|MODIFIERS.super;if((effectiveMod&~supportedModifierMask)===0)return effectiveMod&MODIFIERS.shift&&mods.push("shift"),effectiveMod&MODIFIERS.ctrl&&mods.push("ctrl"),effectiveMod&MODIFIERS.alt&&mods.push("alt"),effectiveMod&MODIFIERS.super&&mods.push("super"),mods.length>0?`${mods.join("+")}+${keyName}`:keyName}function parseKeyId(keyId){let key=keyId.toLowerCase(),modifiers=new Set;for(;;){let modifier=MODIFIER_NAMES.find(name=>key.startsWith(`${name}+`));if(!modifier)break;if(modifiers.has(modifier))return null;modifiers.add(modifier),key=key.slice(modifier.length+1)}return!key||key.includes("+")&&key!=="+"?null:{key,ctrl:modifiers.has("ctrl"),shift:modifiers.has("shift"),alt:modifiers.has("alt"),super:modifiers.has("super")}}function matchesKey(data,keyId){let parsed=parseKeyId(keyId);if(!parsed)return!1;let{key,ctrl,shift,alt,super:superModifier}=parsed,modifier=0;switch(shift&&(modifier|=MODIFIERS.shift),alt&&(modifier|=MODIFIERS.alt),ctrl&&(modifier|=MODIFIERS.ctrl),superModifier&&(modifier|=MODIFIERS.super),key){case"escape":case"esc":return modifier!==0?!1:data==="\x1B"||matchesKittySequence(data,CODEPOINTS.escape,0)||matchesModifyOtherKeys(data,CODEPOINTS.escape,0);case"space":return!_kittyProtocolActive&&(modifier===MODIFIERS.ctrl&&data==="\0"||modifier===MODIFIERS.alt&&data==="\x1B ")?!0:modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.space,0)||matchesModifyOtherKeys(data,CODEPOINTS.space,0):matchesKittySequence(data,CODEPOINTS.space,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.space,modifier);case"tab":return modifier===MODIFIERS.shift?data==="\x1B[Z"||matchesKittySequence(data,CODEPOINTS.tab,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.tab,MODIFIERS.shift):modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.tab,0):matchesKittySequence(data,CODEPOINTS.tab,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.tab,modifier);case"enter":case"return":return modifier===MODIFIERS.shift?matchesKittySequence(data,CODEPOINTS.enter,MODIFIERS.shift)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.shift)?!0:_kittyProtocolActive?data==="\x1B\r"||data===`
|
|
2
|
+
import{source_default}from"./chunk-6QGV3IWD.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-LHRPMXVI.js";import{require_bash,require_c,require_core,require_cpp,require_csharp,require_dart,require_go,require_groovy,require_java,require_javascript,require_json,require_kotlin,require_lua,require_nix,require_perl,require_php,require_python,require_ruby,require_rust,require_scala,require_swift,require_typescript}from"./chunk-5AGIVGSV.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,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,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,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,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var isInRange=(ranges,codePoint)=>{let low=0,high=Math.floor(ranges.length/2)-1;for(;low<=high;){let mid=Math.floor((low+high)/2),i=mid*2;if(codePoint<ranges[i])high=mid-1;else if(codePoint>ranges[i+1])low=mid+1;else return!0}return!1};var commonCjkCodePoint=19968,[wideFastPathStart,wideFastPathEnd]=findWideFastPathRange(wideRanges);function findWideFastPathRange(ranges){let fastPathStart=ranges[0],fastPathEnd=ranges[1];for(let index=0;index<ranges.length;index+=2){let start=ranges[index],end=ranges[index+1];if(commonCjkCodePoint>=start&&commonCjkCodePoint<=end)return[start,end];end-start>fastPathEnd-fastPathStart&&(fastPathStart=start,fastPathEnd=end)}return[fastPathStart,fastPathEnd]}var isAmbiguous=codePoint=>codePoint<161||codePoint>1114109?!1:isInRange(ambiguousRanges,codePoint),isFullWidth=codePoint=>codePoint<fullwidthMinimalCodePoint||codePoint>fullwidthMaximumCodePoint?!1:isInRange(fullwidthRanges,codePoint);var isWide=codePoint=>codePoint>=wideFastPathStart&&codePoint<=wideFastPathEnd?!0:codePoint<wideMinimalCodePoint||codePoint>wideMaximumCodePoint?!1:isInRange(wideRanges,codePoint);function validate(codePoint){if(!Number.isSafeInteger(codePoint))throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`)}function eastAsianWidth(codePoint,{ambiguousAsWide=!1}={}){return validate(codePoint),isFullWidth(codePoint)||isWide(codePoint)||ambiguousAsWide&&isAmbiguous(codePoint)?2:1}var graphemeSegmenter=new Intl.Segmenter(void 0,{granularity:"grapheme"}),wordSegmenter=new Intl.Segmenter(void 0,{granularity:"word"});function getGraphemeSegmenter(){return graphemeSegmenter}function getWordSegmenter(){return wordSegmenter}function couldBeEmoji(segment){let cp=segment.codePointAt(0);return cp>=126976&&cp<=130047||cp>=8960&&cp<=9215||cp>=9728&&cp<=10175||cp>=11088&&cp<=11093||segment.includes("\uFE0F")||segment.length>2}var zeroWidthRegex=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),leadingNonPrintingRegex=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),nonPrintingCharRegex=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$","v"),markCharRegex=new RegExp("^\\p{Mark}$","v"),terminalSpacingMarkRegex=new RegExp("^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$","v"),rgiEmojiRegex=new RegExp("^\\p{RGI_Emoji}$","v"),WIDTH_CACHE_SIZE=512,widthCache=new Map,cjkBreakRegex=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,cjkPunctuationRegex=new RegExp(`(?:(?=\\p{Punctuation})${cjkBreakRegex.source}|[\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\uFF3B\uFF3D\uFF5B\uFF5D\u201C\u201D\u2018\u2019\u2026\u2014])`,"u"),autocompleteSeparatorRegex=new RegExp(`(?:\\s|${cjkPunctuationRegex.source})`,"u"),autocompleteBoundaryRegex=new RegExp(`(?:^|${autocompleteSeparatorRegex.source})`,"u");function isPrintableAscii(str){for(let i=0;i<str.length;i++){let code=str.charCodeAt(i);if(code<32||code>126)return!1}return!0}function truncateFragmentToWidth(text,maxWidth){if(maxWidth<=0||text.length===0)return{text:"",width:0};if(isPrintableAscii(text)){let clipped=text.slice(0,maxWidth);return{text:clipped,width:clipped.length}}let hasAnsi=text.includes("\x1B"),hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){let result2="",width2=0;for(let{segment}of graphemeSegmenter.segment(text)){let w=graphemeWidth(segment);if(width2+w>maxWidth)break;result2+=segment,width2+=w}return{text:result2,width:width2}}let result="",width=0,i=0,pendingAnsi="";for(;i<text.length;){let ansi=extractAnsiCode(text,i);if(ansi){pendingAnsi+=ansi.code,i+=ansi.length;continue}if(text[i]===" "){if(width+3>maxWidth)break;pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=" ",width+=3,i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&!extractAnsiCode(text,end);)end++;for(let{segment}of graphemeSegmenter.segment(text.slice(i,end))){let w=graphemeWidth(segment);if(width+w>maxWidth)return{text:result,width};pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,width+=w}i=end}return{text:result,width}}function finalizeTruncatedResult(prefix,prefixWidth,ellipsis,ellipsisWidth,maxWidth,pad){let reset="\x1B[0m",hyperlinkClose=getActiveOsc8Close(prefix),visibleWidth2=prefixWidth+ellipsisWidth,result;return ellipsis.length>0?result=`${prefix}${hyperlinkClose}${reset}${ellipsis}${reset}`:result=`${prefix}${hyperlinkClose}${reset}`,pad?result+" ".repeat(Math.max(0,maxWidth-visibleWidth2)):result}function graphemeWidth(segment){if(segment.length===1){let code=segment.charCodeAt(0);if(code>=32&&code<=126)return 1;if(code===9)return 3}if(terminalSpacingMarkRegex.test(segment))return[...segment].length;if(zeroWidthRegex.test(segment))return 0;if(couldBeEmoji(segment)&&rgiEmojiRegex.test(segment))return 2;let base=segment.replace(leadingNonPrintingRegex,""),cp=base.codePointAt(0);if(cp===void 0)return 0;if(cp>=127462&&cp<=127487)return 2;let width=eastAsianWidth(cp),followsMark=!1,chars=[...base];for(let char of chars.slice(1))if(terminalSpacingMarkRegex.test(char))width+=1,followsMark=!1;else if(markCharRegex.test(char))followsMark=!0;else if(!nonPrintingCharRegex.test(char)){let c2=char.codePointAt(0);followsMark||c2>=65280&&c2<=65519?width+=eastAsianWidth(c2):(c2===3635||c2===3763)&&(width+=1),followsMark=!1}return width}function visibleWidth(str){if(str.length===0)return 0;let asciiWidth=asciiVisibleWidth(str);if(asciiWidth!==-1)return asciiWidth;let cached=widthCache.get(str);if(cached!==void 0)return cached;let clean=str;str.includes(" ")&&(clean=clean.replace(/\t/g," "));let escapeIndex=clean.indexOf("\x1B");if(escapeIndex!==-1){let stripped="",copyFrom=0;for(;escapeIndex!==-1;){let length=ansiCodeLength(clean,escapeIndex);length>0?(stripped+=clean.slice(copyFrom,escapeIndex),escapeIndex+=length,copyFrom=escapeIndex):escapeIndex++,escapeIndex=clean.indexOf("\x1B",escapeIndex)}clean=stripped+clean.slice(copyFrom)}let width=0;for(let{segment}of graphemeSegmenter.segment(clean))width+=graphemeWidth(segment);if(widthCache.size>=WIDTH_CACHE_SIZE){let firstKey=widthCache.keys().next().value;firstKey!==void 0&&widthCache.delete(firstKey)}return widthCache.set(str,width),width}function stripTerminalSequences(str){if(!str.includes("\x1B"))return str;let result="",i=0;for(;i<str.length;){let ansi=extractAnsiCode(str,i);if(ansi){i+=ansi.length;continue}result+=str[i],i++}return result}function getGraphemeCellRange(line,column){let currentCol=0,i=0;for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let width=graphemeWidth(segment);if(width>0&&column>=currentCol&&column<currentCol+width)return{start:currentCol,end:currentCol+width};currentCol+=width}i=textEnd}}function getOsc8LinkAtColumn(line,column){let activeUrl,currentCol=0,i=0;for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){let hyperlink2=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(ansi.code);hyperlink2&&(activeUrl=hyperlink2[1]||void 0),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let width=segment===" "?3:graphemeWidth(segment);if(column>=currentCol&&column<currentCol+width)return activeUrl;currentCol+=width}i=textEnd}}var THAI_LAO_AM_REGEX=/[\u0e33\u0eb3]/,THAI_LAO_AM_GLOBAL_REGEX=/[\u0e33\u0eb3]/g;function normalizeTerminalOutput(str){let normalized=str;if(THAI_LAO_AM_REGEX.test(normalized)&&(normalized=normalized.replace(THAI_LAO_AM_GLOBAL_REGEX,char=>char==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2")),!normalized.includes(" "))return normalized;let result="",i=0;for(;i<normalized.length;){let ansi=extractAnsiCode(normalized,i);if(ansi){result+=ansi.code,i+=ansi.length;continue}result+=normalized[i]===" "?" ":normalized[i],i++}return result}function extractAnsiCode(str,pos){let length=ansiCodeLength(str,pos);return length>0?{code:str.substring(pos,pos+length),length}:null}function asciiVisibleWidth(str){let width=0,i=0;for(;i<str.length;){let code=str.charCodeAt(i);if(code>=32&&code<=126)width++,i++;else if(code===9)width+=3,i++;else if(code===27){let length=ansiCodeLength(str,i);if(length===0)return-1;i+=length}else return-1}return width}function ansiCodeLength(str,pos){if(pos>=str.length||str.charCodeAt(pos)!==27)return 0;let next=str[pos+1];if(next==="["){for(let j2=pos+2;j2<str.length;j2++){let c2=str.charCodeAt(j2);if(c2===109||c2===71||c2===75||c2===72||c2===74)return j2+1-pos}return 0}if(next==="]"||next==="_"){for(let j2=pos+2;j2<str.length;j2++){let c2=str.charCodeAt(j2);if(c2===7)return j2+1-pos;if(c2===27&&str[j2+1]==="\\")return j2+2-pos}return 0}return 0}function parseOsc8Hyperlink(ansiCode){if(!ansiCode.startsWith("\x1B]8;"))return;let terminator=ansiCode.endsWith("\x07")?"\x07":"\x1B\\",body=ansiCode.slice(4,terminator==="\x07"?-1:-2),separatorIndex=body.indexOf(";");if(separatorIndex===-1)return;let params=body.slice(0,separatorIndex),url=body.slice(separatorIndex+1);return url?{params,url,terminator}:null}function formatOsc8Hyperlink(hyperlink2){return`\x1B]8;${hyperlink2.params};${hyperlink2.url}${hyperlink2.terminator}`}function formatOsc8Close(terminator){return`\x1B]8;;${terminator}`}function getActiveOsc8Close(prefix){if(!prefix.includes("\x1B]8;"))return"";let activeHyperlink=null,i=0;for(;i<prefix.length;){let ansi=extractAnsiCode(prefix,i);if(ansi){let hyperlink2=parseOsc8Hyperlink(ansi.code);hyperlink2!==void 0&&(activeHyperlink=hyperlink2),i+=ansi.length}else i++}return activeHyperlink?formatOsc8Close(activeHyperlink.terminator):""}var AnsiCodeTracker=class{bold=!1;dim=!1;italic=!1;underline=!1;blink=!1;inverse=!1;hidden=!1;strikethrough=!1;fgColor=null;bgColor=null;activeHyperlink=null;process(ansiCode){let hyperlink2=parseOsc8Hyperlink(ansiCode);if(hyperlink2!==void 0){this.activeHyperlink=hyperlink2;return}if(!ansiCode.endsWith("m"))return;let match=ansiCode.match(/\x1b\[([\d;]*)m/);if(!match)return;let params=match[1];if(params===""||params==="0"){this.reset();return}let parts=params.split(";"),i=0;for(;i<parts.length;){let code=Number.parseInt(parts[i],10);if(code===38||code===48){if(parts[i+1]==="5"&&parts[i+2]!==void 0){let colorCode=`${parts[i]};${parts[i+1]};${parts[i+2]}`;code===38?this.fgColor=colorCode:this.bgColor=colorCode,i+=3;continue}else if(parts[i+1]==="2"&&parts[i+4]!==void 0){let colorCode=`${parts[i]};${parts[i+1]};${parts[i+2]};${parts[i+3]};${parts[i+4]}`;code===38?this.fgColor=colorCode:this.bgColor=colorCode,i+=5;continue}}switch(code){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:code>=30&&code<=37||code>=90&&code<=97?this.fgColor=String(code):(code>=40&&code<=47||code>=100&&code<=107)&&(this.bgColor=String(code));break}i++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let codes=[];this.bold&&codes.push("1"),this.dim&&codes.push("2"),this.italic&&codes.push("3"),this.underline&&codes.push("4"),this.blink&&codes.push("5"),this.inverse&&codes.push("7"),this.hidden&&codes.push("8"),this.strikethrough&&codes.push("9"),this.fgColor&&codes.push(this.fgColor),this.bgColor&&codes.push(this.bgColor);let result=codes.length>0?`\x1B[${codes.join(";")}m`:"";return this.activeHyperlink&&(result+=formatOsc8Hyperlink(this.activeHyperlink)),result}getActiveBackgroundCode(){return this.bgColor?`\x1B[${this.bgColor}m`:""}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let result="";return this.underline&&(result+="\x1B[24m"),this.activeHyperlink&&(result+=formatOsc8Close(this.activeHyperlink.terminator)),result}};function updateTrackerFromText(text,tracker){let i=text.indexOf("\x1B");for(;i!==-1;){let length=ansiCodeLength(text,i);length>0?(tracker.process(text.substring(i,i+length)),i+=length):i++,i=text.indexOf("\x1B",i)}}function getActiveBackgroundAnsi(text){let tracker=new AnsiCodeTracker;return updateTrackerFromText(text,tracker),tracker.getActiveBackgroundCode()}function*graphemeSegments(text){for(let{segment}of graphemeSegmenter.segment(text))yield segment}function splitIntoTokensWithAnsi(text){let tokens=[],current="",pendingAnsi="",currentKind=null,i=0,flushCurrent=()=>{current&&(tokens.push(current),current="",currentKind=null)};for(;i<text.length;){let ansiResult=extractAnsiCode(text,i);if(ansiResult){pendingAnsi+=ansiResult.code,i+=ansiResult.length;continue}let end=text.indexOf("\x1B",i+1);for(;end!==-1&&ansiCodeLength(text,end)===0;)end=text.indexOf("\x1B",end+1);end===-1&&(end=text.length);let chunk=text.slice(i,end),ascii=isPrintableAscii(chunk);for(let segment of ascii?chunk:graphemeSegments(chunk)){let segmentIsSpace=segment===" ";if(!ascii&&!segmentIsSpace&&cjkBreakRegex.test(segment)){flushCurrent();let token=pendingAnsi+segment;pendingAnsi="",tokens.push(token);continue}let segmentKind=segmentIsSpace?"space":"word";current&¤tKind!==segmentKind&&flushCurrent(),pendingAnsi&&(current+=pendingAnsi,pendingAnsi=""),currentKind=segmentKind,current+=segment}i=end}return pendingAnsi&&(current?current+=pendingAnsi:tokens.length>0?tokens[tokens.length-1]+=pendingAnsi:current=pendingAnsi),current&&tokens.push(current),tokens}function flattenLines(lines){for(let line of lines)Number(line)}function wrapTextWithAnsi(text,width){if(!text)return[""];let inputLines=text.split(/\r\n|\r|\n/),result=[],tracker=new AnsiCodeTracker;for(let inputLine of inputLines){let prefix=result.length>0?tracker.getActiveCodes():"",wrappedLines=wrapSingleLine(prefix+inputLine,width);for(let wrappedLine of wrappedLines)result.push(wrappedLine);updateTrackerFromText(inputLine,tracker)}return result.length>0?result:[""]}function wrapSingleLine(line,width){if(!line)return[""];if(visibleWidth(line)<=width)return[line];let wrapped=[],tracker=new AnsiCodeTracker,tokens=splitIntoTokensWithAnsi(line),currentLine="",currentVisibleLength=0;for(let token of tokens){let tokenVisibleLength=visibleWidth(token),isWhitespace=token.trim()==="";if(tokenVisibleLength>width&&!isWhitespace){if(currentLine){let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),wrapped.push(currentLine),currentLine="",currentVisibleLength=0}let broken=breakLongWord(token,width,tracker);for(let i=0;i<broken.length-1;i++)wrapped.push(broken[i]);currentLine=broken[broken.length-1],currentVisibleLength=visibleWidth(currentLine);continue}if(currentVisibleLength+tokenVisibleLength>width&¤tVisibleLength>0){let lineToWrap=currentLine.trimEnd(),lineEndReset=tracker.getLineEndReset();lineEndReset&&(lineToWrap+=lineEndReset),wrapped.push(lineToWrap),isWhitespace?(currentLine=tracker.getActiveCodes(),currentVisibleLength=0):(currentLine=tracker.getActiveCodes()+token,currentVisibleLength=tokenVisibleLength)}else currentLine+=token,currentVisibleLength+=tokenVisibleLength;updateTrackerFromText(token,tracker)}return currentLine&&wrapped.push(currentLine),wrapped.length>0?wrapped.map(line2=>line2.trimEnd()):[""]}var PUNCTUATION_REGEX=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function isWhitespaceChar(char){return/\s/.test(char)}function breakLongWord(word,width,tracker){let lines=[],currentLine=tracker.getActiveCodes(),currentWidth=0,i=0,segments=[];for(;i<word.length;){let ansiResult=extractAnsiCode(word,i);if(ansiResult)segments.push({type:"ansi",value:ansiResult.code}),i+=ansiResult.length;else{let end=i;for(;end<word.length&&!extractAnsiCode(word,end);)end++;let textPortion=word.slice(i,end);for(let seg of graphemeSegmenter.segment(textPortion))segments.push({type:"grapheme",value:seg.segment});i=end}}for(let seg of segments){if(seg.type==="ansi"){currentLine+=seg.value,tracker.process(seg.value);continue}let grapheme=seg.value;if(!grapheme)continue;let graphemeWidth2=visibleWidth(grapheme);if(currentWidth+graphemeWidth2>width){let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),lines.push(currentLine),currentLine=tracker.getActiveCodes(),currentWidth=0}currentLine+=grapheme,currentWidth+=graphemeWidth2}return currentLine&&lines.push(currentLine),lines.length>0?lines:[""]}function applyBackgroundToLine(line,width,bgFn){let visibleLen=visibleWidth(line),paddingNeeded=Math.max(0,width-visibleLen),padding=" ".repeat(paddingNeeded),withPadding=line+padding;return bgFn(withPadding)}function truncateToWidth(text,maxWidth,ellipsis="...",pad=!1){if(maxWidth<=0)return"";if(text.length===0)return pad?" ".repeat(maxWidth):"";let ellipsisWidth=visibleWidth(ellipsis);if(ellipsisWidth>=maxWidth){let textWidth=visibleWidth(text);if(textWidth<=maxWidth)return pad?text+" ".repeat(maxWidth-textWidth):text;let clippedEllipsis=truncateFragmentToWidth(ellipsis,maxWidth);return clippedEllipsis.width===0?pad?" ".repeat(maxWidth):"":finalizeTruncatedResult("",0,clippedEllipsis.text,clippedEllipsis.width,maxWidth,pad)}if(isPrintableAscii(text)){if(text.length<=maxWidth)return pad?text+" ".repeat(maxWidth-text.length):text;let targetWidth2=maxWidth-ellipsisWidth;return finalizeTruncatedResult(text.slice(0,targetWidth2),targetWidth2,ellipsis,ellipsisWidth,maxWidth,pad)}let targetWidth=maxWidth-ellipsisWidth,result="",pendingAnsi="",visibleSoFar=0,keptWidth=0,keepContiguousPrefix=!0,overflowed=!1,exhaustedInput=!1,hasAnsi=text.includes("\x1B"),hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){for(let{segment}of graphemeSegmenter.segment(text)){let width=graphemeWidth(segment);if(keepContiguousPrefix&&keptWidth+width<=targetWidth?(result+=segment,keptWidth+=width):keepContiguousPrefix=!1,visibleSoFar+=width,visibleSoFar>maxWidth){overflowed=!0;break}}exhaustedInput=!overflowed}else{let i=0;for(;i<text.length;){let ansi=extractAnsiCode(text,i);if(ansi){pendingAnsi+=ansi.code,i+=ansi.length;continue}if(text[i]===" "){if(keepContiguousPrefix&&keptWidth+3<=targetWidth?(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=" ",keptWidth+=3):(keepContiguousPrefix=!1,pendingAnsi=""),visibleSoFar+=3,visibleSoFar>maxWidth){overflowed=!0;break}i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&!extractAnsiCode(text,end);)end++;for(let{segment}of graphemeSegmenter.segment(text.slice(i,end))){let width=graphemeWidth(segment);if(keepContiguousPrefix&&keptWidth+width<=targetWidth?(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,keptWidth+=width):(keepContiguousPrefix=!1,pendingAnsi=""),visibleSoFar+=width,visibleSoFar>maxWidth){overflowed=!0;break}}if(overflowed)break;i=end}exhaustedInput=i>=text.length}return!overflowed&&exhaustedInput?pad?text+" ".repeat(Math.max(0,maxWidth-visibleSoFar)):text:finalizeTruncatedResult(result,keptWidth,ellipsis,ellipsisWidth,maxWidth,pad)}function sliceByColumn(line,startCol,length,strict=!1){return sliceWithWidth(line,startCol,length,strict).text}function sliceWithWidth(line,startCol,length,strict=!1){if(length<=0)return{text:"",width:0};let endCol=startCol+length,result="",resultWidth=0,currentCol=0,i=0,pendingAnsi="";for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){currentCol>=startCol&¤tCol<endCol?(result+=pendingAnsi+ansi.code,pendingAnsi=""):currentCol<startCol&&(pendingAnsi+=ansi.code),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let w=graphemeWidth(segment),inRange=currentCol>=startCol&¤tCol<endCol,fits=!strict||currentCol+w<=endCol;if(inRange&&fits&&(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,resultWidth+=w),currentCol+=w,currentCol>=endCol)break}if(i=textEnd,currentCol>=endCol)break}return{text:result,width:resultWidth}}var pooledStyleTracker=new AnsiCodeTracker;function extractSegments(line,beforeEnd,afterStart,afterLen,strictAfter=!1){let before="",beforeWidth=0,after="",afterWidth=0,currentCol=0,i=0,pendingAnsiBefore="",afterStarted=!1,afterEnd=afterStart+afterLen;for(pooledStyleTracker.clear();i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){pooledStyleTracker.process(ansi.code),currentCol<beforeEnd?pendingAnsiBefore+=ansi.code:currentCol>=afterStart&¤tCol<afterEnd&&(afterStarted||ansi.code.startsWith("\x1B_"))&&(after+=ansi.code),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let w=graphemeWidth(segment);if(currentCol<beforeEnd&¤tCol+w<=beforeEnd?(pendingAnsiBefore&&(before+=pendingAnsiBefore,pendingAnsiBefore=""),before+=segment,beforeWidth+=w):currentCol>=afterStart&¤tCol<afterEnd&&(!strictAfter||currentCol+w<=afterEnd)&&(afterStarted||(after+=pooledStyleTracker.getActiveCodes(),afterStarted=!0),after+=segment,afterWidth+=w),currentCol+=w,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}if(i=textEnd,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}return{before,beforeWidth,after,afterWidth}}var multiply=(m2,[x2,y2,z2])=>m2.map(row=>row[0]*x2+row[1]*y2+row[2]*z2),LINEAR_SRGB_TO_LMS=[[.4122214694707629,.5363325372617349,.0514459932675022],[.2119034958178251,.6806995506452344,.1073969535369405],[.0883024591900564,.2817188391361215,.6299787016738222]],LMS_TO_LAB=[[.210454268309314,.793617774702305,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],LAB_TO_LMS=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],LMS_TO_LINEAR_SRGB=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-.341319376002657],[-.0041960761386756,-.7034186179359362,1.7076146940746117]],SATURATION_FIT=[[[-1.8817031,-.80936501],[1.19086277,1.76576728,.59662641,.75515197,.56771245]],[[1.8144408,-1.19445267],[.73956515,-.45954404,.08285427,.12541073,-.14503204]],[[.13110758,1.81333971],[1.35733652,-.00915799,-1.1513021,-.50559606,.00692167]]],K1=.206,K2=.03,K3=(1+K1)/(1+K2),oklabToOkhslLightness=x2=>.5*(K3*x2-K1+Math.sqrt((K3*x2-K1)**2+4*K2*K3*x2)),okhslToOklabLightness=x2=>(x2*x2+K1*x2)/(K3*(x2+K2)),linearToSrgb=value=>value>.0031308?1.055*value**(1/2.4)-.055:12.92*value,srgbToLinear=value=>value<=.04045?value/12.92:((value+.055)/1.055)**2.4;function oklabToLinearSrgb(lab){return multiply(LMS_TO_LINEAR_SRGB,multiply(LAB_TO_LMS,lab).map(value=>value**3))}function linearSrgbToOklab(rgb){return multiply(LMS_TO_LAB,multiply(LINEAR_SRGB_TO_LMS,rgb).map(Math.cbrt))}function rgbToOklab({r,g,b:b2}){return linearSrgbToOklab([r/255,g/255,b2/255].map(srgbToLinear))}function linearSrgbToRgb(linear){let[r,g,b2]=linear.map(value=>Math.round(Math.min(1,Math.max(0,linearToSrgb(value)))*255));return{r,g,b:b2}}function lmsSlopes(a,b2){return[LAB_TO_LMS[0],LAB_TO_LMS[1],LAB_TO_LMS[2]].map(row=>row[1]*a+row[2]*b2)}function maxSaturation(a,b2){let channel=SATURATION_FIT.findIndex(([[x2,y2]],index)=>index===2||x2*a+y2*b2>1),[k0,k1,k2,k3,k4]=SATURATION_FIT[channel][1],weights=LMS_TO_LINEAR_SRGB[channel],saturation=k0+k1*a+k2*b2+k3*a*a+k4*a*b2,slopes=lmsSlopes(a,b2),base=slopes.map(k5=>1+saturation*k5),dot=values=>values.reduce((sum,value,index)=>sum+weights[index]*value,0),f2=dot(base.map(value=>value**3)),f1=dot(base.map((value,index)=>3*slopes[index]*value**2)),f22=dot(base.map((value,index)=>6*slopes[index]**2*value));return saturation-f2*f1/(f1*f1-.5*f2*f22)}function cusp(a,b2){let saturation=maxSaturation(a,b2),lightness=Math.cbrt(1/Math.max(...oklabToLinearSrgb([1,saturation*a,saturation*b2])));return[lightness,lightness*saturation]}function maxChroma(a,b2,lightness,[cuspL,cuspC]){if(lightness<=cuspL)return cuspC*lightness/cuspL;let t=cuspC*(lightness-1)/(cuspL-1),slopes=lmsSlopes(a,b2),lms=slopes.map(k2=>lightness+t*k2),cubes=lms.map(value=>value**3),first=lms.map((value,index)=>3*slopes[index]*value**2),second=lms.map((value,index)=>6*slopes[index]**2*value),dot=(row,values)=>row[0]*values[0]+row[1]*values[1]+row[2]*values[2],steps=LMS_TO_LINEAR_SRGB.map(row=>{let f2=dot(row,cubes)-1,f1=dot(row,first),f22=dot(row,second),u=f1/(f1*f1-.5*f2*f22);return u>=0?-f2*u:Number.MAX_VALUE});return t+Math.min(...steps)}function chromaStops(L2,a,b2){let peak=cusp(a,b2),cMax=maxChroma(a,b2,L2,peak),k2=cMax/Math.min(L2*(peak[1]/peak[0]),(1-L2)*(peak[1]/(1-peak[0]))),midS=.11516993+1/(7.4477897+4.1590124*b2+a*(-2.19557347+1.75198401*b2+a*(-2.13704948-10.02301043*b2+a*(-4.24894561+5.38770819*b2+4.69891013*a)))),midT=.11239642+1/(1.6132032-.68124379*b2+a*(.40370612+.90148123*b2+a*(-.27087943+.6122399*b2+a*(.00299215-.45399568*b2-.14661872*a)))),cMid=.9*k2*Math.sqrt(Math.sqrt(1/(1/(L2*midS)**4+1/((1-L2)*midT)**4)));return[Math.sqrt(1/(1/(L2*.4)**2+1/((1-L2)*.8)**2)),cMid,cMax]}function okhslToRgb(hue,saturation,lightness){let L2=okhslToOklabLightness(lightness),lab=[L2,0,0];if(L2>0&&L2<1&&saturation>0){let angle=2*Math.PI*((hue%360+360)%360)/360,a=Math.cos(angle),b2=Math.sin(angle),[c0,cMid,cMax]=chromaStops(L2,a,b2),chroma;if(saturation<.8){let t=1.25*saturation,k1=.8*c0;chroma=t*k1/(1-(1-k1/cMid)*t)}else{let t=5*(saturation-.8),k1=.2*cMid**2*1.25**2/c0;chroma=cMid+t*k1/(1-(1-k1/(cMax-cMid))*t)}lab=[L2,chroma*a,chroma*b2]}return linearSrgbToRgb(oklabToLinearSrgb(lab))}function rgbToOkhsl(rgb){let[L2,labA,labB]=rgbToOklab(rgb),chroma=Math.hypot(labA,labB),lightness=oklabToOkhslLightness(L2);if(chroma<1e-9||lightness<=0||lightness>=1)return{h:0,s:0,l:lightness};let hue=(Math.atan2(labB,labA)*180/Math.PI+360)%360,[c0,cMid,cMax]=chromaStops(L2,labA/chroma,labB/chroma),saturation;if(chroma<cMid){let k1=.8*c0;saturation=.8*(chroma/(k1+(1-k1/cMid)*chroma))}else{let k1=.2*cMid**2*1.5625/c0,offset=chroma-cMid;saturation=.8+.2*(offset/(k1+(1-k1/(cMax-cMid))*offset))}return{h:hue,s:Math.min(1,Math.max(0,saturation)),l:lightness}}function requireFinite(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function indexedColor(index){if(!Number.isInteger(index)||index<0||index>255)throw new Error(`ANSI color index must be an integer from 0 to 255: ${index}`);return Object.freeze({kind:"indexed",index})}function rgbColor(r,g,b2){for(let[name,value]of[["r",r],["g",g],["b",b2]])if(requireFinite(value,name),value<0||value>255)throw new Error(`${name} must be between 0 and 255: ${value}`);return Object.freeze({kind:"rgb",r,g,b:b2})}function oklchColor(l3,c2,h){if(requireFinite(l3,"l"),requireFinite(c2,"c"),requireFinite(h,"h"),l3<0||l3>1)throw new Error(`l must be between 0 and 1: ${l3}`);if(c2<0)throw new Error(`c must not be negative: ${c2}`);return Object.freeze({kind:"oklch",l:l3,c:c2,h:(h%360+360)%360})}var NUMBER_PATTERN=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,OKLCH_PATTERN=new RegExp(`^oklch\\(\\s*(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})\\s+(${NUMBER_PATTERN})(?:deg)?\\s*\\)$`,"i"),OKHSL_PATTERN=new RegExp(`^okhsl\\(\\s*(${NUMBER_PATTERN})(?:deg)?\\s+(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})(%)?\\s*\\)$`,"i");function okhslColor(h,s,l3){if(requireFinite(h,"h"),requireFinite(s,"s"),requireFinite(l3,"l"),s<0||s>1)throw new Error(`s must be between 0 and 1: ${s}`);if(l3<0||l3>1)throw new Error(`l must be between 0 and 1: ${l3}`);let{r,g,b:b2}=okhslToRgb(h,s,l3);return rgbColor(r,g,b2)}function colorToOkhsl(color){return rgbToOkhsl(colorToRgb(color))}function parseColor(value){if(typeof value=="number")return indexedColor(value);let hex=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(value);if(hex){let digits=hex[1].length===3?[...hex[1]].map(digit=>digit+digit).join(""):hex[1];return rgbColor(Number.parseInt(digits.slice(0,2),16),Number.parseInt(digits.slice(2,4),16),Number.parseInt(digits.slice(4,6),16))}let oklch=OKLCH_PATTERN.exec(value);if(oklch){let lightness=Number.parseFloat(oklch[1])/(oklch[2]?100:1);return oklchColor(lightness,Number.parseFloat(oklch[3]),Number.parseFloat(oklch[4]))}let okhsl=OKHSL_PATTERN.exec(value);if(okhsl){let saturation=Number.parseFloat(okhsl[2])/(okhsl[3]?100:1),lightness=Number.parseFloat(okhsl[4])/(okhsl[5]?100:1);return okhslColor(Number.parseFloat(okhsl[1]),saturation,lightness)}throw new Error(`Invalid color value: ${value}`)}var BASIC_COLORS=[{r:0,g:0,b:0},{r:128,g:0,b:0},{r:0,g:128,b:0},{r:128,g:128,b:0},{r:0,g:0,b:128},{r:128,g:0,b:128},{r:0,g:128,b:128},{r:192,g:192,b:192},{r:128,g:128,b:128},{r:255,g:0,b:0},{r:0,g:255,b:0},{r:255,g:255,b:0},{r:0,g:0,b:255},{r:255,g:0,b:255},{r:0,g:255,b:255},{r:255,g:255,b:255}],CUBE_VALUES=[0,95,135,175,215,255],GRAY_VALUES=Array.from({length:24},(_2,index)=>8+index*10);function indexedToRgb(index){if(index<16)return{...BASIC_COLORS[index]};if(index<232){let cubeIndex=index-16;return{r:CUBE_VALUES[Math.floor(cubeIndex/36)],g:CUBE_VALUES[Math.floor(cubeIndex%36/6)],b:CUBE_VALUES[cubeIndex%6]}}let gray=8+(index-232)*10;return{r:gray,g:gray,b:gray}}function isInSrgbGamut(linear){return linear.every(channel=>channel>=-1e-7&&channel<=1+1e-7)}function oklchToRgb({l:l3,c:c2,h}){let radians=h*Math.PI/180,cos=Math.cos(radians),sin=Math.sin(radians),atChroma=chroma=>oklabToLinearSrgb([l3,chroma*cos,chroma*sin]),direct=atChroma(c2);if(isInSrgbGamut(direct))return linearSrgbToRgb(direct);let linear=atChroma(0),low=0,high=c2;for(let index=0;index<20;index++){let chroma=(low+high)/2,candidate=atChroma(chroma);isInSrgbGamut(candidate)?(low=chroma,linear=candidate):high=chroma}return linearSrgbToRgb(linear)}function colorToRgb(color){switch(color.kind){case"indexed":return indexedToRgb(color.index);case"rgb":return{r:color.r,g:color.g,b:color.b};case"oklch":return oklchToRgb(color)}}function colorToOklch(color){if(color.kind==="oklch")return{l:color.l,c:color.c,h:color.h};let[l3,a,b2]=rgbToOklab(colorToRgb(color));return{l:l3,c:Math.hypot(a,b2),h:(Math.atan2(b2,a)*180/Math.PI+360)%360}}function colorToHex(color){let{r,g,b:b2}=colorToRgb(color),channel=value=>Math.round(value).toString(16).padStart(2,"0");return`#${channel(r)}${channel(g)}${channel(b2)}`}function mixColors(first,second,amount,space="oklch"){if(requireFinite(amount,"amount"),amount<0||amount>1)throw new Error(`amount must be between 0 and 1: ${amount}`);if(space==="srgb"){let a2=colorToRgb(first),b3=colorToRgb(second);return rgbColor(a2.r+(b3.r-a2.r)*amount,a2.g+(b3.g-a2.g)*amount,a2.b+(b3.b-a2.b)*amount)}let a=colorToOklch(first),b2=colorToOklch(second),firstHue=a.c<1e-7?b2.h:a.h,hueDelta=((b2.c<1e-7?firstHue:b2.h)-firstHue+540)%360-180;return oklchColor(a.l+(b2.l-a.l)*amount,a.c+(b2.c-a.c)*amount,firstHue+hueDelta*amount)}function findClosest(values,target){let closestIndex=0,closestDistance=1/0;for(let index=0;index<values.length;index++){let distance=Math.abs(target-values[index]);distance<closestDistance&&(closestIndex=index,closestDistance=distance)}return closestIndex}function colorDistance(first,second){let dr=first.r-second.r,dg=first.g-second.g,db=first.b-second.b;return dr*dr*.299+dg*dg*.587+db*db*.114}function rgbToAnsi256(color){let rIndex=findClosest(CUBE_VALUES,color.r),gIndex=findClosest(CUBE_VALUES,color.g),bIndex=findClosest(CUBE_VALUES,color.b),cubeColor={r:CUBE_VALUES[rIndex],g:CUBE_VALUES[gIndex],b:CUBE_VALUES[bIndex]},cubeIndex=16+36*rIndex+6*gIndex+bIndex,gray=Math.round(.299*color.r+.587*color.g+.114*color.b),grayOffset=findClosest(GRAY_VALUES,gray),grayValue=GRAY_VALUES[grayOffset];return Math.max(color.r,color.g,color.b)-Math.min(color.r,color.g,color.b)<10&&colorDistance(color,{r:grayValue,g:grayValue,b:grayValue})<colorDistance(color,cubeColor)?232+grayOffset:cubeIndex}function colorAnsi(color,mode,background){if(color.kind==="indexed")return`\x1B[${background?48:38};5;${color.index}m`;let rgb=colorToRgb(color);return mode==="truecolor"?`\x1B[${background?48:38};2;${Math.round(rgb.r)};${Math.round(rgb.g)};${Math.round(rgb.b)}m`:`\x1B[${background?48:38};5;${rgbToAnsi256(rgb)}m`}function foregroundAnsi(color,mode){return colorAnsi(color,mode,!1)}function backgroundAnsi(color,mode){return colorAnsi(color,mode,!0)}function styleText(text,options,mode){return styleTextWithAnsi(text,options.fg&&foregroundAnsi(options.fg,mode),options.bg&&backgroundAnsi(options.bg,mode),options)}function styleTextWithAnsi(text,fgAnsi,bgAnsi,options){let prefix="",suffix="";return fgAnsi&&(prefix+=fgAnsi,suffix="\x1B[39m"),bgAnsi&&(prefix+=bgAnsi,suffix=`\x1B[49m${suffix}`),options.bold&&(prefix+="\x1B[1m"),options.dim&&(prefix+="\x1B[2m"),(options.bold||options.dim)&&(suffix=`\x1B[22m${suffix}`),options.italic&&(prefix+="\x1B[3m",suffix=`\x1B[23m${suffix}`),options.underline&&(prefix+="\x1B[4m",suffix=`\x1B[24m${suffix}`),options.inverse&&(prefix+="\x1B[7m",suffix=`\x1B[27m${suffix}`),options.strikethrough&&(prefix+="\x1B[9m",suffix=`\x1B[29m${suffix}`),`${prefix}${text}${suffix}`}var _kittyProtocolActive=!1;function setKittyProtocolActive(active){_kittyProtocolActive=active}function isKittyProtocolActive(){return _kittyProtocolActive}var Key={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:key=>`ctrl+${key}`,shift:key=>`shift+${key}`,alt:key=>`alt+${key}`,super:key=>`super+${key}`,ctrlShift:key=>`ctrl+shift+${key}`,shiftCtrl:key=>`shift+ctrl+${key}`,ctrlAlt:key=>`ctrl+alt+${key}`,altCtrl:key=>`alt+ctrl+${key}`,shiftAlt:key=>`shift+alt+${key}`,altShift:key=>`alt+shift+${key}`,ctrlSuper:key=>`ctrl+super+${key}`,superCtrl:key=>`super+ctrl+${key}`,shiftSuper:key=>`shift+super+${key}`,superShift:key=>`super+shift+${key}`,altSuper:key=>`alt+super+${key}`,superAlt:key=>`super+alt+${key}`,ctrlShiftAlt:key=>`ctrl+shift+alt+${key}`,ctrlShiftSuper:key=>`ctrl+shift+super+${key}`},SYMBOL_KEYS=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),SHIFTED_SYMBOL_KEYS=new Set("~!@#$%^&*()_+|{}:<>?"),MODIFIER_NAMES=["shift","alt","ctrl","super"],MODIFIERS={shift:1,alt:2,ctrl:4,super:8},LOCK_MASK=192,CODEPOINTS={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},ARROW_CODEPOINTS={up:-1,down:-2,right:-3,left:-4},FUNCTIONAL_CODEPOINTS={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},KITTY_FUNCTIONAL_KEY_EQUIVALENTS=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,ARROW_CODEPOINTS.left],[57418,ARROW_CODEPOINTS.right],[57419,ARROW_CODEPOINTS.up],[57420,ARROW_CODEPOINTS.down],[57421,FUNCTIONAL_CODEPOINTS.pageUp],[57422,FUNCTIONAL_CODEPOINTS.pageDown],[57423,FUNCTIONAL_CODEPOINTS.home],[57424,FUNCTIONAL_CODEPOINTS.end],[57425,FUNCTIONAL_CODEPOINTS.insert],[57426,FUNCTIONAL_CODEPOINTS.delete]]);function normalizeKittyFunctionalCodepoint(codepoint){return KITTY_FUNCTIONAL_KEY_EQUIVALENTS.get(codepoint)??codepoint}function normalizeShiftedLetterIdentityCodepoint(codepoint,modifier){return(modifier&~LOCK_MASK&MODIFIERS.shift)!==0&&codepoint>=65&&codepoint<=90?codepoint+32:codepoint}function getLogicalShiftedSymbolCandidate(codepoint,modifier,allowedSymbols){if(codepoint===void 0||(modifier&MODIFIERS.shift)===0)return;let normalizedCodepoint=normalizeKittyFunctionalCodepoint(codepoint);if(allowedSymbols.has(String.fromCharCode(normalizedCodepoint)))return{codepoint:normalizedCodepoint,modifier:modifier&~MODIFIERS.shift}}var LEGACY_KEY_SEQUENCES={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},LEGACY_SHIFT_SEQUENCES={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},LEGACY_CTRL_SEQUENCES={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]},LEGACY_SEQUENCE_KEY_IDS={"\x1BOA":"up","\x1BOB":"down","\x1BOC":"right","\x1BOD":"left","\x1BOH":"home","\x1BOF":"end","\x1B[E":"clear","\x1BOE":"clear","\x1BOe":"ctrl+clear","\x1B[e":"shift+clear","\x1B[2~":"insert","\x1B[2$":"shift+insert","\x1B[2^":"ctrl+insert","\x1B[3$":"shift+delete","\x1B[3^":"ctrl+delete","\x1B[[5~":"pageUp","\x1B[[6~":"pageDown","\x1B[a":"shift+up","\x1B[b":"shift+down","\x1B[c":"shift+right","\x1B[d":"shift+left","\x1BOa":"ctrl+up","\x1BOb":"ctrl+down","\x1BOc":"ctrl+right","\x1BOd":"ctrl+left","\x1B[5$":"shift+pageUp","\x1B[6$":"shift+pageDown","\x1B[7$":"shift+home","\x1B[8$":"shift+end","\x1B[5^":"ctrl+pageUp","\x1B[6^":"ctrl+pageDown","\x1B[7^":"ctrl+home","\x1B[8^":"ctrl+end","\x1BOP":"f1","\x1BOQ":"f2","\x1BOR":"f3","\x1BOS":"f4","\x1B[11~":"f1","\x1B[12~":"f2","\x1B[13~":"f3","\x1B[14~":"f4","\x1B[[A":"f1","\x1B[[B":"f2","\x1B[[C":"f3","\x1B[[D":"f4","\x1B[[E":"f5","\x1B[15~":"f5","\x1B[17~":"f6","\x1B[18~":"f7","\x1B[19~":"f8","\x1B[20~":"f9","\x1B[21~":"f10","\x1B[23~":"f11","\x1B[24~":"f12","\x1Bb":"alt+left","\x1Bf":"alt+right","\x1Bp":"alt+up","\x1Bn":"alt+down"},matchesLegacySequence=(data,sequences)=>sequences.includes(data),matchesLegacyModifierSequence=(data,key,modifier)=>modifier===MODIFIERS.shift?matchesLegacySequence(data,LEGACY_SHIFT_SEQUENCES[key]):modifier===MODIFIERS.ctrl?matchesLegacySequence(data,LEGACY_CTRL_SEQUENCES[key]):!1,_lastEventType="press";function isKeyRelease(data){return data.includes("\x1B[200~")?!1:!!(data.includes(":3u")||data.includes(":3~")||data.includes(":3A")||data.includes(":3B")||data.includes(":3C")||data.includes(":3D")||data.includes(":3H")||data.includes(":3F"))}function isKeyRepeat(data){return data.includes("\x1B[200~")?!1:!!(data.includes(":2u")||data.includes(":2~")||data.includes(":2A")||data.includes(":2B")||data.includes(":2C")||data.includes(":2D")||data.includes(":2H")||data.includes(":2F"))}function parseEventType(eventTypeStr){if(!eventTypeStr)return"press";let eventType=parseInt(eventTypeStr,10);return eventType===2?"repeat":eventType===3?"release":"press"}function parseKittySequence(data){let csiUMatch=data.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(csiUMatch){let codepoint=parseInt(csiUMatch[1],10),shiftedKey=csiUMatch[2]&&csiUMatch[2].length>0?parseInt(csiUMatch[2],10):void 0,baseLayoutKey=csiUMatch[3]?parseInt(csiUMatch[3],10):void 0,modValue=csiUMatch[4]?parseInt(csiUMatch[4],10):1,eventType=parseEventType(csiUMatch[5]);return _lastEventType=eventType,{codepoint,shiftedKey,baseLayoutKey,modifier:modValue-1,eventType}}let arrowMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(arrowMatch){let modValue=parseInt(arrowMatch[1],10),eventType=parseEventType(arrowMatch[2]),arrowCodes={A:-1,B:-2,C:-3,D:-4};return _lastEventType=eventType,{codepoint:arrowCodes[arrowMatch[3]],modifier:modValue-1,eventType}}let funcMatch=data.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(funcMatch){let keyNum=parseInt(funcMatch[1],10),modValue=funcMatch[2]?parseInt(funcMatch[2],10):1,eventType=parseEventType(funcMatch[3]),codepoint={2:FUNCTIONAL_CODEPOINTS.insert,3:FUNCTIONAL_CODEPOINTS.delete,5:FUNCTIONAL_CODEPOINTS.pageUp,6:FUNCTIONAL_CODEPOINTS.pageDown,7:FUNCTIONAL_CODEPOINTS.home,8:FUNCTIONAL_CODEPOINTS.end}[keyNum];if(codepoint!==void 0)return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}let homeEndMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(homeEndMatch){let modValue=parseInt(homeEndMatch[1],10),eventType=parseEventType(homeEndMatch[2]),codepoint=homeEndMatch[3]==="H"?FUNCTIONAL_CODEPOINTS.home:FUNCTIONAL_CODEPOINTS.end;return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}return null}function matchesKittySequence(data,expectedCodepoint,expectedModifier){let parsed=parseKittySequence(data);if(!parsed)return!1;let actualMod=parsed.modifier&~LOCK_MASK,expectedMod=expectedModifier&~LOCK_MASK,normalizedCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(parsed.codepoint),parsed.modifier),normalizedExpectedCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(expectedCodepoint),expectedModifier);if(actualMod===expectedMod&&normalizedCodepoint===normalizedExpectedCodepoint)return!0;let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(parsed.shiftedKey,actualMod,SYMBOL_KEYS);if(logicalShiftedSymbol&&(logicalShiftedSymbol.modifier&~LOCK_MASK)===expectedMod&&logicalShiftedSymbol.codepoint===normalizeKittyFunctionalCodepoint(expectedCodepoint))return!0;if(actualMod!==expectedMod)return!1;if(parsed.baseLayoutKey!==void 0&&parsed.baseLayoutKey===expectedCodepoint){let cp=normalizedCodepoint,isLatinLetter=cp>=97&&cp<=122,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(cp));if(!isLatinLetter&&!isKnownSymbol)return!0}return!1}function parseModifyOtherKeysSequence(data){let match=data.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!match)return null;let modValue=parseInt(match[1],10);return{codepoint:parseInt(match[2],10),modifier:modValue-1}}function matchesModifyOtherKeys(data,expectedKeycode,expectedModifier){let parsed=parseModifyOtherKeysSequence(data);return parsed?parsed.codepoint===expectedKeycode&&parsed.modifier===expectedModifier:!1}function isWindowsTerminalSession(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function matchesRawBackspace(data,expectedModifier){return data==="\x7F"?expectedModifier===0:data!=="\b"?!1:isWindowsTerminalSession()?expectedModifier===MODIFIERS.ctrl:expectedModifier===0}function rawCtrlChar(key){let char=key.toLowerCase(),code=char.charCodeAt(0);return code>=97&&code<=122||char==="["||char==="\\"||char==="]"||char==="_"?String.fromCharCode(code&31):char==="-"?"":null}function isDigitKey(key){return key>="0"&&key<="9"}function matchesPrintableModifyOtherKeys(data,expectedKeycode,expectedModifier){let parsed=parseModifyOtherKeysSequence(data);if(!parsed)return!1;if(parsed.modifier===expectedModifier&&normalizeShiftedLetterIdentityCodepoint(parsed.codepoint,parsed.modifier)===normalizeShiftedLetterIdentityCodepoint(expectedKeycode,expectedModifier))return!0;let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(parsed.codepoint,parsed.modifier,SHIFTED_SYMBOL_KEYS);return logicalShiftedSymbol?.modifier===expectedModifier&&logicalShiftedSymbol.codepoint===expectedKeycode}function formatKeyNameWithModifiers(keyName,modifier){let mods=[],effectiveMod=modifier&~LOCK_MASK,supportedModifierMask=MODIFIERS.shift|MODIFIERS.ctrl|MODIFIERS.alt|MODIFIERS.super;if((effectiveMod&~supportedModifierMask)===0)return effectiveMod&MODIFIERS.shift&&mods.push("shift"),effectiveMod&MODIFIERS.ctrl&&mods.push("ctrl"),effectiveMod&MODIFIERS.alt&&mods.push("alt"),effectiveMod&MODIFIERS.super&&mods.push("super"),mods.length>0?`${mods.join("+")}+${keyName}`:keyName}function parseKeyId(keyId){let key=keyId.toLowerCase(),modifiers=new Set;for(;;){let modifier=MODIFIER_NAMES.find(name=>key.startsWith(`${name}+`));if(!modifier)break;if(modifiers.has(modifier))return null;modifiers.add(modifier),key=key.slice(modifier.length+1)}return!key||key.includes("+")&&key!=="+"?null:{key,ctrl:modifiers.has("ctrl"),shift:modifiers.has("shift"),alt:modifiers.has("alt"),super:modifiers.has("super")}}function matchesKey(data,keyId){let parsed=parseKeyId(keyId);if(!parsed)return!1;let{key,ctrl,shift,alt,super:superModifier}=parsed,modifier=0;switch(shift&&(modifier|=MODIFIERS.shift),alt&&(modifier|=MODIFIERS.alt),ctrl&&(modifier|=MODIFIERS.ctrl),superModifier&&(modifier|=MODIFIERS.super),key){case"escape":case"esc":return modifier!==0?!1:data==="\x1B"||matchesKittySequence(data,CODEPOINTS.escape,0)||matchesModifyOtherKeys(data,CODEPOINTS.escape,0);case"space":return!_kittyProtocolActive&&(modifier===MODIFIERS.ctrl&&data==="\0"||modifier===MODIFIERS.alt&&data==="\x1B ")?!0:modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.space,0)||matchesModifyOtherKeys(data,CODEPOINTS.space,0):matchesKittySequence(data,CODEPOINTS.space,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.space,modifier);case"tab":return modifier===MODIFIERS.shift?data==="\x1B[Z"||matchesKittySequence(data,CODEPOINTS.tab,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.tab,MODIFIERS.shift):modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.tab,0):matchesKittySequence(data,CODEPOINTS.tab,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.tab,modifier);case"enter":case"return":return modifier===MODIFIERS.shift?matchesKittySequence(data,CODEPOINTS.enter,MODIFIERS.shift)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.shift)?!0:_kittyProtocolActive?data==="\x1B\r"||data===`
|
|
3
3
|
`:!1:modifier===MODIFIERS.alt?matchesKittySequence(data,CODEPOINTS.enter,MODIFIERS.alt)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.alt)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.alt)?!0:_kittyProtocolActive?!1:data==="\x1B\r":modifier===0?data==="\r"||!_kittyProtocolActive&&data===`
|
|
4
4
|
`||data==="\x1BOM"||matchesKittySequence(data,CODEPOINTS.enter,0)||matchesKittySequence(data,CODEPOINTS.kpEnter,0):matchesKittySequence(data,CODEPOINTS.enter,modifier)||matchesKittySequence(data,CODEPOINTS.kpEnter,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.enter,modifier);case"backspace":return modifier===MODIFIERS.alt?data==="\x1B\x7F"||data==="\x1B\b"?!0:matchesKittySequence(data,CODEPOINTS.backspace,MODIFIERS.alt)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,MODIFIERS.alt):modifier===MODIFIERS.ctrl?matchesRawBackspace(data,MODIFIERS.ctrl)?!0:matchesKittySequence(data,CODEPOINTS.backspace,MODIFIERS.ctrl)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,MODIFIERS.ctrl):modifier===0?matchesRawBackspace(data,0)||matchesKittySequence(data,CODEPOINTS.backspace,0)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,0):matchesKittySequence(data,CODEPOINTS.backspace,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,modifier);case"insert":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.insert)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.insert,0):matchesLegacyModifierSequence(data,"insert",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.insert,modifier);case"delete":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.delete)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.delete,0):matchesLegacyModifierSequence(data,"delete",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.delete,modifier);case"clear":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.clear):matchesLegacyModifierSequence(data,"clear",modifier);case"home":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.home)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.home,0):matchesLegacyModifierSequence(data,"home",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.home,modifier);case"end":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.end)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.end,0):matchesLegacyModifierSequence(data,"end",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.end,modifier);case"pageup":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.pageUp)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageUp,0):matchesLegacyModifierSequence(data,"pageUp",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageUp,modifier);case"pagedown":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.pageDown)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageDown,0):matchesLegacyModifierSequence(data,"pageDown",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageDown,modifier);case"up":return modifier===MODIFIERS.alt?data==="\x1Bp"||matchesKittySequence(data,ARROW_CODEPOINTS.up,MODIFIERS.alt):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.up)||matchesKittySequence(data,ARROW_CODEPOINTS.up,0):matchesLegacyModifierSequence(data,"up",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.up,modifier);case"down":return modifier===MODIFIERS.alt?data==="\x1Bn"||matchesKittySequence(data,ARROW_CODEPOINTS.down,MODIFIERS.alt):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.down)||matchesKittySequence(data,ARROW_CODEPOINTS.down,0):matchesLegacyModifierSequence(data,"down",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.down,modifier);case"left":return modifier===MODIFIERS.alt?data==="\x1B[1;3D"||!_kittyProtocolActive&&data==="\x1BB"||data==="\x1Bb"||matchesKittySequence(data,ARROW_CODEPOINTS.left,MODIFIERS.alt):modifier===MODIFIERS.ctrl?data==="\x1B[1;5D"||matchesLegacyModifierSequence(data,"left",MODIFIERS.ctrl)||matchesKittySequence(data,ARROW_CODEPOINTS.left,MODIFIERS.ctrl):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.left)||matchesKittySequence(data,ARROW_CODEPOINTS.left,0):matchesLegacyModifierSequence(data,"left",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.left,modifier);case"right":return modifier===MODIFIERS.alt?data==="\x1B[1;3C"||!_kittyProtocolActive&&data==="\x1BF"||data==="\x1Bf"||matchesKittySequence(data,ARROW_CODEPOINTS.right,MODIFIERS.alt):modifier===MODIFIERS.ctrl?data==="\x1B[1;5C"||matchesLegacyModifierSequence(data,"right",MODIFIERS.ctrl)||matchesKittySequence(data,ARROW_CODEPOINTS.right,MODIFIERS.ctrl):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.right)||matchesKittySequence(data,ARROW_CODEPOINTS.right,0):matchesLegacyModifierSequence(data,"right",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.right,modifier);case"f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":return modifier!==0?!1:matchesLegacySequence(data,LEGACY_KEY_SEQUENCES[key])}if(key.length===1&&(key>="a"&&key<="z"||isDigitKey(key)||SYMBOL_KEYS.has(key))){let codepoint=key.charCodeAt(0),rawCtrl=rawCtrlChar(key),isLetter=key>="a"&&key<="z",isDigit=isDigitKey(key);return modifier===MODIFIERS.ctrl+MODIFIERS.alt&&!_kittyProtocolActive&&rawCtrl&&data===`\x1B${rawCtrl}`||modifier===MODIFIERS.alt&&!_kittyProtocolActive&&(isLetter||isDigit||SYMBOL_KEYS.has(key))&&data===`\x1B${key}`?!0:modifier===MODIFIERS.ctrl?rawCtrl&&data===rawCtrl?!0:matchesKittySequence(data,codepoint,MODIFIERS.ctrl)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.ctrl):modifier===MODIFIERS.shift+MODIFIERS.ctrl?matchesKittySequence(data,codepoint,MODIFIERS.shift+MODIFIERS.ctrl)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.shift+MODIFIERS.ctrl):modifier===MODIFIERS.shift?isLetter&&data===key.toUpperCase()?!0:matchesKittySequence(data,codepoint,MODIFIERS.shift)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.shift):modifier!==0?matchesKittySequence(data,codepoint,modifier)||matchesPrintableModifyOtherKeys(data,codepoint,modifier):data===key||matchesKittySequence(data,codepoint,0)||matchesPrintableModifyOtherKeys(data,codepoint,0)}return!1}function formatParsedKey(codepoint,modifier,baseLayoutKey){let normalizedCodepoint=normalizeKittyFunctionalCodepoint(codepoint),identityCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizedCodepoint,modifier),isLatinLetter=identityCodepoint>=97&&identityCodepoint<=122,isDigit=identityCodepoint>=48&&identityCodepoint<=57,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(identityCodepoint)),effectiveCodepoint=isLatinLetter||isDigit||isKnownSymbol?identityCodepoint:baseLayoutKey??identityCodepoint,keyName;if(effectiveCodepoint===CODEPOINTS.escape?keyName="escape":effectiveCodepoint===CODEPOINTS.tab?keyName="tab":effectiveCodepoint===CODEPOINTS.enter||effectiveCodepoint===CODEPOINTS.kpEnter?keyName="enter":effectiveCodepoint===CODEPOINTS.space?keyName="space":effectiveCodepoint===CODEPOINTS.backspace?keyName="backspace":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.delete?keyName="delete":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.insert?keyName="insert":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.home?keyName="home":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.end?keyName="end":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.pageUp?keyName="pageUp":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.pageDown?keyName="pageDown":effectiveCodepoint===ARROW_CODEPOINTS.up?keyName="up":effectiveCodepoint===ARROW_CODEPOINTS.down?keyName="down":effectiveCodepoint===ARROW_CODEPOINTS.left?keyName="left":effectiveCodepoint===ARROW_CODEPOINTS.right?keyName="right":(effectiveCodepoint>=48&&effectiveCodepoint<=57||effectiveCodepoint>=97&&effectiveCodepoint<=122||SYMBOL_KEYS.has(String.fromCharCode(effectiveCodepoint)))&&(keyName=String.fromCharCode(effectiveCodepoint)),!!keyName)return formatKeyNameWithModifiers(keyName,modifier)}function parseKey(data){let kitty=parseKittySequence(data);if(kitty){let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(kitty.shiftedKey,kitty.modifier,SYMBOL_KEYS);return formatParsedKey(logicalShiftedSymbol?.codepoint??kitty.codepoint,logicalShiftedSymbol?.modifier??kitty.modifier,kitty.baseLayoutKey)}let modifyOtherKeys=parseModifyOtherKeysSequence(data);if(modifyOtherKeys){let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(modifyOtherKeys.codepoint,modifyOtherKeys.modifier,SHIFTED_SYMBOL_KEYS);return formatParsedKey(logicalShiftedSymbol?.codepoint??modifyOtherKeys.codepoint,logicalShiftedSymbol?.modifier??modifyOtherKeys.modifier)}if(_kittyProtocolActive&&(data==="\x1B\r"||data===`
|
|
5
5
|
`))return"shift+enter";let legacySequenceKeyId=LEGACY_SEQUENCE_KEY_IDS[data];if(legacySequenceKeyId)return legacySequenceKeyId;if(data==="\x1B")return"escape";if(data==="")return"ctrl+\\";if(data==="")return"ctrl+]";if(data==="")return"ctrl+-";if(data==="\x1B\x1B")return"ctrl+alt+[";if(data==="\x1B")return"ctrl+alt+\\";if(data==="\x1B")return"ctrl+alt+]";if(data==="\x1B")return"ctrl+alt+-";if(data===" ")return"tab";if(data==="\r"||!_kittyProtocolActive&&data===`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{getShellConfig}from"./chunk-
|
|
2
|
+
import{getShellConfig}from"./chunk-URBBMV3M.js";import{getAgentDir,getFileRevision,normalizePath,require_cross_spawn,stripBom}from"./chunk-LHRPMXVI.js";import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_polyfills=__commonJS({"node_modules/graceful-fs/polyfills.js"(exports,module){var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return cwd||(cwd=origCwd.call(process)),cwd};try{process.cwd()}catch{}typeof process.chdir=="function"&&(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,chdir));var chdir;module.exports=patch;function patch(fs){constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&patchLchmod(fs),fs.lutimes||patchLutimes(fs),fs.chown=chownFix(fs.chown),fs.fchown=chownFix(fs.fchown),fs.lchown=chownFix(fs.lchown),fs.chmod=chmodFix(fs.chmod),fs.fchmod=chmodFix(fs.fchmod),fs.lchmod=chmodFix(fs.lchmod),fs.chownSync=chownFixSync(fs.chownSync),fs.fchownSync=chownFixSync(fs.fchownSync),fs.lchownSync=chownFixSync(fs.lchownSync),fs.chmodSync=chmodFixSync(fs.chmodSync),fs.fchmodSync=chmodFixSync(fs.fchmodSync),fs.lchmodSync=chmodFixSync(fs.lchmodSync),fs.stat=statFix(fs.stat),fs.fstat=statFix(fs.fstat),fs.lstat=statFix(fs.lstat),fs.statSync=statFixSync(fs.statSync),fs.fstatSync=statFixSync(fs.fstatSync),fs.lstatSync=statFixSync(fs.lstatSync),fs.chmod&&!fs.lchmod&&(fs.lchmod=function(path,mode,cb){cb&&process.nextTick(cb)},fs.lchmodSync=function(){}),fs.chown&&!fs.lchown&&(fs.lchown=function(path,uid,gid,cb){cb&&process.nextTick(cb)},fs.lchownSync=function(){}),platform==="win32"&&(fs.rename=typeof fs.rename!="function"?fs.rename:(function(fs$rename){function rename(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<6e4){setTimeout(function(){fs.stat(to,function(stater,st){stater&&stater.code==="ENOENT"?fs$rename(from,to,CB):cb(er)})},backoff),backoff<100&&(backoff+=10);return}cb&&cb(er)})}return Object.setPrototypeOf&&Object.setPrototypeOf(rename,fs$rename),rename})(fs.rename)),fs.read=typeof fs.read!="function"?fs.read:(function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_=="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs,fd,buffer,offset,length,position,callback)}return Object.setPrototypeOf&&Object.setPrototypeOf(read,fs$read),read})(fs.read),fs.readSync=typeof fs.readSync!="function"?fs.readSync:(function(fs$readSync){return function(fd,buffer,offset,length,position){for(var eagCounter=0;;)try{return fs$readSync.call(fs,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}})(fs.readSync);function patchLchmod(fs2){fs2.lchmod=function(path,mode,callback){fs2.open(path,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){callback&&callback(err);return}fs2.fchmod(fd,mode,function(err2){fs2.close(fd,function(err22){callback&&callback(err2||err22)})})})},fs2.lchmodSync=function(path,mode){var fd=fs2.openSync(path,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs2.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}}function patchLutimes(fs2){constants.hasOwnProperty("O_SYMLINK")&&fs2.futimes?(fs2.lutimes=function(path,at,mt,cb){fs2.open(path,constants.O_SYMLINK,function(er,fd){if(er){cb&&cb(er);return}fs2.futimes(fd,at,mt,function(er2){fs2.close(fd,function(er22){cb&&cb(er2||er22)})})})},fs2.lutimesSync=function(path,at,mt){var fd=fs2.openSync(path,constants.O_SYMLINK),ret,threw=!0;try{ret=fs2.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}):fs2.futimes&&(fs2.lutimes=function(_a,_b,_c,cb){cb&&process.nextTick(cb)},fs2.lutimesSync=function(){})}function chmodFix(orig){return orig&&function(target,mode,cb){return orig.call(fs,target,mode,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chmodFixSync(orig){return orig&&function(target,mode){try{return orig.call(fs,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){return orig&&function(target,uid,gid,cb){return orig.call(fs,target,uid,gid,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chownFixSync(orig){return orig&&function(target,uid,gid){try{return orig.call(fs,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){return orig&&function(target,options,cb){typeof options=="function"&&(cb=options,options=null);function callback(er,stats){stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),cb&&cb.apply(this,arguments)}return options?orig.call(fs,target,options,callback):orig.call(fs,target,callback)}}function statFixSync(orig){return orig&&function(target,options){var stats=options?orig.call(fs,target,options):orig.call(fs,target);return stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),stats}}function chownErOk(er){if(!er||er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;return!!(nonroot&&(er.code==="EINVAL"||er.code==="EPERM"))}}}});var require_legacy_streams=__commonJS({"node_modules/graceful-fs/legacy-streams.js"(exports,module){var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs){return{ReadStream,WriteStream};function ReadStream(path,options){if(!(this instanceof ReadStream))return new ReadStream(path,options);Stream.call(this);var self=this;this.path=path,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path,options){if(!(this instanceof WriteStream))return new WriteStream(path,options);Stream.call(this),this.path=path,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=fs.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}}});var require_clone=__commonJS({"node_modules/graceful-fs/clone.js"(exports,module){"use strict";module.exports=clone;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone(obj){if(obj===null||typeof obj!="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}}});var require_graceful_fs=__commonJS({"node_modules/graceful-fs/graceful-fs.js"(exports,module){var fs=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;typeof Symbol=="function"&&typeof Symbol.for=="function"?(gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous")):(gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous");function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;util.debuglog?debug=util.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
|
|
3
3
|
GFS4: `),console.error(m)});fs[gracefulQueue]||(queue=global[gracefulQueue]||[],publishQueue(fs,queue),fs.close=(function(fs$close){function close(fd,cb){return fs$close.call(fs,fd,function(err){err||resetQueue(),typeof cb=="function"&&cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close})(fs.close),fs.closeSync=(function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync})(fs.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){debug(fs[gracefulQueue]),__require("assert").equal(fs[gracefulQueue].length,0)}));var queue;global[gracefulQueue]||publishQueue(global,fs[gracefulQueue]);module.exports=patch(clone(fs));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs.__patched&&(module.exports=patch(fs),fs.__patched=!0);function patch(fs2){polyfills(fs2),fs2.gracefulify=patch,fs2.createReadStream=createReadStream,fs2.createWriteStream=createWriteStream;var fs$readFile=fs2.readFile;fs2.readFile=readFile;function readFile(path,options,cb){return typeof options=="function"&&(cb=options,options=null),go$readFile(path,options,cb);function go$readFile(path2,options2,cb2,startTime){return fs$readFile(path2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readFile,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$writeFile=fs2.writeFile;fs2.writeFile=writeFile;function writeFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$writeFile(path,data,options,cb);function go$writeFile(path2,data2,options2,cb2,startTime){return fs$writeFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$writeFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$appendFile=fs2.appendFile;fs$appendFile&&(fs2.appendFile=appendFile);function appendFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$appendFile(path,data,options,cb);function go$appendFile(path2,data2,options2,cb2,startTime){return fs$appendFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$appendFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$copyFile=fs2.copyFile;fs$copyFile&&(fs2.copyFile=copyFile);function copyFile(src,dest,flags,cb){return typeof flags=="function"&&(cb=flags,flags=0),go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$readdir=fs2.readdir;fs2.readdir=readdir;var noReaddirOptionVersions=/^v[0-5]\./;function readdir(path,options,cb){typeof options=="function"&&(cb=options,options=null);var go$readdir=noReaddirOptionVersions.test(process.version)?function(path2,options2,cb2,startTime){return fs$readdir(path2,fs$readdirCallback(path2,options2,cb2,startTime))}:function(path2,options2,cb2,startTime){return fs$readdir(path2,options2,fs$readdirCallback(path2,options2,cb2,startTime))};return go$readdir(path,options,cb);function fs$readdirCallback(path2,options2,cb2,startTime){return function(err,files){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readdir,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):(files&&files.sort&&files.sort(),typeof cb2=="function"&&cb2.call(this,err,files))}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs2);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs2.ReadStream;fs$ReadStream&&(ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open);var fs$WriteStream=fs2.WriteStream;fs$WriteStream&&(WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open),Object.defineProperty(fs2,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs2,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs2,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs2,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path,options){return this instanceof ReadStream?(fs$ReadStream.apply(this,arguments),this):ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.autoClose&&that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd),that.read())})}function WriteStream(path,options){return this instanceof WriteStream?(fs$WriteStream.apply(this,arguments),this):WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd))})}function createReadStream(path,options){return new fs2.ReadStream(path,options)}function createWriteStream(path,options){return new fs2.WriteStream(path,options)}var fs$open=fs2.open;fs2.open=open;function open(path,flags,mode,cb){return typeof mode=="function"&&(cb=mode,mode=null),go$open(path,flags,mode,cb);function go$open(path2,flags2,mode2,cb2,startTime){return fs$open(path2,flags2,mode2,function(err,fd){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$open,[path2,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}return fs2}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){for(var now=Date.now(),i=0;i<fs[gracefulQueue].length;++i)fs[gracefulQueue][i].length>2&&(fs[gracefulQueue][i][3]=now,fs[gracefulQueue][i][4]=now);retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs[gracefulQueue].length!==0){var elem=fs[gracefulQueue].shift(),fn=elem[0],args=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn.name,args),fn.apply(null,args);else if(Date.now()-startTime>=6e4){debug("TIMEOUT",fn.name,args);var cb=args.pop();typeof cb=="function"&&cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);sinceAttempt>=desiredDelay?(debug("RETRY",fn.name,args),fn.apply(null,args.concat([startTime]))):fs[gracefulQueue].push(elem)}retryTimer===void 0&&(retryTimer=setTimeout(retry,0))}}}});var require_retry_operation=__commonJS({"node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){self._attempts++,self._operationTimeoutCb&&(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref&&self._timeout.unref()),self._fn(self._attempts)},timeout);return this._options.unref&&timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/proper-lockfile/node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/proper-lockfile/node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_signals=__commonJS({"node_modules/signal-exit/signals.js"(exports,module){module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}});var require_signal_exit=__commonJS({"node_modules/signal-exit/index.js"(exports,module){var process3=global.process,processOk=function(process4){return process4&&typeof process4=="object"&&typeof process4.removeListener=="function"&&typeof process4.emit=="function"&&typeof process4.reallyExit=="function"&&typeof process4.listeners=="function"&&typeof process4.kill=="function"&&typeof process4.pid=="number"&&typeof process4.on=="function"};processOk(process3)?(assert=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!="function"&&(EE=EE.EventEmitter),process3.__signal_exit_emitter__?emitter=process3.__signal_exit_emitter__:(emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={}),emitter.infinite||(emitter.setMaxListeners(1/0),emitter.infinite=!0),module.exports=function(cb,opts){if(!processOk(global.process))return function(){};assert.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1&&load();var ev="exit";opts&&opts.alwaysLast&&(ev="afterexit");var remove=function(){emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0&&unload()};return emitter.on(ev,cb),remove},unload=function(){!loaded||!processOk(global.process)||(loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch{}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1)},module.exports.unload=unload,emit=function(event,code,signal){emitter.emitted[event]||(emitter.emitted[event]=!0,emitter.emit(event,code,signal))},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(processOk(global.process)){var listeners=process3.listeners(sig);listeners.length===emitter.count&&(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP"&&(sig="SIGINT"),process3.kill(process3.pid,sig))}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){loaded||!processOk(global.process)||(loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch{return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit)},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){processOk(global.process)&&(process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode))},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){arg!==void 0&&(process3.exitCode=arg);var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}):module.exports=function(){return function(){}};var assert,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit}});var require_mtime_precision=__commonJS({"node_modules/proper-lockfile/lib/mtime-precision.js"(exports,module){"use strict";var cacheSymbol=Symbol();function probe(file,fs,callback){let cachedPrecision=fs[cacheSymbol];if(cachedPrecision)return fs.stat(file,(err,stat)=>{if(err)return callback(err);callback(null,stat.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1e3)*1e3+5);fs.utimes(file,mtime,mtime,err=>{if(err)return callback(err);fs.stat(file,(err2,stat)=>{if(err2)return callback(err2);let precision=stat.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(fs,cacheSymbol,{value:precision}),callback(null,stat.mtime,precision)})})}function getMtime(precision){let now=Date.now();return precision==="s"&&(now=Math.ceil(now/1e3)*1e3),new Date(now)}module.exports.probe=probe;module.exports.getMtime=getMtime}});var require_lockfile=__commonJS({"node_modules/proper-lockfile/lib/lockfile.js"(exports,module){"use strict";var path=__require("path"),fs=require_graceful_fs(),retry=require_retry2(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file,options){return options.lockfilePath||`${file}.lock`}function resolveCanonicalPath(file,options,callback){if(!options.realpath)return callback(null,path.resolve(file));options.fs.realpath(file,callback)}function acquireLock(file,options,callback){let lockfilePath=getLockFile(file,options);options.fs.mkdir(lockfilePath,err=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));options.fs.stat(lockfilePath,(err2,stat)=>{if(err2)return err2.code==="ENOENT"?acquireLock(file,{...options,stale:0},callback):callback(err2);if(!isLockStale(stat,options))return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));removeLock(file,options,err3=>{if(err3)return callback(err3);acquireLock(file,{...options,stale:0},callback)})})})}function isLockStale(stat,options){return stat.mtime.getTime()<Date.now()-options.stale}function removeLock(file,options,callback){options.fs.rmdir(getLockFile(file,options),err=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file,options){let lock2=locks[file];lock2.updateTimeout||(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err)return err.code==="ENOENT"||isOverThreshold?setLockAsCompromised(file,lock2,Object.assign(err,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));if(!(lock2.mtime.getTime()===stat.mtime.getTime()))return setLockAsCompromised(file,lock2,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,err2=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(!lock2.released){if(err2)return err2.code==="ENOENT"||isOverThreshold2?setLockAsCompromised(file,lock2,Object.assign(err2,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file,options)}})})},lock2.updateDelay),lock2.updateTimeout.unref&&lock2.updateTimeout.unref())}function setLockAsCompromised(file,lock2,err){lock2.released=!0,lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),locks[file]===lock2&&delete locks[file],lock2.options.onCompromised(err)}function lock(file,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs,onCompromised:err=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries=="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2e3),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file2,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file2]={lockfilePath:getLockFile(file2,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file2,options),callback(null,releasedCallback=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));unlock(file2,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file,options,callback){options={fs,realpath:!0,...options},resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let lock2=locks[file2];if(!lock2)return callback(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file2],removeLock(file2,options,callback)})}function check(file,options,callback){options={stale:1e4,realpath:!0,fs,...options},options.stale=Math.max(options.stale||0,2e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);options.fs.stat(getLockFile(file2,options),(err2,stat)=>err2?err2.code==="ENOENT"?callback(null,!1):callback(err2):callback(null,!isLockStale(stat,options)))})}function getLocks(){return locks}onExit(()=>{for(let file in locks){let options=locks[file].options;try{options.fs.rmdirSync(getLockFile(file,options))}catch{}}});module.exports.lock=lock;module.exports.unlock=unlock;module.exports.check=check;module.exports.getLocks=getLocks}});var require_adapter=__commonJS({"node_modules/proper-lockfile/lib/adapter.js"(exports,module){"use strict";var fs=require_graceful_fs();function createSyncFs(fs2){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs2};return methods.forEach(method=>{newFs[method]=(...args)=>{let callback=args.pop(),ret;try{ret=fs2[`${method}Sync`](...args)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args)=>new Promise((resolve,reject)=>{args.push((err,result)=>{err?reject(err):resolve(result)}),method(...args)})}function toSync(method){return(...args)=>{let err,result;if(args.push((_err,_result)=>{err=_err,result=_result}),method(...args),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs),typeof options.retries=="number"&&options.retries>0||options.retries&&typeof options.retries.retries=="number"&&options.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}}});var require_proper_lockfile=__commonJS({"node_modules/proper-lockfile/index.js"(exports,module){"use strict";var lockfile2=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file,options){let release=await toPromise(lockfile2.lock)(file,options);return toPromise(release)}function lockSync(file,options){let release=toSync(lockfile2.lock)(file,toSyncOptions(options));return toSync(release)}function unlock(file,options){return toPromise(lockfile2.unlock)(file,options)}function unlockSync(file,options){return toSync(lockfile2.unlock)(file,toSyncOptions(options))}function check(file,options){return toPromise(lockfile2.check)(file,options)}function checkSync(file,options){return toSync(lockfile2.check)(file,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check;module.exports.checkSync=checkSync}});import{execSync,spawnSync}from"child_process";var commandResultCache=new Map,ENV_VAR_NAME_RE=/^[A-Za-z_][A-Za-z0-9_]*$/,ENV_VAR_NAME_PREFIX_RE=/^[A-Za-z_][A-Za-z0-9_]*/;function appendLiteral(parts,value){if(!value)return;let previousPart=parts[parts.length-1];if(previousPart?.type==="literal"){previousPart.value+=value;return}parts.push({type:"literal",value})}function parseConfigValueTemplate(config){let parts=[],index=0;for(;index<config.length;){let dollarIndex=config.indexOf("$",index);if(dollarIndex<0){appendLiteral(parts,config.slice(index));break}appendLiteral(parts,config.slice(index,dollarIndex));let nextChar=config[dollarIndex+1];if(nextChar==="$"||nextChar==="!"){appendLiteral(parts,nextChar),index=dollarIndex+2;continue}if(nextChar==="{"){let endIndex=config.indexOf("}",dollarIndex+2);if(endIndex<0){appendLiteral(parts,"$"),index=dollarIndex+1;continue}let name=config.slice(dollarIndex+2,endIndex);ENV_VAR_NAME_RE.test(name)?parts.push({type:"env",name}):appendLiteral(parts,config.slice(dollarIndex,endIndex+1)),index=endIndex+1;continue}let match=config.slice(dollarIndex+1).match(ENV_VAR_NAME_PREFIX_RE);if(match){parts.push({type:"env",name:match[0]}),index=dollarIndex+1+match[0].length;continue}appendLiteral(parts,"$"),index=dollarIndex+1}return parts}function parseConfigValueReference(config){return config.startsWith("!")?{type:"command",config}:{type:"template",parts:parseConfigValueTemplate(config)}}function resolveEnvConfigValue(name,env){return env?.[name]||process.env[name]||void 0}function getTemplateEnvVarNames(parts){let names=[];for(let part of parts)part.type!=="env"||names.includes(part.name)||names.push(part.name);return names}function resolveTemplate(parts,env){let resolved="";for(let part of parts){if(part.type==="literal"){resolved+=part.value;continue}let envValue=resolveEnvConfigValue(part.name,env);if(envValue===void 0)return;resolved+=envValue}return resolved}function getConfigValueEnvVarNames(config){let reference=parseConfigValueReference(config);return reference.type==="template"?getTemplateEnvVarNames(reference.parts):[]}function getMissingConfigValueEnvVarNames(config,env){return getConfigValueEnvVarNames(config).filter(name=>resolveEnvConfigValue(name,env)===void 0)}function isCommandConfigValue(config){return parseConfigValueReference(config).type==="command"}function isConfigValueConfigured(config,env){return getMissingConfigValueEnvVarNames(config,env).length===0}function resolveConfigValue(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?executeCommand(reference.config):resolveTemplate(reference.parts,env)}function executeWithConfiguredShell(command){try{let{shell,args,commandTransport}=getShellConfig(),commandFromStdin=commandTransport==="stdin",result=spawnSync(shell,commandFromStdin?args:[...args,command],{encoding:"utf-8",input:commandFromStdin?command:void 0,timeout:1e4,stdio:[commandFromStdin?"pipe":"ignore","pipe","ignore"],shell:!1,windowsHide:!0});return result.error?result.error.code==="ENOENT"?{executed:!1,value:void 0}:{executed:!0,value:void 0}:result.status!==0?{executed:!0,value:void 0}:{executed:!0,value:(result.stdout??"").trim()||void 0}}catch{return{executed:!1,value:void 0}}}function executeWithDefaultShell(command){try{return execSync(command,{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function executeCommandUncached(commandConfig){let command=commandConfig.slice(1);return process.platform==="win32"?(()=>{let configuredResult=executeWithConfiguredShell(command);return configuredResult.executed?configuredResult.value:executeWithDefaultShell(command)})():executeWithDefaultShell(command)}function executeCommand(commandConfig){if(commandResultCache.has(commandConfig))return commandResultCache.get(commandConfig);let result=executeCommandUncached(commandConfig);return commandResultCache.set(commandConfig,result),result}function resolveConfigValueUncached(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?executeCommandUncached(reference.config):resolveTemplate(reference.parts,env)}function resolveConfigValueOrThrow(config,description,env){let resolvedValue=resolveConfigValueUncached(config,env);if(resolvedValue!==void 0)return resolvedValue;let reference=parseConfigValueReference(config);if(reference.type==="command")throw new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);if(reference.type==="template"){let missingEnvVars=getMissingConfigValueEnvVarNames(config,env);if(missingEnvVars.length===1)throw new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);if(missingEnvVars.length>1)throw new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(", ")}`)}throw new Error(`Failed to resolve ${description}`)}function resolveHeadersOrThrow(headers,description,env){if(!headers)return;let resolved={};for(let[key,value]of Object.entries(headers))resolved[key]=resolveConfigValueOrThrow(value,`${description} header "${key}"`,env);return Object.keys(resolved).length>0?resolved:void 0}var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";import{setTimeout as sleep}from"timers/promises";function abortReason(signal){if(signal.reason!==void 0)return signal.reason;let error=new Error("The operation was aborted");return error.name="AbortError",error}function operationSignal(signal){return signal??new AbortController().signal}function raceWithAbortSignal(operation,signal){return signal?signal.aborted?(operation.catch(()=>{}),Promise.reject(abortReason(signal))):new Promise((resolve,reject)=>{let settled=!1,cleanup=()=>signal.removeEventListener("abort",onAbort),onAbort=()=>{settled||(settled=!0,cleanup(),reject(abortReason(signal)))};signal.addEventListener("abort",onAbort,{once:!0}),operation.then(value=>{settled||(settled=!0,cleanup(),resolve(value))},error=>{settled||(settled=!0,cleanup(),reject(error))}),signal.aborted&&onAbort()}):operation}var MAX_EPERM_RETRIES=5;function getRetryableLockErrorCode(error){let code=error instanceof Error&&"code"in error?error.code:void 0;if(code==="ELOCKED"||code==="EPERM"&&process.platform==="win32")return code}var AUTH_FILE_WRITE_OPTIONS={encoding:"utf-8",mode:384},sharedAuthFileReadState,FileAuthStorageBackend=class{authPath;constructor(authPath=join(getAgentDir(),"auth.json")){this.authPath=normalizePath(authPath)}ensureParentDir(){let dir=dirname(this.authPath);existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448})}ensureFileExists(){existsSync(this.authPath)||writeFileSync(this.authPath,"{}",AUTH_FILE_WRITE_OPTIONS)}acquireLockSyncWithRetry(path){for(let attempt=1;;attempt++)try{return import_proper_lockfile.default.lockSync(path,{realpath:!1})}catch(error){if(!getRetryableLockErrorCode(error)||attempt===10)throw error;let start=Date.now();for(;Date.now()-start<20;);}}withLock(fn){this.ensureParentDir(),this.ensureFileExists();let release;try{release=this.acquireLockSyncWithRetry(this.authPath);let current=existsSync(this.authPath)?readFileSync(this.authPath,"utf-8"):void 0,{result,next}=fn(current);return next!==void 0&&writeFileSync(this.authPath,next,AUTH_FILE_WRITE_OPTIONS),result}finally{release&&release()}}async acquireLockAsync(signal,onCompromised){let deadline=Date.now()+3e4,retry=0,epermRetries=0;for(;;){signal?.throwIfAborted();let release;try{release=await import_proper_lockfile.default.lock(this.authPath,{realpath:!1,retries:0,stale:3e4,onCompromised})}catch(error){signal?.throwIfAborted();let code=getRetryableLockErrorCode(error),remainingMs=deadline-Date.now();if(!code||remainingMs<=0||code==="EPERM"&&++epermRetries>MAX_EPERM_RETRIES)throw error;let baseDelayMs=Math.min(10*2**retry,2e3/2);retry++;let delayMs=Math.min(Math.round(baseDelayMs*(1+Math.random())),remainingMs);signal?await sleep(delayMs,void 0,{signal}):await sleep(delayMs);continue}return signal?.aborted&&(await release(),signal.throwIfAborted()),release}}async withLockAsync(fn,options){options?.signal?.throwIfAborted(),this.ensureParentDir(),this.ensureFileExists();let release,lockCompromised=!1,lockCompromisedError,throwIfCompromised=()=>{if(lockCompromised)throw lockCompromisedError??new Error("Auth storage lock was compromised")};try{release=await this.acquireLockAsync(options?.signal,error=>{lockCompromised=!0,lockCompromisedError=error}),throwIfCompromised(),options?.signal?.throwIfAborted();let current=existsSync(this.authPath)?readFileSync(this.authPath,"utf-8"):void 0,{result,next}=await fn(current);return throwIfCompromised(),options?.signal?.throwIfAborted(),next!==void 0&&writeFileSync(this.authPath,next,AUTH_FILE_WRITE_OPTIONS),throwIfCompromised(),result}finally{if(release)try{await release()}catch{}}}},ReadOnlyAuthStorage=class{authPath;data;constructor(authPath=join(getAgentDir(),"auth.json")){this.authPath=normalizePath(authPath)}load(){if(this.data)return this.data;let parsed;try{parsed=JSON.parse(stripBom(readFileSync(this.authPath,"utf-8")))}catch(error){if(error.code==="ENOENT")return this.data={},this.data;throw new Error(`Failed to read auth.json: ${error instanceof Error?error.message:String(error)}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error("Invalid auth.json: expected an object");for(let[providerId,credential]of Object.entries(parsed)){if(typeof credential!="object"||credential===null||Array.isArray(credential))throw new Error(`Invalid auth.json credential for provider "${providerId}"`);let value=credential;if(value.type==="api_key"){let validKey=value.key===void 0||typeof value.key=="string",validEnv=value.env===void 0||typeof value.env=="object"&&value.env!==null&&!Array.isArray(value.env)&&Object.values(value.env).every(entry=>typeof entry=="string");if(validKey&&validEnv)continue}else if(value.type==="oauth"&&typeof value.access=="string"&&typeof value.refresh=="string"&&typeof value.expires=="number"&&Number.isFinite(value.expires))continue;throw new Error(`Invalid auth.json credential for provider "${providerId}"`)}return this.data=parsed,this.data}async read(providerId,options){options?.signal?.throwIfAborted();let credential=this.load()[providerId];if(options?.signal?.throwIfAborted(),!!credential)return credential.type!=="api_key"||!credential.key||isCommandConfigValue(credential.key)?structuredClone(credential):{...credential,key:resolveConfigValue(credential.key,credential.env)}}async list(options){options?.signal?.throwIfAborted();let credentials=Object.entries(this.load()).map(([providerId,credential])=>({providerId,type:credential.type}));return options?.signal?.throwIfAborted(),credentials}async modify(_providerId,_fn,_options){throw new Error("Read-only credential storage cannot modify auth.json")}async delete(_providerId,_options){throw new Error("Read-only credential storage cannot modify auth.json")}},InMemoryAuthStorageBackend=class{value;asyncChain=Promise.resolve();withLock(fn){let{result,next}=fn(this.value);return next!==void 0&&(this.value=next),result}withLockAsync(fn,options){let previous=this.asyncChain,operation=(async()=>{await previous.catch(()=>{}),options?.signal?.throwIfAborted();let{result,next}=await fn(this.value);return options?.signal?.throwIfAborted(),next!==void 0&&(this.value=next),result})();return this.asyncChain=operation.catch(()=>{}),raceWithAbortSignal(operation,options?.signal)}},AuthStorage=class _AuthStorage{storage;authPath;readState;constructor(storage,authPath){if(this.storage=storage,this.authPath=authPath,this.readState=authPath&&sharedAuthFileReadState?.authPath===authPath?sharedAuthFileReadState.readState:{data:{}},authPath&&!sharedAuthFileReadState&&(sharedAuthFileReadState={authPath,readState:this.readState}),authPath){let revision=getFileRevision(authPath);if(revision!==void 0&&revision===this.readState.revision)return}this.reload()}static create(authPath=join(getAgentDir(),"auth.json")){let normalizedAuthPath=normalizePath(authPath);return new _AuthStorage(new FileAuthStorageBackend(normalizedAuthPath),normalizedAuthPath)}static fromStorage(storage){return new _AuthStorage(storage)}static inMemory(data={}){let storage=new InMemoryAuthStorageBackend;return storage.withLock(()=>({result:void 0,next:JSON.stringify(data,null,2)})),_AuthStorage.fromStorage(storage)}parseStorageData(content){return content?JSON.parse(stripBom(content)):{}}updateReadState(data,revision){this.readState.data=data,this.readState.revision=revision}reload(){let content,revision;try{this.storage.withLock(current=>(content=current,revision=this.authPath?getFileRevision(this.authPath):void 0,{result:void 0})),this.updateReadState(this.parseStorageData(content),revision)}catch{}}async reloadFromStorageAsync(options){return this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content),revision=this.authPath?getFileRevision(this.authPath):void 0;return this.updateReadState(currentData,revision),{result:currentData}},options)}async readLatestData(options){if(options?.signal?.throwIfAborted(),!this.authPath){let reload2=this.reloadFromStorageAsync(options);return options?.signal?reload2:reload2.catch(()=>this.readState.data)}let revision=getFileRevision(this.authPath);if(revision!==void 0&&revision===this.readState.revision)return this.readState.data;if(!this.readState.reload){let controller=new AbortController,reload2={controller,promise:this.reloadFromStorageAsync({signal:controller.signal}),readers:0};this.readState.reload=reload2,reload2.promise.then(()=>{this.readState.reload===reload2&&(this.readState.reload=void 0)},()=>{this.readState.reload===reload2&&(this.readState.reload=void 0)})}let reload=this.readState.reload;reload.readers++;try{let result=raceWithAbortSignal(reload.promise,options?.signal);return options?.signal?await result:await result.catch(()=>this.readState.data)}finally{reload.readers--,reload.readers===0&&this.readState.reload===reload&&(this.readState.reload=void 0,reload.controller.abort())}}async read(provider,options){let credential=(await this.readLatestData(options))[provider];return options?.signal?.throwIfAborted(),credential?.type!=="api_key"||credential.key===void 0?credential:{...credential,key:resolveConfigValue(credential.key,credential.env)}}async modify(provider,fn,options){let latestData=this.readState.data,revision,result=await this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content),next=await fn(currentData[provider]);if(next===void 0)return latestData=currentData,revision=this.authPath?getFileRevision(this.authPath):void 0,{result:currentData[provider]};let merged={...currentData,[provider]:next};return latestData=merged,{result:next,next:JSON.stringify(merged,null,2)}},options);return this.updateReadState(latestData,revision),result}async delete(provider,options){let latestData=this.readState.data;await this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content);return delete currentData[provider],latestData=currentData,{result:void 0,next:JSON.stringify(currentData,null,2)}},options),this.updateReadState(latestData)}async list(options){let entries=Object.entries(await this.readLatestData(options));return options?.signal?.throwIfAborted(),entries.map(([providerId,credential])=>({providerId,type:credential.type}))}};function readStoredCredential(providerId,authPath=join(getAgentDir(),"auth.json")){try{return JSON.parse(stripBom(readFileSync(normalizePath(authPath),"utf-8")))[providerId]}catch{return}}function toolPatternRegExp(pattern){let source=pattern.split("*").map(part=>part.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${source}$`)}function createToolNameMatcher(entries){let names=new Set(entries.filter(entry=>!entry.includes("*"))),patterns=entries.filter(entry=>entry.includes("*")).map(toolPatternRegExp);return name=>names.has(name)||patterns.some(pattern=>pattern.test(name))}var LIST_MCP_RESOURCES_TOOL="list_mcp_resources",LIST_MCP_RESOURCE_TEMPLATES_TOOL="list_mcp_resource_templates",READ_MCP_RESOURCE_TOOL="read_mcp_resource",MCP_RESOURCE_TOOLS=new Set([LIST_MCP_RESOURCES_TOOL,LIST_MCP_RESOURCE_TEMPLATES_TOOL,READ_MCP_RESOURCE_TOOL]);function isMcpToolName(name){return name.startsWith("mcp__")||MCP_RESOURCE_TOOLS.has(name)}var MCP_EXPOSURES=["codemode","deferred","direct","hidden"],MCP_EXPOSURE_ALIASES={"codemode-deferred":"codemode"},LOOPBACK_HOSTS=["localhost","127.0.0.1","[::1]"];function isLoopbackRedirectUri(value){if(!URL.canParse(value))return!1;let url=new URL(value);return url.protocol==="http:"&&LOOPBACK_HOSTS.includes(url.hostname)&&url.search===""&&url.hash===""}var SERVER_NAME=/^[A-Za-z0-9_-]+$/;function mcpNamespace(server){return`mcp__${server.replace(/-/g,"_")}`}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStringRecord(value){return isRecord(value)&&Object.values(value).every(entry=>typeof entry=="string")}function validateOAuth(value){if(value===void 0)return;if(!isRecord(value))return"oauth must be an object";if(value.clientId!==void 0&&typeof value.clientId!="string")return"oauth.clientId must be a string";if(value.clientSecret!==void 0&&typeof value.clientSecret!="string")return"oauth.clientSecret must be a string";let port=value.callbackPort;if(port!==void 0&&(typeof port!="number"||!Number.isInteger(port)||port<1||port>65535))return"oauth.callbackPort must be a port number";if(value.callbackUrl!==void 0){if(typeof value.callbackUrl!="string"||!isLoopbackRedirectUri(value.callbackUrl))return"oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment";let urlPort=new URL(value.callbackUrl).port;if(urlPort&&port!==void 0&&Number(urlPort)!==port)return"oauth.callbackUrl and oauth.callbackPort name different ports"}if(value.scope!==void 0&&typeof value.scope!="string")return"oauth.scope must be a string";if(value.clientName!==void 0&&(typeof value.clientName!="string"||!value.clientName.trim()))return"oauth.clientName must be a non-empty string";if(value.clientRegistration!==void 0&&value.clientRegistration!=="dcr"){if(value.clientRegistration!=="cimd")return'oauth.clientRegistration must be "dcr" or "cimd"';if(value.clientId!==void 0||value.clientName!==void 0)return'oauth.clientRegistration "cimd" cannot be combined with oauth.clientId or oauth.clientName';let callback=typeof value.callbackUrl=="string"?new URL(value.callbackUrl):void 0;if(callback&&(callback.hostname==="[::1]"||callback.pathname!=="/callback"))return'oauth.clientRegistration "cimd" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback'}let metadataUrl=value.authServerMetadataUrl;if(metadataUrl!==void 0){let url=typeof metadataUrl=="string"&&URL.canParse(metadataUrl)?new URL(metadataUrl):void 0;if(!url||!(url.protocol==="https:"||url.protocol==="http:"&&LOOPBACK_HOSTS.includes(url.hostname)))return"oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]"}}function isExposure(value){return typeof value=="string"&&MCP_EXPOSURES.includes(value)}function resolveExposureAlias(value){return typeof value=="string"?MCP_EXPOSURE_ALIASES[value]??value:value}function resolveExposureAliases(value){let{exposure,toolExposure}=value,resolved={...value};return exposure!==void 0&&(resolved.exposure=resolveExposureAlias(exposure)),isRecord(toolExposure)&&(resolved.toolExposure=Object.fromEntries(Object.entries(toolExposure).map(([tool,entry])=>[tool,resolveExposureAlias(entry)]))),resolved}function getMcpToolExposure(config,toolName){let overrides=config.toolExposure??{},exact=overrides[toolName];if(exact!==void 0)return exact;for(let[pattern,exposure]of Object.entries(overrides))if(pattern.includes("*")&&toolPatternRegExp(pattern).test(toolName))return exposure;return config.exposure??"codemode"}function validateMcpServerConfig(name,raw){if(!SERVER_NAME.test(name))return`invalid server name "${name}" (use letters, digits, "_" and "-")`;if(!isRecord(raw))return`server "${name}" must be an object`;let value=resolveExposureAliases(raw),{type,exposure,enabled,timeout,toolExposure,description}=value,exposures=MCP_EXPOSURES.map(value2=>`"${value2}"`).join(", ");if(exposure!==void 0&&!isExposure(exposure))return`server "${name}": exposure must be one of ${exposures}`;if(toolExposure!==void 0){if(!isRecord(toolExposure))return`server "${name}": toolExposure must map tool names to exposures`;for(let[tool,value2]of Object.entries(toolExposure))if(!isExposure(value2))return`server "${name}": toolExposure "${tool}" must be one of ${exposures}`}if(enabled!==void 0&&typeof enabled!="boolean")return`server "${name}": enabled must be a boolean`;if(description!==void 0&&typeof description!="string")return`server "${name}": description must be a string`;if(timeout!==void 0&&(typeof timeout!="number"||!(timeout>0)))return`server "${name}": timeout must be a positive number of seconds`;if(type==="sse")return`server "${name}": legacy SSE transport is not supported; use the streamable HTTP URL`;if(typeof value.url=="string"&&(type===void 0||type==="http"||type==="streamable-http")){if(!URL.canParse(value.url)||!/^https?:$/.test(new URL(value.url).protocol))return`server "${name}": url must be an http or https URL`;if(value.headers!==void 0&&!isStringRecord(value.headers))return`server "${name}": headers must map names to strings`;let oauthError=validateOAuth(value.oauth);if(oauthError)return`server "${name}": ${oauthError}`;if(value.auth!==void 0){if(!isRecord(value.auth)||typeof value.auth.provider!="string"||!value.auth.provider)return`server "${name}": auth.provider must be a provider name`;let url=new URL(value.url);if(url.protocol!=="https:"&&!LOOPBACK_HOSTS.includes(url.hostname))return`server "${name}": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`}return value}return typeof value.command=="string"&&(type===void 0||type==="stdio")?value.args!==void 0&&!(Array.isArray(value.args)&&value.args.every(arg=>typeof arg=="string"))?`server "${name}": args must be an array of strings`:value.env!==void 0&&!isStringRecord(value.env)?`server "${name}": env must map names to strings`:value.cwd!==void 0&&typeof value.cwd!="string"?`server "${name}": cwd must be a string`:value.inheritEnv!==void 0&&typeof value.inheritEnv!="boolean"?`server "${name}": inheritEnv must be a boolean`:value:`server "${name}" needs either "command" (stdio) or "url" (streamable HTTP)`}var McpServerRegistry=class{servers=new Map;changeListener;register(server){this.servers.set(server.name,server),this.changeListener?.()}unregister(name,extensionPath){this.servers.get(name)?.extensionPath===extensionPath&&(this.servers.delete(name),this.changeListener?.())}get(name){return this.servers.get(name)}list(){return[...this.servers.values()].map(server=>({...server,config:structuredClone(server.config)}))}setChangeListener(listener){this.changeListener=listener}};var JSON_RPC_ERROR_CODES={parseError:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internalError:-32603},McpError=class extends Error{code;data;constructor(code,message,data){super(message),this.name="McpError",this.code=code,this.data=data}},McpConnectionClosedError=class extends Error{constructor(message="MCP connection closed"){super(message),this.name="McpConnectionClosedError"}},McpTimeoutError=class extends Error{timeoutMs;constructor(timeoutMs){super(`MCP request timed out after ${timeoutMs}ms`),this.name="McpTimeoutError",this.timeoutMs=timeoutMs}},McpAbortError=class extends Error{constructor(message="MCP request aborted"){super(message),this.name="AbortError"}};function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function toError(value){return value instanceof Error?value:new Error(String(value))}function isJsonRpcId(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)}function isJsonRpcRequest(message){return isObject(message)&&message.jsonrpc==="2.0"&&isJsonRpcId(message.id)&&typeof message.method=="string"}function isJsonRpcNotification(message){return isObject(message)&&message.jsonrpc==="2.0"&&!("id"in message)&&typeof message.method=="string"}function isJsonRpcResponse(message){return!isObject(message)||message.jsonrpc!=="2.0"||!isJsonRpcId(message.id)?!1:"result"in message?!("error"in message):!("error"in message)||!isObject(message.error)?!1:typeof message.error.code=="number"&&typeof message.error.message=="string"}function parseJsonRpcMessage(value){if(isJsonRpcRequest(value)||isJsonRpcNotification(value)||isJsonRpcResponse(value))return value;throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid JSON-RPC message")}var LATEST_PROTOCOL_VERSION="2025-11-25",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05"];var DEFAULT_REQUEST_TIMEOUT_MS=3e4,MAX_LIST_PAGES=1e3;function validateInitializeResult(value){if(!isObject(value)||typeof value.protocolVersion!="string"||!isObject(value.capabilities)||!isObject(value.serverInfo)||typeof value.serverInfo.name!="string"||typeof value.serverInfo.version!="string"||value.instructions!==void 0&&typeof value.instructions!="string")throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid MCP initialize result");return value}function invalid(message){return new McpError(JSON_RPC_ERROR_CODES.invalidRequest,message)}function validateListPage(method,key,value,isItem){let items=isObject(value)?value[key]:void 0;if(!isObject(value)||!Array.isArray(items))throw invalid(`Invalid MCP ${method} result`);for(let item of items)if(!isObject(item)||!isItem(item))throw invalid(`Invalid entry in MCP ${method} result`);let nextCursor=value.nextCursor===null||value.nextCursor===""?void 0:value.nextCursor;if(nextCursor!==void 0&&typeof nextCursor!="string")throw invalid(`Invalid MCP ${method} cursor`);return{items,...nextCursor===void 0?{}:{nextCursor}}}var isTool=tool=>typeof tool.name=="string"&&isObject(tool.inputSchema),isResource=resource=>typeof resource.uri=="string"&&(resource.name===void 0||typeof resource.name=="string"),isResourceTemplate=template=>typeof template.uriTemplate=="string"&&(template.name===void 0||typeof template.name=="string");function toResource(item){return{...item,name:item.name??item.uri}}function toResourceTemplate(item){return{...item,name:item.name??item.uriTemplate}}function pageCursor(page){return page.nextCursor===void 0?{}:{nextCursor:page.nextCursor}}function validateReadResourceResult(value){if(!isObject(value)||!Array.isArray(value.contents))throw invalid("Invalid MCP resources/read result");for(let contents of value.contents)if(!isObject(contents)||typeof contents.uri!="string"||typeof contents.text!="string"&&typeof contents.blob!="string")throw invalid("Invalid contents in MCP resources/read result");return value}function validateCallToolResult(value){if(!isObject(value)||value.content!==void 0&&!Array.isArray(value.content))throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid MCP tools/call result");return value.content===void 0?{...value,content:[]}:value}var McpClient=class{options;state="idle";transport;nextRequestId=1;serverInfoValue;serverCapabilitiesValue;instructionsValue;protocolVersionValue;pending=new Map;progressRequests=new Map;incoming=new Map;requestHandlers=new Map;notificationListeners=new Map;errorListeners=new Set;closeListeners=new Set;disposers=[];constructor(options){this.options=Object.freeze({...options}),this.requestHandlers.set("ping",()=>({}));let roots=options.roots;roots&&this.requestHandlers.set("roots/list",async()=>({roots:[...typeof roots=="function"?await roots():roots]}))}get connectionState(){return this.state}get serverInfo(){return this.serverInfoValue}get serverCapabilities(){return this.serverCapabilitiesValue}get instructions(){return this.instructionsValue}get protocolVersion(){return this.protocolVersionValue}async connect(transport){if(this.state!=="idle")throw new Error(`Cannot connect MCP client in ${this.state} state`);this.state="connecting",this.transport=transport,this.disposers=[transport.onMessage(message=>this.handleMessage(message)),transport.onError(error=>this.emitError(error)),transport.onClose(()=>this.handleTransportClose())];try{await transport.start();let capabilities={...this.options.capabilities};this.options.roots&&capabilities.roots===void 0&&(capabilities.roots={});let result=validateInitializeResult(await this.requestInternal("initialize",{protocolVersion:this.options.protocolVersion??LATEST_PROTOCOL_VERSION,capabilities,clientInfo:{name:this.options.name,version:this.options.version,...this.options.title===void 0?{}:{title:this.options.title}}},{},!0));if(!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion))throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);return this.protocolVersionValue=result.protocolVersion,this.serverInfoValue=result.serverInfo,this.serverCapabilitiesValue=result.capabilities,this.instructionsValue=result.instructions,transport.setProtocolVersion?.(result.protocolVersion),await this.notifyInternal("notifications/initialized",void 0,!0),this.state="connected",result}catch(error){throw await this.close().catch(()=>{}),error}}request(method,params,options={}){return this.requestInternal(method,params,options,!1)}notify(method,params){return this.notifyInternal(method,params,!1)}setRequestHandler(method,handler){return this.requestHandlers.set(method,handler),()=>{this.requestHandlers.get(method)===handler&&this.requestHandlers.delete(method)}}onNotification(method,listener){let listeners=this.notificationListeners.get(method)??new Set;return this.notificationListeners.set(method,listeners),listeners.add(listener),()=>{listeners.delete(listener),listeners.size===0&&this.notificationListeners.delete(method)}}onError(listener){return this.errorListeners.add(listener),()=>this.errorListeners.delete(listener)}onClose(listener){return this.closeListeners.add(listener),()=>this.closeListeners.delete(listener)}async ping(options={}){await this.request("ping",void 0,options)}async listTools(options={}){return await this.listAll("tools/list","tools",isTool,options)}async listResources(options={}){return(await this.listAll("resources/list","resources",isResource,options)).map(toResource)}async listResourcesPage(cursor,options={}){let page=await this.listPage("resources/list","resources",isResource,cursor,options);return{resources:page.items.map(toResource),...pageCursor(page)}}async listResourceTemplates(options={}){return(await this.listAll("resources/templates/list","resourceTemplates",isResourceTemplate,options)).map(toResourceTemplate)}async listResourceTemplatesPage(cursor,options={}){let page=await this.listPage("resources/templates/list","resourceTemplates",isResourceTemplate,cursor,options);return{resourceTemplates:page.items.map(toResourceTemplate),...pageCursor(page)}}async readResource(uri,options={}){return validateReadResourceResult(await this.request("resources/read",{uri},options))}async listPage(method,key,isItem,cursor,options){return validateListPage(method,key,await this.request(method,cursor===void 0?void 0:{cursor},options),isItem)}async listAll(method,key,isItem,options){let items=[],cursors=new Set,cursor;for(let pageNumber=0;pageNumber<MAX_LIST_PAGES;pageNumber++){let page=await this.listPage(method,key,isItem,cursor,options);if(items.push(...page.items),page.nextCursor===void 0)return items;if(cursors.has(page.nextCursor))throw new Error(`MCP ${method} returned duplicate cursor: ${page.nextCursor}`);cursors.add(page.nextCursor),cursor=page.nextCursor}throw new Error(`MCP ${method} exceeded ${MAX_LIST_PAGES} pages`)}async callTool(name,args,options={}){return validateCallToolResult(await this.request("tools/call",{name,...args===void 0?{}:{arguments:args}},options))}async close(){let transport=this.transport;this.transport=void 0,this.disposeTransportListeners(),this.markClosed(new McpConnectionClosedError),await transport?.close()}async requestInternal(method,params,options,allowConnecting){let transport=this.requireTransport(allowConnecting);if(options.signal?.aborted)throw new McpAbortError;let id=this.nextRequestId++,progressToken=options.onProgress?id:void 0,requestParams=progressToken===void 0?params:{...params,_meta:{...isObject(params?._meta)?params._meta:{},progressToken}},message={jsonrpc:"2.0",id,method,...requestParams===void 0?{}:{params:requestParams}};return new Promise((resolve,reject)=>{let entry={resolve,reject,timeoutMs:options.timeoutMs??this.options.requestTimeoutMs??DEFAULT_REQUEST_TIMEOUT_MS,timer:void 0,signal:options.signal,onAbort:()=>this.cancelPending(id,new McpAbortError,method!=="initialize",String(options.signal?.reason??"Aborted")),sendController:new AbortController,cancellable:method!=="initialize",onProgress:options.onProgress,progressToken};this.pending.set(id,entry),progressToken!==void 0&&this.progressRequests.set(progressToken,id),options.signal?.addEventListener("abort",entry.onAbort,{once:!0}),this.armTimeout(id,entry),transport.send(message,{signal:entry.sendController.signal}).catch(error=>this.cancelPending(id,error,!1))})}async notifyInternal(method,params,allowConnecting){await this.requireTransport(allowConnecting).send({jsonrpc:"2.0",method,...params===void 0?{}:{params}})}requireTransport(allowConnecting){if(this.transport&&(this.state==="connected"||allowConnecting&&this.state==="connecting"))return this.transport;throw new McpConnectionClosedError(`MCP client is ${this.state}`)}handleMessage(message){if(isJsonRpcResponse(message)){this.handleResponse(message);return}if(isJsonRpcRequest(message)){this.handleRequest(message);return}if(isJsonRpcNotification(message)){this.handleNotification(message.method,message.params);return}this.emitError(new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Received invalid JSON-RPC message"))}handleResponse(message){let entry=this.pending.get(message.id);if(!entry){this.emitError(new Error(`Received response for unknown MCP request ${String(message.id)}`));return}this.removePending(message.id,entry),"error"in message?entry.reject(new McpError(message.error.code,message.error.message,message.error.data)):entry.resolve(message.result)}async handleRequest(message){let transport=this.transport;if(!transport)return;let handler=this.requestHandlers.get(message.method);if(!handler){await transport.send({jsonrpc:"2.0",id:message.id,error:{code:JSON_RPC_ERROR_CODES.methodNotFound,message:`Method not found: ${message.method}`}}).catch(error=>this.emitError(error));return}let controller=new AbortController;this.incoming.set(message.id,controller);try{let result=await handler(message.params,{signal:controller.signal});await transport.send({jsonrpc:"2.0",id:message.id,result:result??{}})}catch(error){let responseError=error instanceof McpError?{code:error.code,message:error.message,data:error.data}:{code:JSON_RPC_ERROR_CODES.internalError,message:toError(error).message};await transport.send({jsonrpc:"2.0",id:message.id,error:responseError}).catch(sendError=>this.emitError(sendError))}finally{this.incoming.delete(message.id)}}handleNotification(method,params){method==="notifications/progress"?this.handleProgress(params):method==="notifications/cancelled"&&this.handleCancelled(params);for(let listener of this.notificationListeners.get(method)??[])try{listener(params)}catch(error){this.emitError(error)}}handleProgress(params){if(!isObject(params)||!isJsonRpcId(params.progressToken)||typeof params.progress!="number")return;let requestId=this.progressRequests.get(params.progressToken),entry=requestId===void 0?void 0:this.pending.get(requestId);if(!(requestId===void 0||!entry)){this.armTimeout(requestId,entry);try{entry.onProgress?.(params)}catch(error){this.emitError(error)}}}handleCancelled(params){isObject(params)&&isJsonRpcId(params.requestId)&&this.incoming.get(params.requestId)?.abort(params.reason)}armTimeout(id,entry){entry.timer&&clearTimeout(entry.timer),!(!Number.isFinite(entry.timeoutMs)||entry.timeoutMs<=0)&&(entry.timer=setTimeout(()=>{this.cancelPending(id,new McpTimeoutError(entry.timeoutMs),entry.cancellable,"Request timed out")},entry.timeoutMs))}cancelPending(id,error,notifyServer,reason){let entry=this.pending.get(id);entry&&(this.removePending(id,entry),entry.reject(error),notifyServer&&this.transport&&this.transport.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:id,...reason?{reason}:{}}}).catch(sendError=>this.emitError(sendError)))}removePending(id,entry){this.pending.delete(id),entry.timer&&clearTimeout(entry.timer),entry.progressToken!==void 0&&this.progressRequests.delete(entry.progressToken),entry.signal?.removeEventListener("abort",entry.onAbort),entry.sendController.abort()}rejectPending(error){for(let[id,entry]of this.pending)this.removePending(id,entry),entry.reject(error)}handleTransportClose(){this.markClosed(new McpConnectionClosedError)}markClosed(error){let wasClosed=this.state==="closed";this.state="closed",this.rejectPending(error);for(let controller of this.incoming.values())controller.abort(error);if(this.incoming.clear(),!wasClosed)for(let listener of[...this.closeListeners])try{listener()}catch(listenerError){this.emitError(listenerError)}}emitError(error){let normalized=toError(error);for(let listener of this.errorListeners)listener(normalized)}disposeTransportListeners(){for(let dispose of this.disposers.splice(0))dispose()}};var import_cross_spawn=__toESM(require_cross_spawn(),1);import{spawn}from"node:child_process";import process2 from"node:process";var DEFAULT_MAX_MESSAGE_BYTES=16*1024*1024,TransportEvents=class{messageListeners=new Set;errorListeners=new Set;closeListeners=new Set;closeEmitted=!1;onMessage(listener){return this.messageListeners.add(listener),()=>this.messageListeners.delete(listener)}onError(listener){return this.errorListeners.add(listener),()=>this.errorListeners.delete(listener)}onClose(listener){return this.closeListeners.add(listener),()=>this.closeListeners.delete(listener)}emitMessage(message){for(let listener of this.messageListeners)listener(message)}emitError(error){let normalized=toError(error);for(let listener of this.errorListeners)listener(normalized)}emitClose(){if(!this.closeEmitted){this.closeEmitted=!0;for(let listener of this.closeListeners)listener()}}};var DEFAULT_MAX_STDERR_BYTES=64*1024,DEFAULT_CLOSE_TIMEOUT_MS=2e3,STDIN_CLOSE_GRACE_MS=500,USE_PROCESS_GROUPS=process2.platform!=="win32",liveProcessGroups=new Set,exitHookInstalled=!1;function killProcessTree(child,signal){let pid=child.pid;if(process2.platform==="win32"&&pid!==void 0){if(child.exitCode!==null)return;spawn("taskkill",["/pid",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:!0}).on("error",()=>{});return}if(USE_PROCESS_GROUPS&&pid!==void 0)try{process2.kill(-pid,signal);return}catch{}try{child.kill(signal)}catch{}}function installExitHook(){exitHookInstalled||(exitHookInstalled=!0,process2.once("exit",()=>{for(let pid of liveProcessGroups)try{process2.kill(-pid,"SIGTERM")}catch{}}))}var StdioTransport=class extends TransportEvents{options;child;stdoutBuffer=Buffer.alloc(0);stderrBuffer=Buffer.alloc(0);started=!1;closed=!1;constructor(options){super(),this.options=Object.freeze({...options,args:options.args?[...options.args]:void 0})}get pid(){return this.child?.pid}get stderr(){return this.stderrBuffer.toString("utf8")}async start(){if(this.started)throw new Error("MCP stdio transport already started");if(this.closed)throw new McpConnectionClosedError;this.started=!0;let env=this.options.inheritEnv===!1?{...this.options.env}:{...process2.env,...this.options.env},child=(0,import_cross_spawn.default)(this.options.command,this.options.args??[],{cwd:this.options.cwd,env,stdio:["pipe","pipe",this.options.stderr==="inherit"?"inherit":"pipe"],windowsHide:!0,detached:USE_PROCESS_GROUPS});this.child=child;let pid=child.pid;USE_PROCESS_GROUPS&&pid!==void 0&&(installExitHook(),liveProcessGroups.add(pid),child.once("exit",()=>liveProcessGroups.delete(pid))),child.stdout?.on("data",chunk=>this.handleStdout(chunk)),child.stdout?.on("error",error=>this.emitError(error)),child.stdin?.on("error",error=>{this.closed||this.emitError(error)}),child.stderr?.on("data",chunk=>this.handleStderr(chunk)),child.stderr?.on("error",error=>this.emitError(error)),child.on("close",()=>{this.child=void 0,this.stdoutBuffer.toString("utf8").trim()&&this.emitError(new Error("MCP stdio server closed with an incomplete JSON-RPC message")),this.stdoutBuffer=Buffer.alloc(0),this.emitClose()}),await new Promise((resolve,reject)=>{let onSpawn=()=>{child.off("error",onError),resolve()},onError=error=>{child.off("spawn",onSpawn),reject(error)};child.once("spawn",onSpawn),child.once("error",onError)}),child.on("error",error=>{this.closed||this.emitError(error)})}async send(message){let stdin=this.child?.stdin;if(!this.started||this.closed||!stdin?.writable)throw new McpConnectionClosedError;let payload=`${JSON.stringify(message)}
|
|
4
4
|
`;await new Promise((resolve,reject)=>{stdin.write(payload,error=>error?reject(error):resolve())})}async close(){if(this.closed)return;this.closed=!0;let child=this.child;if(!child){this.emitClose();return}if(child.exitCode!==null||child.signalCode!==null){child.stdin?.end();return}let closeTimeoutMs=this.options.closeTimeoutMs??DEFAULT_CLOSE_TIMEOUT_MS;await new Promise(resolve=>{let timers=[];child.once("close",()=>{for(let timer of timers)clearTimeout(timer);killProcessTree(child,"SIGTERM"),resolve()});let grace=Math.min(STDIN_CLOSE_GRACE_MS,closeTimeoutMs);timers.push(setTimeout(()=>killProcessTree(child,"SIGTERM"),grace)),timers.push(setTimeout(()=>killProcessTree(child,"SIGKILL"),grace+closeTimeoutMs)),child.stdin?.end()})}handleStdout(chunk){this.stdoutBuffer=Buffer.concat([this.stdoutBuffer,Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk)]);let maxMessageBytes=this.options.maxMessageBytes??DEFAULT_MAX_MESSAGE_BYTES;for(;;){let newline=this.stdoutBuffer.indexOf(10);if(newline<0){this.stdoutBuffer.length>maxMessageBytes&&(this.stdoutBuffer=Buffer.alloc(0),this.emitError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`)));return}let line=this.stdoutBuffer.subarray(0,newline);if(this.stdoutBuffer=this.stdoutBuffer.subarray(newline+1),line.length>maxMessageBytes){this.emitError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`));continue}let text=line.toString("utf8").replace(/\r$/,"");if(text.trim())try{this.emitMessage(parseJsonRpcMessage(JSON.parse(text)))}catch(error){this.emitError(error)}}}handleStderr(chunk){let buffer=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk),maxStderrBytes=this.options.maxStderrBytes??DEFAULT_MAX_STDERR_BYTES;this.stderrBuffer=Buffer.concat([this.stderrBuffer,buffer]),this.stderrBuffer.length>maxStderrBytes&&(this.stderrBuffer=this.stderrBuffer.subarray(-maxStderrBytes)),this.options.onStderr?.(buffer.toString("utf8"))}};var MAX_ERROR_BODY_BYTES=8*1024,ERROR_MESSAGE_BODY_CHARS=500,DEFAULT_RECONNECT_INITIAL_DELAY_MS=1e3,DEFAULT_RECONNECT_MAX_DELAY_MS=3e4,DEFAULT_RECONNECT_MAX_RETRIES=5;async function consumeSseStream(stream,options){let reader=stream.getReader(),decoder=new TextDecoder,buffered="",eventName,eventId,dataLines=[],dataBytes=0,maxEventBytes=options.maxEventBytes??DEFAULT_MAX_MESSAGE_BYTES,dispatch=()=>{if(dataLines.length===0){eventName=void 0,eventId=void 0;return}let data=dataLines.join(`
|
|
5
5
|
`);options.onEvent({...eventName?{event:eventName}:{},data,...eventId?{id:eventId}:{}}),eventName=void 0,eventId=void 0,dataLines=[],dataBytes=0},processLine=rawLine=>{let line=rawLine.endsWith("\r")?rawLine.slice(0,-1):rawLine;if(line===""){dispatch();return}if(line.startsWith(":"))return;let colon=line.indexOf(":"),field=colon<0?line:line.slice(0,colon),value=colon<0?"":line.slice(colon+1);if(value.startsWith(" ")&&(value=value.slice(1)),field==="data"){if(dataBytes+=Buffer.byteLength(value)+(dataLines.length>0?1:0),dataBytes>maxEventBytes)throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);dataLines.push(value)}else field==="event"?eventName=value:field==="id"&&!value.includes("\0")?(eventId=value,options.onId?.(value)):field==="retry"&&/^\d+$/.test(value)&&options.onRetry?.(Number(value))};try{for(;;){let{done,value}=await reader.read();if(done)break;buffered+=decoder.decode(value,{stream:!0});let newline=buffered.indexOf(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{getBinDir}from"./chunk-
|
|
2
|
+
import{getBinDir}from"./chunk-LHRPMXVI.js";import{existsSync}from"node:fs";import{delimiter,join,win32}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){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 gitBashCandidates(env,exists=existsSync){let paths=[],add=path=>{paths.some(known=>known.toLowerCase()===path.toLowerCase())||paths.push(path)},programFiles=env.ProgramFiles;programFiles&&add(win32.join(programFiles,"Git","bin","bash.exe"));let programFilesX86=env["ProgramFiles(x86)"];programFilesX86&&add(win32.join(programFilesX86,"Git","bin","bash.exe"));let localAppData=env.LOCALAPPDATA;localAppData&&add(win32.join(localAppData,"Programs","Git","bin","bash.exe"));let pathKey=Object.keys(env).find(key=>key.toLowerCase()==="path");for(let entry of(pathKey?env[pathKey]??"":"").split(";")){let dir=entry.trim().replace(/^"(.*)"$/,"$1");dir&&exists(win32.join(dir,"git.exe"))&&add(win32.join(dir,"..","bin","bash.exe"))}return paths}function getShellConfig(customShellPath){if(customShellPath){if(existsSync(customShellPath))return getBashShellConfig(customShellPath);throw new Error(`Custom shell path not found: ${customShellPath}`)}if(process.platform==="win32"){let paths=gitBashCandidates(process.env);for(let path of paths)if(existsSync(path))return getBashShellConfig(path);let bashOnPath2=findExecutableOnPath("bash.exe");if(bashOnPath2)return getBashShellConfig(bashOnPath2);throw new Error(`No bash shell found. Options:
|
|
3
3
|
1. Install Git for Windows: https://git-scm.com/download/win
|
|
4
4
|
2. Add your bash to PATH (Cygwin, MSYS2, etc.)
|
|
5
5
|
3. Set shellPath in settings.json
|